File:  [LON-CAPA] / loncom / interface / domainprefs.pm
Revision 1.160.6.123: download - view: text, annotated - select for diffs
Wed Jul 3 21:16:32 2024 UTC (2 weeks, 5 days ago) by raeburn
Branches: version_2_11_X
Diff to branchpoint 1.160: preferred, unified
- For 2.11
  Backport 1.411, 1.420 (part), 1.433

    1: # The LearningOnline Network with CAPA
    2: # Handler to set domain-wide configuration settings
    3: #
    4: # $Id: domainprefs.pm,v 1.160.6.123 2024/07/03 21:16:32 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, and textbook).  In each case the radio buttons 
  108: 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 File::Copy;
  174: use Locale::Language;
  175: use DateTime::TimeZone;
  176: use DateTime::Locale;
  177: use Net::CIDR;
  178: 
  179: my $registered_cleanup;
  180: my $modified_urls;
  181: 
  182: sub handler {
  183:     my $r=shift;
  184:     if ($r->header_only) {
  185:         &Apache::loncommon::content_type($r,'text/html');
  186:         $r->send_http_header;
  187:         return OK;
  188:     }
  189: 
  190:     my $context = 'domain';
  191:     my $dom = $env{'request.role.domain'};
  192:     my $domdesc = &Apache::lonnet::domain($dom,'description');
  193:     if (&Apache::lonnet::allowed('mau',$dom)) {
  194:         &Apache::loncommon::content_type($r,'text/html');
  195:         $r->send_http_header;
  196:     } else {
  197:         $env{'user.error.msg'}=
  198:         "/adm/domainprefs:mau:0:0:Cannot modify domain settings";
  199:         return HTTP_NOT_ACCEPTABLE;
  200:     }
  201: 
  202:     $registered_cleanup=0;
  203:     @{$modified_urls}=();
  204: 
  205:     &Apache::lonhtmlcommon::clear_breadcrumbs();
  206:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
  207:                                             ['phase','actions']);
  208:     my $phase = 'pickactions';
  209:     if ( exists($env{'form.phase'}) ) {
  210:         $phase = $env{'form.phase'};
  211:     }
  212:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
  213:     my %domconfig =
  214:       &Apache::lonnet::get_dom('configuration',['login','rolecolors',
  215:                 'quotas','autoenroll','autoupdate','autocreate',
  216:                 'directorysrch','usercreation','usermodification',
  217:                 'contacts','defaults','scantron','coursecategories',
  218:                 'serverstatuses','requestcourses','helpsettings',
  219:                 'coursedefaults','usersessions','loadbalancing',
  220:                 'requestauthor','selfenrollment','inststatus',
  221:                 'passwords','wafproxy','ipaccess'],$dom);
  222:     my @prefs_order = ('rolecolors','login','ipaccess','defaults','wafproxy','passwords',
  223:                        'quotas','autoenroll','autoupdate','autocreate','directorysrch',
  224:                        'contacts','usercreation','selfcreation','usermodification',
  225:                        'scantron','requestcourses','requestauthor','coursecategories',
  226:                        'serverstatuses','helpsettings','coursedefaults',
  227:                        'selfenrollment','usersessions');
  228:     my %existing;
  229:     if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
  230:         %existing = %{$domconfig{'loadbalancing'}};
  231:     }
  232:     if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
  233:         push(@prefs_order,'loadbalancing');
  234:     }
  235:     my %prefs = (
  236:         'rolecolors' =>
  237:                    { text => 'Default color schemes',
  238:                      help => 'Domain_Configuration_Color_Schemes',
  239:                      header => [{col1 => 'Student Settings',
  240:                                  col2 => '',},
  241:                                 {col1 => 'Coordinator Settings',
  242:                                  col2 => '',},
  243:                                 {col1 => 'Author Settings',
  244:                                  col2 => '',},
  245:                                 {col1 => 'Administrator Settings',
  246:                                  col2 => '',}],
  247:                       print => \&print_rolecolors,
  248:                       modify => \&modify_rolecolors,
  249:                     },
  250:         'login' =>
  251:                     { text => 'Log-in page options',
  252:                       help => 'Domain_Configuration_Login_Page',
  253:                       header => [{col1 => 'Log-in Page Items',
  254:                                   col2 => '',},
  255:                                  {col1 => 'Log-in Help',
  256:                                   col2 => 'Value'},
  257:                                  {col1 => 'Custom HTML in document head',
  258:                                   col2 => 'Value'},
  259:                                  {col1 => 'SSO',
  260:                                   col2 => 'Dual login: SSO and non-SSO options'},
  261:                                 ],
  262:                       print => \&print_login,
  263:                       modify => \&modify_login,
  264:                     },
  265:         'defaults' => 
  266:                     { text => 'Default authentication/language/timezone/portal/types',
  267:                       help => 'Domain_Configuration_LangTZAuth',
  268:                       header => [{col1 => 'Setting',
  269:                                   col2 => 'Value'},
  270:                                  {col1 => 'Institutional user types',
  271:                                   col2 => 'Name displayed'},
  272:                                  {col1 => 'Mapping for missing usernames via standard log-in',
  273:                                   col2 => 'Rules in use'}],
  274:                       print => \&print_defaults,
  275:                       modify => \&modify_defaults,
  276:                     },
  277:         'wafproxy' =>
  278:                     { text => 'Web Application Firewall/Reverse Proxy',
  279:                       help => 'Domain_Configuration_WAF_Proxy',
  280:                       header => [{col1 => 'Domain(s)',
  281:                                   col2 => 'Servers and WAF/Reverse Proxy alias(es)',
  282:                                  },
  283:                                  {col1 => 'Domain(s)',
  284:                                   col2 => 'WAF Configuration',}],
  285:                       print => \&print_wafproxy,
  286:                       modify => \&modify_wafproxy,
  287:                     },
  288:         'passwords' =>
  289:                     { text => 'Passwords (Internal authentication)',
  290:                       help => 'Domain_Configuration_Passwords',
  291:                       header => [{col1 => 'Resetting Forgotten Password',
  292:                                   col2 => 'Settings'},
  293:                                  {col1 => 'Encryption of Stored Passwords (Internal Auth)',
  294:                                   col2 => 'Settings'},
  295:                                  {col1 => 'Rules for LON-CAPA Passwords',
  296:                                   col2 => 'Settings'},
  297:                                  {col1 => 'Course Owner Changing Student Passwords',
  298:                                   col2 => 'Settings'}],
  299:                       print => \&print_passwords,
  300:                       modify => \&modify_passwords,
  301:                     },
  302:         'quotas' => 
  303:                     { text => 'Blogs, personal web pages, webDAV/quotas, portfolios',
  304:                       help => 'Domain_Configuration_Quotas',
  305:                       header => [{col1 => 'User affiliation',
  306:                                   col2 => 'Available tools',
  307:                                   col3 => 'Quotas, MB; (Authoring requires role)',}],
  308:                       print => \&print_quotas,
  309:                       modify => \&modify_quotas,
  310:                     },
  311:         'autoenroll' =>
  312:                    { text => 'Auto-enrollment settings',
  313:                      help => 'Domain_Configuration_Auto_Enrollment',
  314:                      header => [{col1 => 'Configuration setting',
  315:                                  col2 => 'Value(s)'}],
  316:                      print => \&print_autoenroll,
  317:                      modify => \&modify_autoenroll,
  318:                    },
  319:         'autoupdate' => 
  320:                    { text => 'Auto-update settings',
  321:                      help => 'Domain_Configuration_Auto_Updates',
  322:                      header => [{col1 => 'Setting',
  323:                                  col2 => 'Value',},
  324:                                 {col1 => 'Setting',
  325:                                  col2 => 'Affiliation'},
  326:                                 {col1 => 'User population',
  327:                                  col2 => 'Updatable user data'}],
  328:                      print => \&print_autoupdate,
  329:                      modify => \&modify_autoupdate,
  330:                   },
  331:         'autocreate' => 
  332:                   { text => 'Auto-course creation settings',
  333:                      help => 'Domain_Configuration_Auto_Creation',
  334:                      header => [{col1 => 'Configuration Setting',
  335:                                  col2 => 'Value',}],
  336:                      print => \&print_autocreate,
  337:                      modify => \&modify_autocreate,
  338:                   },
  339:         'directorysrch' => 
  340:                   { text => 'Directory searches',
  341:                     help => 'Domain_Configuration_InstDirectory_Search',
  342:                     header => [{col1 => 'Institutional Directory Setting',
  343:                                 col2 => 'Value',},
  344:                                {col1 => 'LON-CAPA Directory Setting',
  345:                                 col2 => 'Value',}],
  346:                     print => \&print_directorysrch,
  347:                     modify => \&modify_directorysrch,
  348:                   },
  349:         'contacts' =>
  350:                   { text => 'E-mail addresses and helpform',
  351:                     help => 'Domain_Configuration_Contact_Info',
  352:                     header => [{col1 => 'Default e-mail addresses',
  353:                                 col2 => 'Value',},
  354:                                {col1 => 'Recipient(s) for notifications',
  355:                                 col2 => 'Value',},
  356:                                {col1 => 'Nightly status check e-mail',
  357:                                 col2 => 'Settings',},
  358:                                {col1 => 'Ask helpdesk form settings',
  359:                                 col2 => 'Value',},],
  360:                     print => \&print_contacts,
  361:                     modify => \&modify_contacts,
  362:                   },
  363:         'usercreation' => 
  364:                   { text => 'User creation',
  365:                     help => 'Domain_Configuration_User_Creation',
  366:                     header => [{col1 => 'Format rule type',
  367:                                 col2 => 'Format rules in force'},
  368:                                {col1 => 'User account creation',
  369:                                 col2 => 'Usernames which may be created',},
  370:                                {col1 => 'Context',
  371:                                 col2 => 'Assignable authentication types'}],
  372:                     print => \&print_usercreation,
  373:                     modify => \&modify_usercreation,
  374:                   },
  375:         'selfcreation' => 
  376:                   { text => 'Users self-creating accounts',
  377:                     help => 'Domain_Configuration_Self_Creation', 
  378:                     header => [{col1 => 'Self-creation with institutional username',
  379:                                 col2 => 'Enabled?'},
  380:                                {col1 => 'Institutional user type (login/SSO self-creation)',
  381:                                 col2 => 'Information user can enter'},
  382:                                {col1 => 'Self-creation with e-mail verification',
  383:                                 col2 => 'Settings'}],
  384:                     print => \&print_selfcreation,
  385:                     modify => \&modify_selfcreation,
  386:                   },
  387:         'usermodification' =>
  388:                   { text => 'User modification',
  389:                     help => 'Domain_Configuration_User_Modification',
  390:                     header => [{col1 => 'Target user has role',
  391:                                 col2 => 'User information updatable in author context'},
  392:                                {col1 => 'Target user has role',
  393:                                 col2 => 'User information updatable in course context'}],
  394:                     print => \&print_usermodification,
  395:                     modify => \&modify_usermodification,
  396:                   },
  397:         'scantron' =>
  398:                   { text => 'Bubblesheet format',
  399:                     help => 'Domain_Configuration_Scantron_Format',
  400:                     header => [ {col1 => 'Bubblesheet format file',
  401:                                  col2 => ''},
  402:                                 {col1 => 'Bubblesheet data upload formats',
  403:                                  col2 => 'Settings'}],
  404:                     print => \&print_scantron,
  405:                     modify => \&modify_scantron,
  406:                   },
  407:         'requestcourses' => 
  408:                  {text => 'Request creation of courses',
  409:                   help => 'Domain_Configuration_Request_Courses',
  410:                   header => [{col1 => 'User affiliation',
  411:                               col2 => 'Availability/Processing of requests',},
  412:                              {col1 => 'Setting',
  413:                               col2 => 'Value'},
  414:                              {col1 => 'Available textbooks',
  415:                               col2 => ''},
  416:                              {col1 => 'Available templates',
  417:                               col2 => ''},
  418:                              {col1 => 'Validation (not official courses)',
  419:                               col2 => 'Value'},],
  420:                   print => \&print_quotas,
  421:                   modify => \&modify_quotas,
  422:                  },
  423:         'requestauthor' =>
  424:                  {text => 'Request Authoring Space',
  425:                   help => 'Domain_Configuration_Request_Author',
  426:                   header => [{col1 => 'User affiliation',
  427:                               col2 => 'Availability/Processing of requests',},
  428:                              {col1 => 'Setting',
  429:                               col2 => 'Value'}],
  430:                   print => \&print_quotas,
  431:                   modify => \&modify_quotas,
  432:                  },
  433:         'coursecategories' =>
  434:                   { text => 'Cataloging of courses/communities',
  435:                     help => 'Domain_Configuration_Cataloging_Courses',
  436:                     header => [{col1 => 'Catalog type/availability',
  437:                                 col2 => '',},
  438:                                {col1 => 'Category settings for standard catalog',
  439:                                 col2 => '',},
  440:                                {col1 => 'Categories',
  441:                                 col2 => '',
  442:                                }],
  443:                     print => \&print_coursecategories,
  444:                     modify => \&modify_coursecategories,
  445:                   },
  446:         'serverstatuses' =>
  447:                  {text   => 'Access to server status pages',
  448:                   help   => 'Domain_Configuration_Server_Status',
  449:                   header => [{col1 => 'Status Page',
  450:                               col2 => 'Other named users',
  451:                               col3 => 'Specific IPs',
  452:                             }],
  453:                   print => \&print_serverstatuses,
  454:                   modify => \&modify_serverstatuses,
  455:                  },
  456:         'helpsettings' =>
  457:                  {text   => 'Support settings',
  458:                   help   => 'Domain_Configuration_Help_Settings',
  459:                   header => [{col1 => 'Help Page Settings (logged-in users)',
  460:                               col2 => 'Value'},
  461:                              {col1 => 'Helpdesk Roles',
  462:                               col2 => 'Settings'},],
  463:                   print  => \&print_helpsettings,
  464:                   modify => \&modify_helpsettings,
  465:                  },
  466:         'coursedefaults' => 
  467:                  {text => 'Course/Community defaults',
  468:                   help => 'Domain_Configuration_Course_Defaults',
  469:                   header => [{col1 => 'Defaults which can be overridden in each course by a CC',
  470:                               col2 => 'Value',},
  471:                              {col1 => 'Defaults which can be overridden for each course by a DC',
  472:                               col2 => 'Value',},],
  473:                   print => \&print_coursedefaults,
  474:                   modify => \&modify_coursedefaults,
  475:                  },
  476:         'selfenrollment' => 
  477:                  {text   => 'Self-enrollment in Course/Community',
  478:                   help   => 'Domain_Configuration_Selfenrollment',
  479:                   header => [{col1 => 'Configuration Rights',
  480:                               col2 => 'Configured by Course Personnel or Domain Coordinator?'},
  481:                              {col1 => 'Defaults',
  482:                               col2 => 'Value'},
  483:                              {col1 => 'Self-enrollment validation (optional)',
  484:                               col2 => 'Value'},],
  485:                   print => \&print_selfenrollment,
  486:                   modify => \&modify_selfenrollment,
  487:                  },
  488:         'usersessions' =>
  489:                  {text  => 'User session hosting/offloading',
  490:                   help  => 'Domain_Configuration_User_Sessions',
  491:                   header => [{col1 => 'Domain server',
  492:                               col2 => 'Servers to offload sessions to when busy'},
  493:                              {col1 => 'Hosting of users from other domains',
  494:                               col2 => 'Rules'},
  495:                              {col1 => "Hosting domain's own users elsewhere",
  496:                               col2 => 'Rules'}],
  497:                   print => \&print_usersessions,
  498:                   modify => \&modify_usersessions,
  499:                  },
  500:         'loadbalancing' =>
  501:                  {text  => 'Dedicated Load Balancer(s)',
  502:                   help  => 'Domain_Configuration_Load_Balancing',
  503:                   header => [{col1 => 'Balancers',
  504:                               col2 => 'Default destinations',
  505:                               col3 => 'User affiliation',
  506:                               col4 => 'Overrides'},
  507:                             ],
  508:                   print => \&print_loadbalancing,
  509:                   modify => \&modify_loadbalancing,
  510:                  },
  511:          'ipaccess' =>
  512:                        {text => 'IP-based access control',
  513:                         help => 'Domain_Configuration_IP_Access',
  514:                         header => [{col1 => 'Setting',
  515:                                     col2 => 'Value'},],
  516:                         print  => \&print_ipaccess,
  517:                         modify => \&modify_ipaccess,
  518:                        },
  519:     );
  520:     if (keys(%servers) > 1) {
  521:         $prefs{'login'}  = { text   => 'Log-in page options',
  522:                              help   => 'Domain_Configuration_Login_Page',
  523:                             header => [{col1 => 'Log-in Service',
  524:                                         col2 => 'Server Setting',},
  525:                                        {col1 => 'Log-in Page Items',
  526:                                         col2 => ''},
  527:                                        {col1 => 'Log-in Help',
  528:                                         col2 => 'Value'},
  529:                                        {col1 => 'Custom HTML in document head',
  530:                                         col2 => 'Value'},
  531:                                        {col1 => 'SSO',
  532:                                         col2 => 'Dual login: SSO and non-SSO options'},
  533:                                       ],
  534:                             print => \&print_login,
  535:                             modify => \&modify_login,
  536:                            };
  537:     }
  538: 
  539:     my @roles = ('student','coordinator','author','admin');
  540:     my @actions = &Apache::loncommon::get_env_multiple('form.actions');
  541:     &Apache::lonhtmlcommon::add_breadcrumb
  542:     ({href=>"javascript:changePage(document.$phase,'pickactions')",
  543:       text=>"Settings to display/modify"});
  544:     my $confname = $dom.'-domainconfig';
  545: 
  546:     if ($phase eq 'process') {
  547:         my $result = &Apache::lonconfigsettings::make_changes($r,$dom,$phase,$context,\@prefs_order,
  548:                                                               \%prefs,\%domconfig,$confname,\@roles);
  549:         if ((ref($result) eq 'HASH') && (keys(%{$result}))) {
  550:             $r->rflush();
  551:             &devalidate_remote_domconfs($dom,$result);
  552:         }
  553:     } elsif ($phase eq 'display') {
  554:         my $js = &recaptcha_js().
  555:                  &toggle_display_js();
  556:         if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
  557:             my ($othertitle,$usertypes,$types) =
  558:                 &Apache::loncommon::sorted_inst_types($dom);
  559:             $js .= &lonbalance_targets_js($dom,$types,\%servers,
  560:                                           $domconfig{'loadbalancing'}).
  561:                    &new_spares_js().
  562:                    &common_domprefs_js().
  563:                    &Apache::loncommon::javascript_array_indexof();
  564:         }
  565:         if (grep(/^requestcourses$/,@actions)) {
  566:             my $javascript_validations;
  567:             my $coursebrowserjs=&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}); 
  568:             $js .= <<END;
  569: <script type="text/javascript">
  570: $javascript_validations
  571: </script>
  572: $coursebrowserjs
  573: END
  574:         } elsif (grep(/^ipaccess$/,@actions)) {
  575:             $js .= &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
  576:         }
  577:         if (grep(/^selfcreation$/,@actions)) {
  578:             $js .= &selfcreate_javascript();
  579:         }
  580:         if (grep(/^contacts$/,@actions)) {
  581:             $js .= &contacts_javascript();
  582:         }
  583:         if (grep(/^scantron$/,@actions)) {
  584:             $js .= &scantron_javascript();
  585:         }
  586:         &Apache::lonconfigsettings::display_settings($r,$dom,$phase,$context,\@prefs_order,\%prefs,\%domconfig,$confname,$js);
  587:     } else {
  588: # check if domconfig user exists for the domain.
  589:         my $servadm = $r->dir_config('lonAdmEMail');
  590:         my ($configuserok,$author_ok,$switchserver) =
  591:             &config_check($dom,$confname,$servadm);
  592:         unless ($configuserok eq 'ok') {
  593:             &Apache::lonconfigsettings::print_header($r,$phase,$context);
  594:             $r->print(&mt('The domain configuration user "[_1]" has yet to be created.',
  595:                           $confname).
  596:                       '<br />'
  597:             );
  598:             if ($switchserver) {
  599:                 $r->print(&mt('Ordinarily, that domain configuration user is created when the ./UPDATE script is run to install LON-CAPA for the first time.').
  600:                           '<br />'.
  601:                           &mt('However, that does not apply when new domains are added to a multi-domain server, and ./UPDATE has not been run recently.').
  602:                           '<br />'.
  603:                           &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).
  604:                           '<br />'.
  605:                           &mt('To do that now, use the following link: [_1]',$switchserver)
  606:                 );
  607:             } else {
  608:                 $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.').
  609:                           '<br />'.
  610:                           &mt('Once that is done, you will be able to use the web-based "Set domain configuration" to configure the domain')
  611:                 );
  612:             }
  613:             $r->print(&Apache::loncommon::end_page());
  614:             return OK;
  615:         }
  616:         if (keys(%domconfig) == 0) {
  617:             my $primarylibserv = &Apache::lonnet::domain($dom,'primary');
  618:             my @ids=&Apache::lonnet::current_machine_ids();
  619:             if (!grep(/^\Q$primarylibserv\E$/,@ids)) {
  620:                 my %designhash = &Apache::loncommon::get_domainconf($dom);
  621:                 my @loginimages = ('img','logo','domlogo','login');
  622:                 my $custom_img_count = 0;
  623:                 foreach my $img (@loginimages) {
  624:                     if ($designhash{$dom.'.login.'.$img} ne '') {
  625:                         $custom_img_count ++;
  626:                     }
  627:                 }
  628:                 foreach my $role (@roles) {
  629:                     if ($designhash{$dom.'.'.$role.'.img'} ne '') {
  630:                         $custom_img_count ++;
  631:                     }
  632:                 }
  633:                 if ($custom_img_count > 0) {
  634:                     &Apache::lonconfigsettings::print_header($r,$phase,$context);
  635:                     my $switch_server = &check_switchserver($dom,$confname);
  636:                     $r->print(
  637:     &mt('Domain configuration settings have yet to be saved for this domain via the web-based domain preferences interface.').'<br />'.
  638:     &mt("While this remains so, you must switch to the domain's primary library server in order to update settings.").'<br /><br />'.
  639:     &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 />'.
  640:     &mt("However, you will still need to switch to the domain's primary library server to upload new images or logos.").'<br /><br />');
  641:                     if ($switch_server) {
  642:                         $r->print($switch_server.' '.&mt('to primary library server for domain: [_1]',$dom));
  643:                     }
  644:                     $r->print(&Apache::loncommon::end_page());
  645:                     return OK;
  646:                 }
  647:             }
  648:         }
  649:         &Apache::lonconfigsettings::display_choices($r,$phase,$context,\@prefs_order,\%prefs);
  650:     }
  651:     return OK;
  652: }
  653: 
  654: sub process_changes {
  655:     my ($r,$dom,$confname,$action,$roles,$values,$lastactref) = @_;
  656:     my %domconfig;
  657:     if (ref($values) eq 'HASH') {
  658:         %domconfig = %{$values};
  659:     }
  660:     my $output;
  661:     if ($action eq 'login') {
  662:         $output = &modify_login($r,$dom,$confname,$lastactref,%domconfig);
  663:     } elsif ($action eq 'rolecolors') {
  664:         $output = &modify_rolecolors($r,$dom,$confname,$roles,
  665:                                      $lastactref,%domconfig);
  666:     } elsif ($action eq 'quotas') {
  667:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  668:     } elsif ($action eq 'autoenroll') {
  669:         $output = &modify_autoenroll($dom,$lastactref,%domconfig);
  670:     } elsif ($action eq 'autoupdate') {
  671:         $output = &modify_autoupdate($dom,%domconfig);
  672:     } elsif ($action eq 'autocreate') {
  673:         $output = &modify_autocreate($dom,%domconfig);
  674:     } elsif ($action eq 'directorysrch') {
  675:         $output = &modify_directorysrch($dom,$lastactref,%domconfig);
  676:     } elsif ($action eq 'usercreation') {
  677:         $output = &modify_usercreation($dom,%domconfig);
  678:     } elsif ($action eq 'selfcreation') {
  679:         $output = &modify_selfcreation($dom,$lastactref,%domconfig);
  680:     } elsif ($action eq 'usermodification') {
  681:         $output = &modify_usermodification($dom,%domconfig);
  682:     } elsif ($action eq 'contacts') {
  683:         $output = &modify_contacts($dom,$lastactref,%domconfig);
  684:     } elsif ($action eq 'defaults') {
  685:         $output = &modify_defaults($dom,$lastactref,%domconfig);
  686:     } elsif ($action eq 'scantron') {
  687:         $output = &modify_scantron($r,$dom,$confname,$lastactref,%domconfig);
  688:     } elsif ($action eq 'coursecategories') {
  689:         $output = &modify_coursecategories($dom,$lastactref,%domconfig);
  690:     } elsif ($action eq 'serverstatuses') {
  691:         $output = &modify_serverstatuses($dom,%domconfig);
  692:     } elsif ($action eq 'requestcourses') {
  693:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  694:     } elsif ($action eq 'requestauthor') {
  695:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  696:     } elsif ($action eq 'helpsettings') {
  697:         $output = &modify_helpsettings($r,$dom,$confname,$lastactref,%domconfig);
  698:     } elsif ($action eq 'coursedefaults') {
  699:         $output = &modify_coursedefaults($dom,$lastactref,%domconfig);
  700:     } elsif ($action eq 'selfenrollment') {
  701:         $output = &modify_selfenrollment($dom,$lastactref,%domconfig)
  702:     } elsif ($action eq 'usersessions') {
  703:         $output = &modify_usersessions($dom,$lastactref,%domconfig);
  704:     } elsif ($action eq 'loadbalancing') {
  705:         $output = &modify_loadbalancing($dom,%domconfig);
  706:     } elsif ($action eq 'passwords') {
  707:         $output = &modify_passwords($r,$dom,$confname,$lastactref,%domconfig);
  708:     } elsif ($action eq 'wafproxy') {
  709:         $output = &modify_wafproxy($dom,$action,$lastactref,%domconfig);
  710:     } elsif ($action eq 'ipaccess') {
  711:         $output = &modify_ipaccess($dom,$lastactref,%domconfig);
  712:     }
  713:     return $output;
  714: }
  715: 
  716: sub print_config_box {
  717:     my ($r,$dom,$confname,$phase,$action,$item,$settings) = @_;
  718:     my $rowtotal = 0;
  719:     my $output;
  720:     if ($action eq 'coursecategories') {
  721:         $output = &coursecategories_javascript($settings);
  722:     } elsif ($action eq 'defaults') {
  723:         $output = &defaults_javascript($settings); 
  724:     } elsif ($action eq 'passwords') {
  725:         $output = &passwords_javascript();
  726:     } elsif ($action eq 'helpsettings') {
  727:         my (%privs,%levelscurrent);
  728:         my %full=();
  729:         my %levels=(
  730:                      course => {},
  731:                      domain => {},
  732:                      system => {},
  733:                    );
  734:         my $context = 'domain';
  735:         my $crstype = 'Course';
  736:         my $formname = 'display';
  737:         &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
  738:         my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
  739:         $output =
  740:             &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,\%full,
  741:                                                       \@templateroles);
  742:     } elsif ($action eq 'wafproxy') {
  743:         $output .= &wafproxy_javascript($dom);
  744:     } elsif ($action eq 'autoupdate') {
  745:         $output .= &autoupdate_javascript();
  746:     } elsif ($action eq 'autoenroll') {
  747:         $output .= &autoenroll_javascript();
  748:     } elsif ($action eq 'login') {
  749:         $output .= &saml_javascript();
  750:     } elsif ($action eq 'ipaccess') {
  751:         $output .= &ipaccess_javascript($settings);
  752:     }
  753:     $output .=
  754:          '<table class="LC_nested_outer">
  755:           <tr>
  756:            <th class="LC_left_item LC_middle"><span class="LC_nobreak">'.
  757:            &mt($item->{text}).'&nbsp;'.
  758:            &Apache::loncommon::help_open_topic($item->{'help'}).'</span></th>'."\n".
  759:           '</tr>';
  760:     $rowtotal ++;
  761:     my $numheaders = 1;
  762:     if (ref($item->{'header'}) eq 'ARRAY') {
  763:         $numheaders = scalar(@{$item->{'header'}});
  764:     }
  765:     if ($numheaders > 1) {
  766:         my $colspan = '';
  767:         my $rightcolspan = '';
  768:         my $leftnobr = '';  
  769:         if (($action eq 'rolecolors') || ($action eq 'defaults') ||
  770:             ($action eq 'directorysrch') ||
  771:             (($action eq 'login') && ($numheaders < 5))) {
  772:             $colspan = ' colspan="2"';
  773:         }
  774:         if ($action eq 'usersessions') {
  775:             $rightcolspan = ' colspan="3"'; 
  776:         }
  777:         if ($action eq 'passwords') {
  778:             $leftnobr = ' LC_nobreak';
  779:         }
  780:         $output .= '
  781:           <tr>
  782:            <td>
  783:             <table class="LC_nested">
  784:              <tr class="LC_info_row">
  785:               <td class="LC_left_item'.$leftnobr.'"'.$colspan.'>'.&mt($item->{'header'}->[0]->{'col1'}).'</td>
  786:               <td class="LC_right_item"'.$rightcolspan.'>'.&mt($item->{'header'}->[0]->{'col2'}).'</td>
  787:              </tr>';
  788:         $rowtotal ++;
  789:         if (($action eq 'autoupdate') || ($action eq 'usercreation') || ($action eq 'selfcreation') ||
  790:             ($action eq 'usermodification') || ($action eq 'defaults') || ($action eq 'coursedefaults') ||
  791:             ($action eq 'selfenrollment') || ($action eq 'usersessions') || ($action eq 'directorysrch') ||
  792:             ($action eq 'helpsettings') || ($action eq 'contacts') || ($action eq 'wafproxy')) {
  793:             $output .= $item->{'print'}->('top',$dom,$settings,\$rowtotal);
  794:         } elsif ($action eq 'passwords') {
  795:             $output .= $item->{'print'}->('top',$dom,$confname,$settings,\$rowtotal);
  796:         } elsif ($action eq 'coursecategories') {
  797:             $output .= $item->{'print'}->('top',$dom,$item,$settings,\$rowtotal);
  798:         } elsif ($action eq 'scantron') {
  799:             $output .= $item->{'print'}->($r,'top',$dom,$confname,$settings,\$rowtotal);
  800:         } elsif ($action eq 'login') {
  801:             if ($numheaders == 5) {
  802:                 $colspan = ' colspan="2"';
  803:                 $output .= &print_login('service',$dom,$confname,$phase,$settings,\$rowtotal);
  804:             } else {
  805:                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal);
  806:             }
  807:         } elsif (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
  808:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
  809:         } elsif ($action eq 'rolecolors') {
  810:             $output .= &print_rolecolors($phase,'student',$dom,$confname,$settings,\$rowtotal);
  811:         }
  812:         $output .= '
  813:            </table>
  814:           </td>
  815:          </tr>
  816:          <tr>
  817:            <td>
  818:             <table class="LC_nested">
  819:              <tr class="LC_info_row">
  820:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col1'}).'</td>
  821:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col2'}).'</td>
  822:              </tr>';
  823:             $rowtotal ++;
  824:         if (($action eq 'autoupdate') || ($action eq 'usercreation') ||
  825:             ($action eq 'selfcreation') || ($action eq 'selfenrollment') ||
  826:             ($action eq 'usersessions') || ($action eq 'coursecategories') ||
  827:             ($action eq 'contacts') || ($action eq 'passwords') || ($action eq 'defaults')) {
  828:             if ($action eq 'coursecategories') {
  829:                 $output .= &print_coursecategories('middle',$dom,$item,$settings,\$rowtotal);
  830:                 $colspan = ' colspan="2"';
  831:             } elsif ($action eq 'passwords') {
  832:                 $output .= $item->{'print'}->('middle',$dom,$confname,$settings,\$rowtotal);
  833:             } else {
  834:                 $output .= $item->{'print'}->('middle',$dom,$settings,\$rowtotal);
  835:             }
  836:             $output .= '
  837:            </table>
  838:           </td>
  839:          </tr>
  840:          <tr>
  841:            <td>
  842:             <table class="LC_nested">
  843:              <tr class="LC_info_row">
  844:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
  845:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
  846:              </tr>'."\n";
  847:             if ($action eq 'coursecategories') {
  848:                 $output .= &print_coursecategories('bottom',$dom,$item,$settings,\$rowtotal);
  849:             } elsif (($action eq 'contacts') || ($action eq 'passwords')) {
  850:                 if ($action eq 'passwords') {
  851:                     $output .= $item->{'print'}->('lower',$dom,$confname,$settings,\$rowtotal);
  852:                 } else {
  853:                     $output .= $item->{'print'}->('lower',$dom,$settings,\$rowtotal);
  854:                 }
  855:                 $output .= '
  856:              </tr>
  857:             </table>
  858:            </td>
  859:           </tr>
  860:           <tr>
  861:            <td>
  862:             <table class="LC_nested">
  863:              <tr class="LC_info_row">
  864:               <td class="LC_left_item'.$leftnobr.'"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
  865:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td></tr>'."\n";
  866:                 if ($action eq 'passwords') {
  867:                     $output .= $item->{'print'}->('bottom',$dom,$confname,$settings,\$rowtotal);
  868:                 } else {
  869:                     $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
  870:                 }
  871:                 $output .= '
  872:             </table>
  873:           </td>
  874:          </tr>
  875:          <tr>';
  876:             } else {
  877:                 $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
  878:             }
  879:             $rowtotal ++;
  880:         } elsif (($action eq 'usermodification') || ($action eq 'coursedefaults') ||
  881:                  ($action eq 'directorysrch') || ($action eq 'helpsettings') ||
  882:                  ($action eq 'wafproxy')) {
  883:             $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
  884:         } elsif ($action eq 'scantron') {
  885:             $output .= $item->{'print'}->($r,'bottom',$dom,$confname,$settings,\$rowtotal);
  886:         } elsif ($action eq 'login') {
  887:             if ($numheaders == 5) {
  888:                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal).'
  889:            </table>
  890:           </td>
  891:          </tr>
  892:          <tr>
  893:            <td>
  894:             <table class="LC_nested">
  895:              <tr class="LC_info_row">
  896:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
  897:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td></tr>'.
  898:                        &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
  899:                 $rowtotal ++;
  900:             } else {
  901:                 $output .= &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
  902:             }
  903:             $output .= '
  904:            </table>
  905:           </td>
  906:          </tr>
  907:          <tr>
  908:            <td>
  909:             <table class="LC_nested">
  910:              <tr class="LC_info_row">';
  911:             if ($numheaders == 5) {
  912:                 $output .= '
  913:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
  914:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
  915:              </tr>';
  916:             } else {
  917:                 $output .= '
  918:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
  919:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
  920:              </tr>';
  921:             }
  922:             $rowtotal ++;
  923:             $output .= &print_login('headtag',$dom,$confname,$phase,$settings,\$rowtotal).'
  924:            </table>
  925:           </td>
  926:          </tr>
  927:          <tr>
  928:            <td>
  929:             <table class="LC_nested">
  930:              <tr class="LC_info_row">';
  931:             if ($numheaders == 5) {
  932:                 $output .= '
  933:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[4]->{'col1'}).'</td>
  934:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[4]->{'col2'}).'</td>
  935:              </tr>';
  936:             } else {
  937:                 $output .= '
  938:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
  939:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
  940:              </tr>';
  941:             }
  942:             $rowtotal ++;
  943:             $output .= &print_login('saml',$dom,$confname,$phase,$settings,\$rowtotal);
  944:         } elsif ($action eq 'requestcourses') {
  945:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
  946:             $rowtotal ++;
  947:             $output .= &print_studentcode($settings,\$rowtotal).'
  948:            </table>
  949:           </td>
  950:          </tr>
  951:          <tr>
  952:            <td>
  953:             <table class="LC_nested">
  954:              <tr class="LC_info_row">
  955:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
  956:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td> </tr>'.
  957:                        &textbookcourses_javascript($settings).
  958:                        &print_textbookcourses($dom,'textbooks',$settings,\$rowtotal).'
  959:             </table>
  960:            </td>
  961:           </tr>
  962:          <tr>
  963:            <td>
  964:             <table class="LC_nested">
  965:              <tr class="LC_info_row">
  966:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
  967:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td> </tr>'.
  968:                        &print_textbookcourses($dom,'templates',$settings,\$rowtotal).'
  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.' valign="top">'.&mt($item->{'header'}->[4]->{'col1'}).'</td>
  977:               <td class="LC_right_item" valign="top">'.&mt($item->{'header'}->[4]->{'col2'}).'</td>
  978:              </tr>'.
  979:             &print_validation_rows('requestcourses',$dom,$settings,\$rowtotal);
  980:         } elsif ($action eq 'requestauthor') {
  981:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
  982:             $rowtotal ++;
  983:         } elsif ($action eq 'rolecolors') {
  984:             $output .= &print_rolecolors($phase,'coordinator',$dom,$confname,$settings,\$rowtotal).'
  985:            </table>
  986:           </td>
  987:          </tr>
  988:          <tr>
  989:            <td>
  990:             <table class="LC_nested">
  991:              <tr class="LC_info_row">
  992:               <td class="LC_left_item"'.$colspan.' valign="top">'.
  993:                &mt($item->{'header'}->[2]->{'col1'}).'</td>
  994:               <td class="LC_right_item" valign="top">'.
  995:                &mt($item->{'header'}->[2]->{'col2'}).'</td>
  996:              </tr>'.
  997:             &print_rolecolors($phase,'author',$dom,$confname,$settings,\$rowtotal).'
  998:            </table>
  999:           </td>
 1000:          </tr>
 1001:          <tr>
 1002:            <td>
 1003:             <table class="LC_nested">
 1004:              <tr class="LC_info_row">
 1005:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1006:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
 1007:              </tr>'.
 1008:             &print_rolecolors($phase,'admin',$dom,$confname,$settings,\$rowtotal);
 1009:             $rowtotal += 2;
 1010:         }
 1011:     } else {
 1012:         $output .= '
 1013:           <tr>
 1014:            <td>
 1015:             <table class="LC_nested">
 1016:              <tr class="LC_info_row">';
 1017:         if ($action eq 'login') {
 1018:             $output .= '  
 1019:               <td class="LC_left_item" colspan="2">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
 1020:         } elsif ($action eq 'serverstatuses') {
 1021:             $output .= '
 1022:               <td class="LC_left_item" valign="top">'.&mt($item->{'header'}->[0]->{'col1'}).
 1023:               '<br />('.&mt('Automatic access for Dom. Coords.').')</td>';
 1024: 
 1025:         } else {
 1026:             $output .= '
 1027:               <td class="LC_left_item" valign="top">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
 1028:         }
 1029:         if (defined($item->{'header'}->[0]->{'col3'})) {
 1030:             $output .= '<td class="LC_left_item" valign="top">'.
 1031:                        &mt($item->{'header'}->[0]->{'col2'});
 1032:             if ($action eq 'serverstatuses') {
 1033:                 $output .= '<br />(<tt>'.&mt('user1:domain1,user2:domain2 etc.').'</tt>)';
 1034:             } 
 1035:         } else {
 1036:             $output .= '<td class="LC_right_item" valign="top">'.
 1037:                        &mt($item->{'header'}->[0]->{'col2'});
 1038:         }
 1039:         $output .= '</td>';
 1040:         if ($item->{'header'}->[0]->{'col3'}) {
 1041:             if (defined($item->{'header'}->[0]->{'col4'})) {
 1042:                 $output .= '<td class="LC_left_item" valign="top">'.
 1043:                             &mt($item->{'header'}->[0]->{'col3'});
 1044:             } else {
 1045:                 $output .= '<td class="LC_right_item" valign="top">'.
 1046:                            &mt($item->{'header'}->[0]->{'col3'});
 1047:             }
 1048:             if ($action eq 'serverstatuses') {
 1049:                 $output .= '<br />(<tt>'.&mt('IP1,IP2 etc.').'</tt>)';
 1050:             }
 1051:             $output .= '</td>';
 1052:         }
 1053:         if ($item->{'header'}->[0]->{'col4'}) {
 1054:             $output .= '<td class="LC_right_item" valign="top">'.
 1055:                        &mt($item->{'header'}->[0]->{'col4'});
 1056:         }
 1057:         $output .= '</tr>';
 1058:         $rowtotal ++;
 1059:         if ($action eq 'quotas') {
 1060:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
 1061:         } elsif (($action eq 'autoenroll') || ($action eq 'autocreate') || 
 1062:                  ($action eq 'serverstatuses') || ($action eq 'loadbalancing') ||
 1063:                  ($action eq 'ipaccess')) {
 1064:             $output .= $item->{'print'}->($dom,$settings,\$rowtotal);
 1065:         }
 1066:     }
 1067:     $output .= '
 1068:    </table>
 1069:   </td>
 1070:  </tr>
 1071: </table><br />';
 1072:     return ($output,$rowtotal);
 1073: }
 1074: 
 1075: sub print_login {
 1076:     my ($caller,$dom,$confname,$phase,$settings,$rowtotal) = @_;
 1077:     my ($css_class,$datatable,$switchserver,%lt);
 1078:     my %choices = &login_choices();
 1079:     if (($caller eq 'help') || ($caller eq 'headtag') || ($caller eq 'saml')) {
 1080:         %lt = &login_file_options();
 1081:         $switchserver = &check_switchserver($dom,$confname);
 1082:     }
 1083: 
 1084:     if ($caller eq 'service') {
 1085:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 1086:         my $choice = $choices{'disallowlogin'};
 1087:         $css_class = ' class="LC_odd_row"';
 1088:         $datatable .= '<tr'.$css_class.'><td>'.$choice.'</td>'.
 1089:                       '<td align="right"><table><tr><th>'.$choices{'hostid'}.'</th>'.
 1090:                       '<th>'.$choices{'server'}.'</th>'.
 1091:                       '<th>'.$choices{'serverpath'}.'</th>'.
 1092:                       '<th>'.$choices{'custompath'}.'</th>'.
 1093:                       '<th><span class="LC_nobreak">'.$choices{'exempt'}.'</span></th></tr>'."\n";
 1094:         my %disallowed;
 1095:         if (ref($settings) eq 'HASH') {
 1096:             if (ref($settings->{'loginvia'}) eq 'HASH') {
 1097:                %disallowed = %{$settings->{'loginvia'}};
 1098:             }
 1099:         }
 1100:         foreach my $lonhost (sort(keys(%servers))) {
 1101:             my $direct = 'selected="selected"';
 1102:             if (ref($disallowed{$lonhost}) eq 'HASH') {
 1103:                 if ($disallowed{$lonhost}{'server'} ne '') {
 1104:                     $direct = '';
 1105:                 }
 1106:             }
 1107:             $datatable .= '<tr><td>'.$servers{$lonhost}.'</td>'.
 1108:                           '<td><select name="'.$lonhost.'_server">'.
 1109:                           '<option value=""'.$direct.'>'.$choices{'directlogin'}.
 1110:                           '</option>';
 1111:             foreach my $hostid (sort(keys(%servers))) {
 1112:                 next if ($servers{$hostid} eq $servers{$lonhost});
 1113:                 my $selected = '';
 1114:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
 1115:                     if ($hostid eq $disallowed{$lonhost}{'server'}) {
 1116:                         $selected = 'selected="selected"';
 1117:                     }
 1118:                 }
 1119:                 $datatable .= '<option value="'.$hostid.'"'.$selected.'>'.
 1120:                               $servers{$hostid}.'</option>';
 1121:             }
 1122:             $datatable .= '</select></td>'.
 1123:                           '<td><select name="'.$lonhost.'_serverpath">';
 1124:             foreach my $path ('','/','/adm/login','/adm/roles','custom') {
 1125:                 my $pathname = $path;
 1126:                 if ($path eq 'custom') {
 1127:                     $pathname = &mt('Custom Path').' ->';
 1128:                 }
 1129:                 my $selected = '';
 1130:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
 1131:                     if ($path eq $disallowed{$lonhost}{'serverpath'}) {
 1132:                         $selected = 'selected="selected"';
 1133:                     }
 1134:                 } elsif ($path eq '') {
 1135:                     $selected = 'selected="selected"';
 1136:                 }
 1137:                 $datatable .= '<option value="'.$path.'"'.$selected.'>'.$pathname.'</option>';
 1138:             }
 1139:             $datatable .= '</select></td>';
 1140:             my ($custom,$exempt);
 1141:             if (ref($disallowed{$lonhost}) eq 'HASH') {
 1142:                 $custom = $disallowed{$lonhost}{'custompath'};
 1143:                 $exempt = $disallowed{$lonhost}{'exempt'};
 1144:             }
 1145:             $datatable .= '<td><input type="text" name="'.$lonhost.'_custompath" size="6" value="'.$custom.'" /></td>'.
 1146:                           '<td><input type="text" name="'.$lonhost.'_exempt" size="8" value="'.$exempt.'" /></td>'.
 1147:                           '</tr>';
 1148:         }
 1149:         $datatable .= '</table></td></tr>';
 1150:         return $datatable;
 1151:     } elsif ($caller eq 'page') {
 1152:         my %defaultchecked = ( 
 1153:                                'coursecatalog' => 'on',
 1154:                                'helpdesk'      => 'on',
 1155:                                'adminmail'     => 'off',
 1156:                                'newuser'       => 'off',
 1157:                              );
 1158:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
 1159:         my (%checkedon,%checkedoff);
 1160:         foreach my $item (@toggles) {
 1161:             if ($defaultchecked{$item} eq 'on') { 
 1162:                 $checkedon{$item} = ' checked="checked" ';
 1163:                 $checkedoff{$item} = ' ';
 1164:             } elsif ($defaultchecked{$item} eq 'off') {
 1165:                 $checkedoff{$item} = ' checked="checked" ';
 1166:                 $checkedon{$item} = ' ';
 1167:             }
 1168:         }
 1169:         my @images = ('img','logo','domlogo','login');
 1170:         my @alttext = ('img','logo','domlogo');
 1171:         my @logintext = ('textcol','bgcol');
 1172:         my @bgs = ('pgbg','mainbg','sidebg');
 1173:         my @links = ('link','alink','vlink');
 1174:         my %designhash = &Apache::loncommon::get_domainconf($dom);
 1175:         my %defaultdesign = %Apache::loncommon::defaultdesign;
 1176:         my (%is_custom,%designs);
 1177:         my %defaults = (
 1178:                        font => $defaultdesign{'login.font'},
 1179:                        );
 1180:         foreach my $item (@images) {
 1181:             $defaults{$item} = $defaultdesign{'login.'.$item};
 1182:             $defaults{'showlogo'}{$item} = 1;
 1183:         }
 1184:         foreach my $item (@bgs) {
 1185:             $defaults{'bgs'}{$item} = $defaultdesign{'login.'.$item};
 1186:         }
 1187:         foreach my $item (@logintext) {
 1188:             $defaults{'logintext'}{$item} = $defaultdesign{'login.'.$item};
 1189:         }
 1190:         foreach my $item (@links) {
 1191:             $defaults{'links'}{$item} = $defaultdesign{'login.'.$item};
 1192:         }
 1193:         if (ref($settings) eq 'HASH') {
 1194:             foreach my $item (@toggles) {
 1195:                 if ($settings->{$item} eq '1') {
 1196:                     $checkedon{$item} =  ' checked="checked" ';
 1197:                     $checkedoff{$item} = ' ';
 1198:                 } elsif ($settings->{$item} eq '0') {
 1199:                     $checkedoff{$item} =  ' checked="checked" ';
 1200:                     $checkedon{$item} = ' ';
 1201:                 }
 1202:             }
 1203:             foreach my $item (@images) {
 1204:                 if (defined($settings->{$item})) {
 1205:                     $designs{$item} = $settings->{$item};
 1206:                     $is_custom{$item} = 1;
 1207:                 }
 1208:                 if (defined($settings->{'showlogo'}{$item})) {
 1209:                     $designs{'showlogo'}{$item} = $settings->{'showlogo'}{$item};
 1210:                 }
 1211:             }
 1212:             foreach my $item (@alttext) {
 1213:                 if (ref($settings->{'alttext'}) eq 'HASH') {
 1214:                     if ($settings->{'alttext'}->{$item} ne '') {
 1215:                         $designs{'alttext'}{$item} = $settings->{'alttext'}{$item};
 1216:                     }
 1217:                 }
 1218:             }
 1219:             foreach my $item (@logintext) {
 1220:                 if ($settings->{$item} ne '') {
 1221:                     $designs{'logintext'}{$item} = $settings->{$item};
 1222:                     $is_custom{$item} = 1;
 1223:                 }
 1224:             }
 1225:             if ($settings->{'font'} ne '') {
 1226:                 $designs{'font'} = $settings->{'font'};
 1227:                 $is_custom{'font'} = 1;
 1228:             }
 1229:             foreach my $item (@bgs) {
 1230:                 if ($settings->{$item} ne '') {
 1231:                     $designs{'bgs'}{$item} = $settings->{$item};
 1232:                     $is_custom{$item} = 1;
 1233:                 }
 1234:             }
 1235:             foreach my $item (@links) {
 1236:                 if ($settings->{$item} ne '') {
 1237:                     $designs{'links'}{$item} = $settings->{$item};
 1238:                     $is_custom{$item} = 1;
 1239:                 }
 1240:             }
 1241:         } else {
 1242:             if ($designhash{$dom.'.login.font'} ne '') {
 1243:                 $designs{'font'} = $designhash{$dom.'.login.font'};
 1244:                 $is_custom{'font'} = 1;
 1245:             }
 1246:             foreach my $item (@images) {
 1247:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1248:                     $designs{$item} = $designhash{$dom.'.login.'.$item};
 1249:                     $is_custom{$item} = 1;
 1250:                 }
 1251:             }
 1252:             foreach my $item (@bgs) {
 1253:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1254:                     $designs{'bgs'}{$item} = $designhash{$dom.'.login.'.$item};
 1255:                     $is_custom{$item} = 1;
 1256:                 }
 1257:             }
 1258:             foreach my $item (@links) {
 1259:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1260:                     $designs{'links'}{$item} = $designhash{$dom.'.login.'.$item};
 1261:                     $is_custom{$item} = 1;
 1262:                 }
 1263:             }
 1264:         }
 1265:         my %alt_text = &Apache::lonlocal::texthash  ( img => 'Log-in banner',
 1266:                                                       logo => 'Institution Logo',
 1267:                                                       domlogo => 'Domain Logo',
 1268:                                                       login => 'Login box');
 1269:         my $itemcount = 1;
 1270:         foreach my $item (@toggles) {
 1271:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1272:             $datatable .=  
 1273:                 '<tr'.$css_class.'><td colspan="2">'.$choices{$item}.
 1274:                 '</td><td>'.
 1275:                 '<span class="LC_nobreak"><label><input type="radio" name="'.
 1276:                 $item.'"'.$checkedon{$item}.' value="1" />'.&mt('Yes').
 1277:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'"'.
 1278:                 $checkedoff{$item}.' value="0" />'.&mt('No').'</label></span></td>'.
 1279:                 '</tr>';
 1280:             $itemcount ++;
 1281:         }
 1282:         $datatable .= &display_color_options($dom,$confname,$phase,'login',$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal,\@logintext);
 1283:         $datatable .= '</tr></table></td></tr>';
 1284:     } elsif ($caller eq 'help') {
 1285:         my ($defaulturl,$defaulttype,%url,%type,%langchoices);
 1286:         my $itemcount = 1;
 1287:         $defaulturl = '/adm/loginproblems.html';
 1288:         $defaulttype = 'default';
 1289:         %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
 1290:         my @currlangs;
 1291:         if (ref($settings) eq 'HASH') {
 1292:             if (ref($settings->{'helpurl'}) eq 'HASH') {
 1293:                 foreach my $key (sort(keys(%{$settings->{'helpurl'}}))) {
 1294:                     next if ($settings->{'helpurl'}{$key} eq '');
 1295:                     $url{$key} = $settings->{'helpurl'}{$key}.'?inhibitmenu=yes';
 1296:                     $type{$key} = 'custom';
 1297:                     unless ($key eq 'nolang') {
 1298:                         push(@currlangs,$key);
 1299:                     }
 1300:                 }
 1301:             } elsif ($settings->{'helpurl'} ne '') {
 1302:                 $type{'nolang'} = 'custom';
 1303:                 $url{'nolang'} = $settings->{'helpurl'}.'?inhibitmenu=yes';
 1304:             }
 1305:         }
 1306:         foreach my $lang ('nolang',sort(@currlangs)) {
 1307:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1308:             $datatable .= '<tr'.$css_class.'>';
 1309:             if ($url{$lang} eq '') {
 1310:                 $url{$lang} = $defaulturl;
 1311:             }
 1312:             if ($type{$lang} eq '') {
 1313:                 $type{$lang} = $defaulttype;
 1314:             }
 1315:             $datatable .= '<td colspan="2"><span class="LC_nobreak">';
 1316:             if ($lang eq 'nolang') {
 1317:                 $datatable .= &mt('Log-in help page if no specific language file: [_1]',
 1318:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1319:             } else {
 1320:                 $datatable .= &mt('Log-in help page for language: [_1] is [_2]',
 1321:                                   $langchoices{$lang},
 1322:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1323:             }
 1324:             $datatable .= '</span></td>'."\n".
 1325:                           '<td class="LC_left_item">';
 1326:             if ($type{$lang} eq 'custom') {
 1327:                 $datatable .= '<span class="LC_nobreak"><label>'.
 1328:                               '<input type="checkbox" name="loginhelpurl_del" value="'.$lang.'" />'.
 1329:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1330:             } else {
 1331:                 $datatable .= $lt{'upl'};
 1332:             }
 1333:             $datatable .='<br />';
 1334:             if ($switchserver) {
 1335:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1336:             } else {
 1337:                 $datatable .= '<input type="file" name="loginhelpurl_'.$lang.'" />';
 1338:             }
 1339:             $datatable .= '</td></tr>';
 1340:             $itemcount ++;
 1341:         }
 1342:         my @addlangs;
 1343:         foreach my $lang (sort(keys(%langchoices))) {
 1344:             next if ((grep(/^\Q$lang\E$/,@currlangs)) || ($lang eq 'x_chef'));
 1345:             push(@addlangs,$lang);
 1346:         }
 1347:         if (@addlangs > 0) {
 1348:             my %toadd;
 1349:             map { $toadd{$_} = $langchoices{$_} ; } @addlangs;
 1350:             $toadd{''} = &mt('Select');
 1351:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1352:             $datatable .= '<tr'.$css_class.'><td class="LC_left_item" colspan="2">'.
 1353:                           &mt('Add log-in help page for a specific language:').'&nbsp;'.
 1354:                           &Apache::loncommon::select_form('','loginhelpurl_add_lang',\%toadd).
 1355:                           '</td><td class="LC_left_item">'.$lt{'upl'}.'<br />';
 1356:             if ($switchserver) {
 1357:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1358:             } else {
 1359:                 $datatable .= '<input type="file" name="loginhelpurl_add_file" />';
 1360:             }
 1361:             $datatable .= '</td></tr>';
 1362:             $itemcount ++;
 1363:         }
 1364:         $datatable .= &captcha_choice('login',$settings,$itemcount);
 1365:     } elsif ($caller eq 'headtag') {
 1366:         my %domservers = &Apache::lonnet::get_servers($dom);
 1367:         my $choice = $choices{'headtag'};
 1368:         $css_class = ' class="LC_odd_row"';
 1369:         $datatable .= '<tr'.$css_class.'><td colspan="2">'.$choice.'</td>'.
 1370:                       '<td align="left"><table><tr><th>'.$choices{'hostid'}.'</th>'.
 1371:                       '<th>'.$choices{'current'}.'</th>'.
 1372:                       '<th>'.$choices{'action'}.'</th>'.
 1373:                       '<th>'.$choices{'exempt'}.'</th></tr>'."\n";
 1374:         my (%currurls,%currexempt);
 1375:         if (ref($settings) eq 'HASH') {
 1376:             if (ref($settings->{'headtag'}) eq 'HASH') {
 1377:                 foreach my $lonhost (keys(%{$settings->{'headtag'}})) {
 1378:                     if (ref($settings->{'headtag'}{$lonhost}) eq 'HASH') {
 1379:                         $currurls{$lonhost} = $settings->{'headtag'}{$lonhost}{'url'};
 1380:                         $currexempt{$lonhost} = $settings->{'headtag'}{$lonhost}{'exempt'};
 1381:                     }
 1382:                 }
 1383:             }
 1384:         }
 1385:         foreach my $lonhost (sort(keys(%domservers))) {
 1386:             my $exempt = &check_exempt_addresses($currexempt{$lonhost});
 1387:             $datatable .= '<tr><td>'.$domservers{$lonhost}.'</td>';
 1388:             if ($currurls{$lonhost}) {
 1389:                 $datatable .= '<td class="LC_right_item"><a href="'.
 1390:                               "javascript:void(open('$currurls{$lonhost}?inhibitmenu=yes','Custom_HeadTag',
 1391:                               'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
 1392:                               '">'.$lt{'curr'}.'</a></td>'.
 1393:                               '<td><span class="LC_nobreak"><label>'.
 1394:                               '<input type="checkbox" name="loginheadtag_del" value="'.$lonhost.'" />'.
 1395:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1396:             } else {
 1397:                 $datatable .= '<td class="LC_right_item">'.$lt{'none'}.'</td><td>'.$lt{'upl'};
 1398:             }
 1399:             $datatable .='<br />';
 1400:             if ($switchserver) {
 1401:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1402:             } else {
 1403:                 $datatable .= '<input type="file" name="loginheadtag_'.$lonhost.'" />';
 1404:             }
 1405:             $datatable .= '</td><td><input type="text" name="loginheadtagexempt_'.$lonhost.'" value="'.$exempt.'" /></td></tr>';
 1406:         }
 1407:         $datatable .= '</table></td></tr>';
 1408:     } elsif ($caller eq 'saml') {
 1409:         my %domservers = &Apache::lonnet::get_servers($dom);
 1410:         $datatable .= '<tr><td colspan="3" style="text-align: left">'.
 1411:                       '<table><tr><th>'.$choices{'hostid'}.'</th>'.
 1412:                       '<th>'.$choices{'samllanding'}.'</th>'.
 1413:                       '<th>'.$choices{'samloptions'}.'</th></tr>'."\n";
 1414:         my (%saml,%samltext,%samlimg,%samlalt,%samlurl,%samltitle,%samlnotsso,%styleon,%styleoff);
 1415:         foreach my $lonhost (keys(%domservers)) {
 1416:             $samlurl{$lonhost} = '/adm/sso';
 1417:             $styleon{$lonhost} = 'display:none';
 1418:             $styleoff{$lonhost} = '';
 1419:         }
 1420:         if ((ref($settings) eq 'HASH') && (ref($settings->{'saml'}) eq 'HASH')) {
 1421:             foreach my $lonhost (keys(%{$settings->{'saml'}})) {
 1422:                 if (ref($settings->{'saml'}{$lonhost}) eq 'HASH') {
 1423:                     $saml{$lonhost} = 1;
 1424:                     $samltext{$lonhost} = $settings->{'saml'}{$lonhost}{'text'};
 1425:                     $samlimg{$lonhost} = $settings->{'saml'}{$lonhost}{'img'};
 1426:                     $samlalt{$lonhost} = $settings->{'saml'}{$lonhost}{'alt'};
 1427:                     $samlurl{$lonhost} = $settings->{'saml'}{$lonhost}{'url'};
 1428:                     $samltitle{$lonhost} = $settings->{'saml'}{$lonhost}{'title'};
 1429:                     $samlnotsso{$lonhost} = $settings->{'saml'}{$lonhost}{'notsso'};
 1430:                     $styleon{$lonhost} = '';
 1431:                     $styleoff{$lonhost} = 'display:none';
 1432:                 } else {
 1433:                     $styleon{$lonhost} = 'display:none';
 1434:                     $styleoff{$lonhost} = '';
 1435:                 }
 1436:             }
 1437:         }
 1438:         my $itemcount = 1;
 1439:         foreach my $lonhost (sort(keys(%domservers))) {
 1440:             my $samlon = ' ';
 1441:             my $samloff = ' checked="checked" ';
 1442:             if ($saml{$lonhost}) {
 1443:                 $samlon = $samloff;
 1444:                 $samloff = ' ';
 1445:             }
 1446:             my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1447:             $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.$domservers{$lonhost}.'</span></td>'.
 1448:                           '<td><span class="LC_nobreak"><label><input type="radio" name="saml_'.$lonhost.'"'.$samloff.
 1449:                           'onclick="toggleSamlOptions(this.form,'."'$lonhost'".');" value="0" />'.
 1450:                           &mt('No').'</label>'.('&nbsp;'x2).
 1451:                           '<label><input type="radio" name="saml_'.$lonhost.'"'.$samlon.
 1452:                           'onclick="toggleSamlOptions(this.form,'."'$lonhost'".');" value="1" />'.
 1453:                           &mt('Yes').'</label></span></td>'.
 1454:                           '<td id="samloptionson_'.$lonhost.'" style="'.$styleon{$lonhost}.'" width="100%">'.
 1455:                           '<table><tr><th colspan="5" align="center">'.&mt('SSO').'</th><th align="center">'.
 1456:                           '<span class="LC_nobreak">'.&mt('Non-SSO').'</span></th></tr>'.
 1457:                           '<tr><th>'.&mt('Text').'</th><th>'.&mt('Image').'</th>'.
 1458:                           '<th>'.&mt('Alt Text').'</th><th>'.&mt('URL').'</th>'.
 1459:                           '<th>'.&mt('Tool Tip').'</th><th>'.&mt('Text').'</th></tr>'.
 1460:                           '<tr'.$css_class.'><td><input type="text" name="saml_text_'.$lonhost.'" size="8" value="'.
 1461:                           $samltext{$lonhost}.'" /></td><td>';
 1462:             if ($samlimg{$lonhost}) {
 1463:                 $datatable .= '<img src="'.$samlimg{$lonhost}.'" /><br />'.
 1464:                               '<span class="LC_nobreak"><label>'.
 1465:                               '<input type="checkbox" name="saml_img_del" value="'.$lonhost.'" />'.
 1466:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1467:             } else {
 1468:                 $datatable .= $lt{'upl'};
 1469:             }
 1470:             $datatable .='<br />';
 1471:             if ($switchserver) {
 1472:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1473:             } else {
 1474:                 $datatable .= '<input type="file" name="saml_img_'.$lonhost.'" />';
 1475:             }
 1476:             $datatable .= '</td>'.
 1477:                           '<td><input type="text" name="saml_alt_'.$lonhost.'" size="20" '.
 1478:                           'value="'.$samlalt{$lonhost}.'" /></td>'.
 1479:                           '<td><input type="text" name="saml_url_'.$lonhost.'" size="8" '.
 1480:                           'value="'.$samlurl{$lonhost}.'" /></td>'.
 1481:                           '<td><textarea name="saml_title_'.$lonhost.'" rows="3" cols="15">'.
 1482:                           $samltitle{$lonhost}.'</textarea></td>'.
 1483:                           '<td><input type="text" name="saml_notsso_'.$lonhost.'" size="8" '.
 1484:                           'value="'.$samlnotsso{$lonhost}.'" /></td></tr>'.
 1485:                           '</table></td>'.
 1486:                           '<td id="samloptionsoff_'.$lonhost.'" style="'.$styleoff{$lonhost}.'" width="100%">&nbsp;</td></tr>';
 1487:            $itemcount ++;
 1488:         }
 1489:         $datatable .= '</table></td></tr>';
 1490:     }
 1491:     return $datatable;
 1492: }
 1493: 
 1494: sub login_choices {
 1495:     my %choices =
 1496:         &Apache::lonlocal::texthash (
 1497:             coursecatalog => 'Display Course/Community Catalog link?',
 1498:             adminmail     => "Display Administrator's E-mail Address?",
 1499:             helpdesk      => 'Display "Contact Helpdesk" link',
 1500:             disallowlogin => "Login page requests redirected",
 1501:             hostid        => "Server",
 1502:             server        => "Redirect to:",
 1503:             serverpath    => "Path",
 1504:             custompath    => "Custom", 
 1505:             exempt        => "Exempt IP(s)",
 1506:             directlogin   => "No redirect",
 1507:             newuser       => "Link to create a user account",
 1508:             img           => "Header",
 1509:             logo          => "Main Logo",
 1510:             domlogo       => "Domain Logo",
 1511:             login         => "Log-in Header", 
 1512:             textcol       => "Text color",
 1513:             bgcol         => "Box color",
 1514:             bgs           => "Background colors",
 1515:             links         => "Link colors",
 1516:             font          => "Font color",
 1517:             pgbg          => "Header",
 1518:             mainbg        => "Page",
 1519:             sidebg        => "Login box",
 1520:             link          => "Link",
 1521:             alink         => "Active link",
 1522:             vlink         => "Visited link",
 1523:             headtag       => "Custom markup",
 1524:             action        => "Action",
 1525:             current       => "Current",
 1526:             samllanding   => "Dual login?",
 1527:             samloptions   => "Options",
 1528:             alttext       => "Alt text",
 1529:         );
 1530:     return %choices;
 1531: }
 1532: 
 1533: sub login_file_options {
 1534:       return &Apache::lonlocal::texthash(
 1535:                                            del     => 'Delete?',
 1536:                                            rep     => 'Replace:',
 1537:                                            upl     => 'Upload:',
 1538:                                            curr    => 'View contents',
 1539:                                            default => 'Default',
 1540:                                            custom  => 'Custom',
 1541:                                            none    => 'None',
 1542:       );
 1543: }
 1544: 
 1545: sub print_ipaccess {
 1546:     my ($dom,$settings,$rowtotal) = @_;
 1547:     my $css_class;
 1548:     my $itemcount = 0;
 1549:     my $datatable;
 1550:     my %ordered;
 1551:     if (ref($settings) eq 'HASH') {
 1552:         foreach my $item (keys(%{$settings})) {
 1553:             if (ref($settings->{$item}) eq 'HASH') {
 1554:                 my $num = $settings->{$item}{'order'};
 1555:                 if ($num eq '') {
 1556:                     $num = scalar(keys(%{$settings}));
 1557:                 }
 1558:                 $ordered{$num} = $item;
 1559:             }
 1560:         }
 1561:     }
 1562:     my $maxnum = scalar(keys(%ordered));
 1563:     if (keys(%ordered)) {
 1564:         my @items = sort { $a <=> $b } keys(%ordered);
 1565:         for (my $i=0; $i<@items; $i++) {
 1566:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1567:             my $item = $ordered{$items[$i]};
 1568:             my ($name,$ipranges,%commblocks,%courses);
 1569:             if (ref($settings->{$item}) eq 'HASH') {
 1570:                 $name = $settings->{$item}->{'name'};
 1571:                 $ipranges = $settings->{$item}->{'ip'};
 1572:                 if (ref($settings->{$item}->{'commblocks'}) eq 'HASH') {
 1573:                     %commblocks = %{$settings->{$item}->{'commblocks'}};
 1574:                 }
 1575:                 if (ref($settings->{$item}->{'courses'}) eq 'HASH') {
 1576:                     %courses = %{$settings->{$item}->{'courses'}};
 1577:                 }
 1578:             }
 1579:             my $chgstr = ' onchange="javascript:reorderIPaccess(this.form,'."'ipaccess_pos_".$item."'".');"';
 1580:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 1581:                          .'<select name="ipaccess_pos_'.$item.'"'.$chgstr.'>';
 1582:             for (my $k=0; $k<=$maxnum; $k++) {
 1583:                 my $vpos = $k+1;
 1584:                 my $selstr;
 1585:                 if ($k == $i) {
 1586:                     $selstr = ' selected="selected" ';
 1587:                 }
 1588:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 1589:             }
 1590:             $datatable .= '</select>'.('&nbsp;'x2).
 1591:                 '<label><input type="checkbox" name="ipaccess_del" value="'.$item.'" />'.
 1592:                 &mt('Delete?').'</label></span></td>'.
 1593:                 '<td colspan="2"><input type="hidden" name="ipaccess_id_'.$i.'" value="'.$item.'" />'.
 1594:                 &ipaccess_options($i,$itemcount,$dom,$name,$ipranges,\%commblocks,\%courses).
 1595:                 '</td></tr>';
 1596:             $itemcount ++;
 1597:         }
 1598:     }
 1599:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1600:     my $chgstr = ' onchange="javascript:reorderIPaccess(this.form,'."'ipaccess_pos_add'".');"';
 1601:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 1602:                   '<input type="hidden" name="ipaccess_maxnum" value="'.$maxnum.'" />'."\n".
 1603:                   '<select name="ipaccess_pos_add"'.$chgstr.'>';
 1604:     for (my $k=0; $k<$maxnum+1; $k++) {
 1605:         my $vpos = $k+1;
 1606:         my $selstr;
 1607:         if ($k == $maxnum) {
 1608:             $selstr = ' selected="selected" ';
 1609:         }
 1610:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 1611:     }
 1612:     $datatable .= '</select>&nbsp;'."\n".
 1613:                   '<input type="checkbox" name="ipaccess_add" value="1" />'.&mt('Add').'</span></td>'."\n".
 1614:                   '<td colspan="2">'.
 1615:                   &ipaccess_options('add',$itemcount,$dom).
 1616:                   '</td>'."\n".
 1617:                   '</tr>'."\n";
 1618:     $$rowtotal ++;
 1619:     return $datatable;
 1620: }
 1621: 
 1622: sub ipaccess_options {
 1623:     my ($num,$itemcount,$dom,$name,$ipranges,$blocksref,$coursesref) = @_;
 1624:     my (%currblocks,%currcourses,$output);
 1625:     if (ref($blocksref) eq 'HASH') {
 1626:         %currblocks = %{$blocksref};
 1627:     }
 1628:     if (ref($coursesref) eq 'HASH') {
 1629:         %currcourses = %{$coursesref};
 1630:     }
 1631:     $output = '<fieldset><legend>'.&mt('Location(s)').'</legend>'.
 1632:               '<span class="LC_nobreak">'.&mt('Name').':&nbsp;'.
 1633:               '<input type="text" name="ipaccess_name_'.$num.'" value="'.$name.'" />'.
 1634:               '</span></fieldset>'.
 1635:               '<fieldset><legend>'.&mt('IP Range(s)').'</legend>'.
 1636:               &mt('Format for each IP range').': '.&mt('A.B.C.D/N or A.B.C.D-E.F.G.H').'<br />'.
 1637:               &mt('Range(s) will be stored as IP netblock(s) in CIDR notation (comma separated)').'<br />'.
 1638:               '<textarea name="ipaccess_range_'.$num.'" rows="3" cols="80">'.
 1639:               $ipranges.'</textarea></fieldset>'.
 1640:               '<fieldset><legend>'.&mt('Functionality Blocked?').'</legend>'.
 1641:               &blocker_checkboxes($num,$blocksref).'</fieldset>'.
 1642:               '<fieldset><legend>'.&mt('Courses/Communities allowed').'</legend>'.
 1643:               '<table>';
 1644:     foreach my $cid (sort(keys(%currcourses))) {
 1645:         my %courseinfo = &Apache::lonnet::coursedescription($cid,{'one_time' => 1});
 1646:         $output .= '<tr><td><span class="LC_nobreak">'.
 1647:                    '<label><input type="checkbox" name="ipaccess_course_delete_'.$num.'" value="'.$cid.'" />'.
 1648:                    &mt('Delete?').'&nbsp;<span class="LC_cusr_emph">'.$courseinfo{'description'}.'</span></label></span>'.
 1649:                    ' <span class="LC_fontsize_medium">('.$cid.')</span></td></tr>';
 1650:     }
 1651:     $output .= '<tr><td><span class="LC_nobreak">'.&mt('Add').':&nbsp;'.
 1652:                '<input type="text" name="ipaccess_cdesc_'.$num.'" value="" onfocus="this.blur();opencrsbrowser('."'display','ipaccess_cnum_$num','ipaccess_cdom_$num','ipaccess_cdesc_$num'".');" />'.
 1653:                 &Apache::loncommon::selectcourse_link('display','ipaccess_cnum_'.$num,'ipaccess_cdom_'.$num,'ipaccess_cdesc_'.$num,$dom,undef,'Course/Community').
 1654:                '<input type="hidden" name="ipaccess_cnum_'.$num.'" value="" />'.
 1655:                '<input type="hidden" name="ipaccess_cdom_'.$num.'" value="" />'.
 1656:                '</span></td></tr></table>'."\n".
 1657:                '</fieldset>';
 1658:     return $output;
 1659: }
 1660: 
 1661: sub blocker_checkboxes {
 1662:     my ($num,$blocks) = @_;
 1663:     my ($typeorder,$types) = &commblocktype_text();
 1664:     my $numinrow = 6;
 1665:     my $output = '<table>';
 1666:     for (my $i=0; $i<@{$typeorder}; $i++) {
 1667:         my $block = $typeorder->[$i];
 1668:         my $blockstatus;
 1669:         if (ref($blocks) eq 'HASH') {
 1670:             if ($blocks->{$block} eq 'on') {
 1671:                 $blockstatus = 'checked="checked"';
 1672:             }
 1673:         }
 1674:         my $rem = $i%($numinrow);
 1675:         if ($rem == 0) {
 1676:             if ($i > 0) {
 1677:                 $output .= '</tr>';
 1678:             }
 1679:             $output .= '<tr>';
 1680:         }
 1681:         if ($i == scalar(@{$typeorder})-1) {
 1682:             my $colsleft = $numinrow-$rem;
 1683:             if ($colsleft > 1) {
 1684:                 $output .= '<td colspan="'.$colsleft.'">';
 1685:             } else {
 1686:                 $output .= '<td>';
 1687:             }
 1688:         } else {
 1689:             $output .= '<td>';
 1690:         }
 1691:         my $item = 'ipaccess_block_'.$num;
 1692:         if ($blockstatus) {
 1693:             $blockstatus = ' '.$blockstatus;
 1694:         }
 1695:         $output .= '<span class="LC_nobreak"><label>'."\n".
 1696:                    '<input type="checkbox" name="'.$item.'"'.
 1697:                    $blockstatus.' value="'.$block.'"'.' />'.
 1698:                    $types->{$block}.'</label></span>'."\n".
 1699:                    '<br /></td>';
 1700:     }
 1701:     $output .= '</tr></table>';
 1702:     return $output;
 1703: }
 1704: 
 1705: sub commblocktype_text {
 1706:     my %types = &Apache::lonlocal::texthash(
 1707:         'com' => 'Messaging',
 1708:         'chat' => 'Chat Room',
 1709:         'boards' => 'Discussion',
 1710:         'port' => 'Portfolio',
 1711:         'groups' => 'Groups',
 1712:         'blogs' => 'Blogs',
 1713:         'about' => 'User Information',
 1714:         'printout' => 'Printouts',
 1715:         'passwd' => 'Change Password',
 1716:         'grades' => 'Gradebook',
 1717:         'search' => 'Course search',
 1718:         'wishlist' => 'Stored links',
 1719:         'annotate' => 'Annotations',
 1720:     );
 1721:     my $typeorder = ['com','chat','boards','port','groups','blogs','about','wishlist','printout','grades','search','annotate','passwd'];
 1722:     return ($typeorder,\%types);
 1723: }
 1724: 
 1725: sub print_rolecolors {
 1726:     my ($phase,$role,$dom,$confname,$settings,$rowtotal) = @_;
 1727:     my %choices = &color_font_choices();
 1728:     my @bgs = ('pgbg','tabbg','sidebg');
 1729:     my @links = ('link','alink','vlink');
 1730:     my @images = ('img');
 1731:     my %alt_text = &Apache::lonlocal::texthash(img => "Banner for $role role");
 1732:     my %designhash = &Apache::loncommon::get_domainconf($dom);
 1733:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 1734:     my (%is_custom,%designs);
 1735:     my %defaults = &role_defaults($role,\@bgs,\@links,\@images);
 1736:     if (ref($settings) eq 'HASH') {
 1737:         if (ref($settings->{$role}) eq 'HASH') {
 1738:             if ($settings->{$role}->{'img'} ne '') {
 1739:                 $designs{'img'} = $settings->{$role}->{'img'};
 1740:                 $is_custom{'img'} = 1;
 1741:             }
 1742:             if ($settings->{$role}->{'font'} ne '') {
 1743:                 $designs{'font'} = $settings->{$role}->{'font'};
 1744:                 $is_custom{'font'} = 1;
 1745:             }
 1746:             if ($settings->{$role}->{'fontmenu'} ne '') {
 1747:                 $designs{'fontmenu'} = $settings->{$role}->{'fontmenu'};
 1748:                 $is_custom{'fontmenu'} = 1;
 1749:             }
 1750:             foreach my $item (@bgs) {
 1751:                 if ($settings->{$role}->{$item} ne '') {
 1752:                     $designs{'bgs'}{$item} = $settings->{$role}->{$item};
 1753:                     $is_custom{$item} = 1;
 1754:                 }
 1755:             }
 1756:             foreach my $item (@links) {
 1757:                 if ($settings->{$role}->{$item} ne '') {
 1758:                     $designs{'links'}{$item} = $settings->{$role}->{$item};
 1759:                     $is_custom{$item} = 1;
 1760:                 }
 1761:             }
 1762:         }
 1763:     } else {
 1764:         if ($designhash{$dom.'.'.$role.'.img'} ne '') {
 1765:             $designs{img} = $designhash{$dom.'.'.$role.'.img'};
 1766:             $is_custom{'img'} = 1;
 1767:         }
 1768:         if ($designhash{$dom.'.'.$role.'.fontmenu'} ne '') {
 1769:             $designs{fontmenu} = $designhash{$dom.'.'.$role.'.fontmenu'};
 1770:             $is_custom{'fontmenu'} = 1; 
 1771:         }
 1772:         if ($designhash{$dom.'.'.$role.'.font'} ne '') {
 1773:             $designs{font} = $designhash{$dom.'.'.$role.'.font'};
 1774:             $is_custom{'font'} = 1;
 1775:         }
 1776:         foreach my $item (@bgs) {
 1777:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 1778:                 $designs{'bgs'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 1779:                 $is_custom{$item} = 1;
 1780:             
 1781:             }
 1782:         }
 1783:         foreach my $item (@links) {
 1784:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 1785:                 $designs{'links'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 1786:                 $is_custom{$item} = 1;
 1787:             }
 1788:         }
 1789:     }
 1790:     my $itemcount = 1;
 1791:     my $datatable = &display_color_options($dom,$confname,$phase,$role,$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal);
 1792:     $datatable .= '</tr></table></td></tr>';
 1793:     return $datatable;
 1794: }
 1795: 
 1796: sub role_defaults {
 1797:     my ($role,$bgs,$links,$images,$logintext) = @_;
 1798:     my %defaults;
 1799:     unless ((ref($bgs) eq 'ARRAY') && (ref($links) eq 'ARRAY') && (ref($images) eq 'ARRAY')) {
 1800:         return %defaults;
 1801:     }
 1802:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 1803:     if ($role eq 'login') {
 1804:         %defaults = (
 1805:                        font => $defaultdesign{$role.'.font'},
 1806:                     );
 1807:         if (ref($logintext) eq 'ARRAY') {
 1808:             foreach my $item (@{$logintext}) {
 1809:                 $defaults{'logintext'}{$item} = $defaultdesign{$role.'.'.$item};
 1810:             }
 1811:         }
 1812:         foreach my $item (@{$images}) {
 1813:             $defaults{'showlogo'}{$item} = 1;
 1814:         }
 1815:     } else {
 1816:         %defaults = (
 1817:                        img => $defaultdesign{$role.'.img'},
 1818:                        font => $defaultdesign{$role.'.font'},
 1819:                        fontmenu => $defaultdesign{$role.'.fontmenu'},
 1820:                     );
 1821:     }
 1822:     foreach my $item (@{$bgs}) {
 1823:         $defaults{'bgs'}{$item} = $defaultdesign{$role.'.'.$item};
 1824:     }
 1825:     foreach my $item (@{$links}) {
 1826:         $defaults{'links'}{$item} = $defaultdesign{$role.'.'.$item};
 1827:     }
 1828:     foreach my $item (@{$images}) {
 1829:         $defaults{$item} = $defaultdesign{$role.'.'.$item};
 1830:     }
 1831:     return %defaults;
 1832: }
 1833: 
 1834: sub display_color_options {
 1835:     my ($dom,$confname,$phase,$role,$itemcount,$choices,$is_custom,$defaults,$designs,
 1836:         $images,$bgs,$links,$alt_text,$rowtotal,$logintext) = @_;
 1837:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 1838:     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1839:     my $datatable = '<tr'.$css_class.'>'.
 1840:         '<td>'.$choices->{'font'}.'</td>';
 1841:     if (!$is_custom->{'font'}) {
 1842:         $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span class="css_default_'.$role.'_font" style="color: '.$defaults->{'font'}.';">'.$defaults->{'font'}.'</span></td>';
 1843:     } else {
 1844:         $datatable .= '<td>&nbsp;</td>';
 1845:     }
 1846:     my $current_color = $designs->{'font'} ? $designs->{'font'} : $defaults->{'font'};
 1847: 
 1848:     $datatable .= '<td><span class="LC_nobreak">'.
 1849:                   '<input type="text" class="colorchooser" size="10" name="'.$role.'_font"'.
 1850:                   ' value="'.$current_color.'" />&nbsp;'.
 1851:                   '&nbsp;</span></td></tr>';
 1852:     unless ($role eq 'login') { 
 1853:         $datatable .= '<tr'.$css_class.'>'.
 1854:                       '<td>'.$choices->{'fontmenu'}.'</td>';
 1855:         if (!$is_custom->{'fontmenu'}) {
 1856:             $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span class="css_default_'.$role.'_font" style="color: '.$defaults->{'fontmenu'}.';">'.$defaults->{'fontmenu'}.'</span></td>';
 1857:         } else {
 1858:             $datatable .= '<td>&nbsp;</td>';
 1859:         }
 1860: 	$current_color = $designs->{'fontmenu'} ?
 1861: 	    $designs->{'fontmenu'} : $defaults->{'fontmenu'};
 1862:         $datatable .= '<td><span class="LC_nobreak">'.
 1863:                       '<input class="colorchooser" type="text" size="10" name="'
 1864: 		      .$role.'_fontmenu"'.
 1865:                       ' value="'.$current_color.'" />&nbsp;'.
 1866:                       '&nbsp;</span></td></tr>';
 1867:     }
 1868:     my $switchserver = &check_switchserver($dom,$confname);
 1869:     foreach my $img (@{$images}) {
 1870: 	$itemcount ++;
 1871:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1872:         $datatable .= '<tr'.$css_class.'>'.
 1873:                       '<td>'.$choices->{$img};
 1874:         my ($imgfile,$img_import,$login_hdr_pick,$logincolors,$alttext);
 1875:         if ($role eq 'login') {
 1876:             if ($img eq 'login') {
 1877:                 $login_hdr_pick =
 1878:                     &login_header_options($img,$role,$defaults,$is_custom,$choices);
 1879:                 $logincolors =
 1880:                     &login_text_colors($img,$role,$logintext,$phase,$choices,
 1881:                                        $designs,$defaults);
 1882:             } else { 
 1883:                 if ($img ne 'domlogo') {
 1884:                     $datatable.= &logo_display_options($img,$defaults,$designs);
 1885:                 }
 1886:                 if (ref($designs->{'alttext'}) eq 'HASH') {
 1887:                     $alttext = $designs->{'alttext'}{$img};
 1888:                 }
 1889:             }
 1890:         }
 1891:         $datatable .= '</td>';
 1892:         if ($designs->{$img} ne '') {
 1893:             $imgfile = $designs->{$img};
 1894: 	    $img_import = ($imgfile =~ m{^/adm/});
 1895:         } else {
 1896:             $imgfile = $defaults->{$img};
 1897:         }
 1898:         if ($imgfile) {
 1899:             my ($showfile,$fullsize);
 1900:             if ($imgfile =~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
 1901:                 my $urldir = $1;
 1902:                 my $filename = $2;
 1903:                 my @info = &Apache::lonnet::stat_file($designs->{$img});
 1904:                 if (@info) {
 1905:                     my $thumbfile = 'tn-'.$filename;
 1906:                     my @thumb=&Apache::lonnet::stat_file($urldir.'/'.$thumbfile);
 1907:                     if (@thumb) {
 1908:                         $showfile = $urldir.'/'.$thumbfile;
 1909:                     } else {
 1910:                         $showfile = $imgfile;
 1911:                     }
 1912:                 } else {
 1913:                     $showfile = '';
 1914:                 }
 1915:             } elsif ($imgfile =~ m-^/(adm/[^/]+)/([^/]+)$-) {
 1916:                 $showfile = $imgfile;
 1917:                 my $imgdir = $1;
 1918:                 my $filename = $2;
 1919:                 if (-e "$londocroot/$imgdir/tn-".$filename) {
 1920:                     $showfile = "/$imgdir/tn-".$filename;
 1921:                 } else {
 1922:                     my $input = $londocroot.$imgfile;
 1923:                     my $output = "$londocroot/$imgdir/tn-".$filename;
 1924:                     if (!-e $output) {
 1925:                         my ($width,$height) = &thumb_dimensions();
 1926:                         my ($fullwidth,$fullheight) = &check_dimensions($input);
 1927:                         if ($fullwidth ne '' && $fullheight ne '') {
 1928:                             if ($fullwidth > $width && $fullheight > $height) { 
 1929:                                 my $size = $width.'x'.$height;
 1930:                                 my @args = ('convert','-sample',$size,$input,$output);
 1931:                                 system({$args[0]} @args);
 1932:                                 $showfile = "/$imgdir/tn-".$filename;
 1933:                             }
 1934:                         }
 1935:                     }
 1936:                 }
 1937:             }
 1938:             if ($showfile) {
 1939:                 if ($showfile =~ m{^/(adm|res)/}) {
 1940:                     if ($showfile =~ m{^/res/}) {
 1941:                         my $local_showfile =
 1942:                             &Apache::lonnet::filelocation('',$showfile);
 1943:                         &Apache::lonnet::repcopy($local_showfile);
 1944:                     }
 1945:                     $showfile = &Apache::loncommon::lonhttpdurl($showfile);
 1946:                 }
 1947:                 if ($imgfile) {
 1948:                     if ($imgfile  =~ m{^/(adm|res)/}) {
 1949:                         if ($imgfile =~ m{^/res/}) {
 1950:                             my $local_imgfile =
 1951:                                 &Apache::lonnet::filelocation('',$imgfile);
 1952:                             &Apache::lonnet::repcopy($local_imgfile);
 1953:                         }
 1954:                         $fullsize = &Apache::loncommon::lonhttpdurl($imgfile);
 1955:                     } else {
 1956:                         $fullsize = $imgfile;
 1957:                     }
 1958:                 }
 1959:                 $datatable .= '<td>';
 1960:                 if ($img eq 'login') {
 1961:                     $datatable .= $login_hdr_pick;
 1962:                 } 
 1963:                 $datatable .= &image_changes($is_custom->{$img},$alt_text->{$img},$img_import,
 1964:                                              $showfile,$fullsize,$role,$img,$imgfile,$logincolors);
 1965:             } else {
 1966:                 $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 1967:                               &mt('Upload:').'<br />';
 1968:             }
 1969:         } else {
 1970:             $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 1971:                           &mt('Upload:').'<br />';
 1972:         }
 1973:         if ($switchserver) {
 1974:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1975:         } else {
 1976:             if ($img ne 'login') { # suppress file selection for Log-in header
 1977:                 $datatable .='&nbsp;<input type="file" name="'.$role.'_'.$img.'" />';
 1978:             }
 1979:         }
 1980:         if (($role eq 'login') && ($img ne 'login')) {
 1981:             $datatable .= ('&nbsp;' x2).' <span class="LC_nobreak"><label>'.$choices->{'alttext'}.':'.
 1982:                           '<input type="text" name="'.$role.'_alt_'.$img.'" size="10" value="'.$alttext.'" />'.
 1983:                           '</label></span>';
 1984:         }
 1985:         $datatable .= '</td></tr>';
 1986:     }
 1987:     $itemcount ++;
 1988:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1989:     $datatable .= '<tr'.$css_class.'>'.
 1990:                   '<td>'.$choices->{'bgs'}.'</td>';
 1991:     my $bgs_def;
 1992:     foreach my $item (@{$bgs}) {
 1993:         if (!$is_custom->{$item}) {
 1994:             $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>';
 1995:         }
 1996:     }
 1997:     if ($bgs_def) {
 1998:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$bgs_def.'</tr></table></td>';
 1999:     } else {
 2000:         $datatable .= '<td>&nbsp;</td>';
 2001:     }
 2002:     $datatable .= '<td class="LC_right_item">'.
 2003:                   '<table border="0"><tr>';
 2004: 
 2005:     foreach my $item (@{$bgs}) {
 2006:         $datatable .= '<td align="center">'.$choices->{$item};
 2007: 	my $color = $designs->{'bgs'}{$item} ? $designs->{'bgs'}{$item} : $defaults->{'bgs'}{$item};
 2008:         if ($designs->{'bgs'}{$item}) {
 2009:             $datatable .= '&nbsp;';
 2010:         }
 2011:         $datatable .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 2012:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 2013:     }
 2014:     $datatable .= '</tr></table></td></tr>';
 2015:     $itemcount ++;
 2016:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2017:     $datatable .= '<tr'.$css_class.'>'.
 2018:                   '<td>'.$choices->{'links'}.'</td>';
 2019:     my $links_def;
 2020:     foreach my $item (@{$links}) {
 2021:         if (!$is_custom->{$item}) {
 2022:             $links_def .= '<td>'.$choices->{$item}.'<br /><span class="css_default_'.$role.'_'.$item.'" style="color: '.$defaults->{'links'}{$item}.';">'.$defaults->{'links'}{$item}.'</span></td>';
 2023:         }
 2024:     }
 2025:     if ($links_def) {
 2026:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$links_def.'</tr></table></td>';
 2027:     } else {
 2028:         $datatable .= '<td>&nbsp;</td>';
 2029:     }
 2030:     $datatable .= '<td class="LC_right_item">'.
 2031:                   '<table border="0"><tr>';
 2032:     foreach my $item (@{$links}) {
 2033: 	my $color = $designs->{'links'}{$item} ? $designs->{'links'}{$item} : $defaults->{'links'}{$item};
 2034:         $datatable .= '<td align="center">'.$choices->{$item}."\n";
 2035:         if ($designs->{'links'}{$item}) {
 2036:             $datatable.='&nbsp;';
 2037:         }
 2038:         $datatable .= '<br /><input type="text" size="8" class="colorchooser" name="'.$role.'_'.$item.'" value="'.$color.
 2039:                       '" /></td>';
 2040:     }
 2041:     $$rowtotal += $itemcount;
 2042:     return $datatable;
 2043: }
 2044: 
 2045: sub logo_display_options {
 2046:     my ($img,$defaults,$designs) = @_;
 2047:     my $checkedon;
 2048:     if (ref($defaults) eq 'HASH') {
 2049:         if (ref($defaults->{'showlogo'}) eq 'HASH') {
 2050:             if ($defaults->{'showlogo'}{$img}) {
 2051:                 $checkedon = 'checked="checked" ';     
 2052:             }
 2053:         } 
 2054:     }
 2055:     if (ref($designs) eq 'HASH') {
 2056:         if (ref($designs->{'showlogo'}) eq 'HASH') {
 2057:             if (defined($designs->{'showlogo'}{$img})) {
 2058:                 if ($designs->{'showlogo'}{$img} == 0) {
 2059:                     $checkedon = '';
 2060:                 } elsif ($designs->{'showlogo'}{$img} == 1) {
 2061:                     $checkedon = 'checked="checked" ';
 2062:                 }
 2063:             }
 2064:         }
 2065:     }
 2066:     return '<br /><label>&nbsp;&nbsp;<input type="checkbox" name="'.
 2067:            'login_showlogo_'.$img.'" value="1" '.$checkedon.'/>'.
 2068:            &mt('show').'</label>'."\n";
 2069: }
 2070: 
 2071: sub login_header_options  {
 2072:     my ($img,$role,$defaults,$is_custom,$choices) = @_;
 2073:     my $output = '';
 2074:     if ((!$is_custom->{'textcol'}) || (!$is_custom->{'bgcol'})) {
 2075:         $output .= &mt('Text default(s):').'<br />';
 2076:         if (!$is_custom->{'textcol'}) {
 2077:             $output .= $choices->{'textcol'}.':&nbsp;'.$defaults->{'logintext'}{'textcol'}.
 2078:                        '&nbsp;&nbsp;&nbsp;';
 2079:         }
 2080:         if (!$is_custom->{'bgcol'}) {
 2081:             $output .= $choices->{'bgcol'}.':&nbsp;'.
 2082:                        '<span id="css_'.$role.'_font" style="background-color: '.
 2083:                        $defaults->{'logintext'}{'bgcol'}.';">&nbsp;&nbsp;&nbsp;</span>';
 2084:         }
 2085:         $output .= '<br />';
 2086:     }
 2087:     $output .='<br />';
 2088:     return $output;
 2089: }
 2090: 
 2091: sub login_text_colors {
 2092:     my ($img,$role,$logintext,$phase,$choices,$designs,$defaults) = @_;
 2093:     my $color_menu = '<table border="0"><tr>';
 2094:     foreach my $item (@{$logintext}) {
 2095:         $color_menu .= '<td align="center">'.$choices->{$item};
 2096:         my $color = $designs->{'logintext'}{$item} ? $designs->{'logintext'}{$item} : $defaults->{'logintext'}{$item};
 2097:         $color_menu .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 2098:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 2099:     }
 2100:     $color_menu .= '</tr></table><br />';
 2101:     return $color_menu;
 2102: }
 2103: 
 2104: sub image_changes {
 2105:     my ($is_custom,$alt_text,$img_import,$showfile,$fullsize,$role,$img,$imgfile,$logincolors) = @_;
 2106:     my $output;
 2107:     if ($img eq 'login') {
 2108:         $output = '</td><td>'.$logincolors; # suppress image for Log-in header
 2109:     } elsif (!$is_custom) {
 2110:         if ($img ne 'domlogo') {
 2111:             $output = &mt('Default image:').'<br />';
 2112:         } else {
 2113:             $output = &mt('Default in use:').'<br />';
 2114:         }
 2115:     }
 2116:     if ($img ne 'login') {
 2117:         if ($img_import) {
 2118:             $output .= '<input type="hidden" name="'.$role.'_import_'.$img.'" value="'.$imgfile.'" />';
 2119:         }
 2120:         $output .= '<a href="'.$fullsize.'" target="_blank"><img src="'.
 2121:                    $showfile.'" alt="'.$alt_text.'" border="0" /></a></td>';
 2122:         if ($is_custom) {
 2123:             $output .= '<td>'.$logincolors.'<span class="LC_nobreak"><label>'.
 2124:                        '<input type="checkbox" name="'.
 2125:                        $role.'_del_'.$img.'" value="1" />'.&mt('Delete?').
 2126:                        '</label>&nbsp;'.&mt('Replace:').'</span><br />';
 2127:         } else {
 2128:             $output .= '<td valign="middle">'.$logincolors.&mt('Upload:').'<br />';
 2129:         }
 2130:     }
 2131:     return $output;
 2132: }
 2133: 
 2134: sub print_quotas {
 2135:     my ($dom,$settings,$rowtotal,$action) = @_;
 2136:     my $context;
 2137:     if ($action eq 'quotas') {
 2138:         $context = 'tools';
 2139:     } else {
 2140:         $context = $action;
 2141:     }
 2142:     my ($datatable,$defaultquota,$authorquota,@usertools,@options,%validations);
 2143:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 2144:     my $typecount = 0;
 2145:     my ($css_class,%titles);
 2146:     if ($context eq 'requestcourses') {
 2147:         @usertools = ('official','unofficial','community','textbook');
 2148:         @options =('norequest','approval','validate','autolimit');
 2149:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
 2150:         %titles = &courserequest_titles();
 2151:     } elsif ($context eq 'requestauthor') {
 2152:         @usertools = ('author');
 2153:         @options = ('norequest','approval','automatic');
 2154:         %titles = &authorrequest_titles();
 2155:     } else {
 2156:         @usertools = ('aboutme','blog','webdav','portfolio');
 2157:         %titles = &tool_titles();
 2158:     }
 2159:     if (ref($types) eq 'ARRAY') {
 2160:         foreach my $type (@{$types}) {
 2161:             my ($currdefquota,$currauthorquota);
 2162:             unless (($context eq 'requestcourses') ||
 2163:                     ($context eq 'requestauthor')) {
 2164:                 if (ref($settings) eq 'HASH') {
 2165:                     if (ref($settings->{defaultquota}) eq 'HASH') {
 2166:                         $currdefquota = $settings->{defaultquota}->{$type};
 2167:                     } else {
 2168:                         $currdefquota = $settings->{$type};
 2169:                     }
 2170:                     if (ref($settings->{authorquota}) eq 'HASH') {
 2171:                         $currauthorquota = $settings->{authorquota}->{$type};
 2172:                     }
 2173:                 }
 2174:             }
 2175:             if (defined($usertypes->{$type})) {
 2176:                 $typecount ++;
 2177:                 $css_class = $typecount%2?' class="LC_odd_row"':'';
 2178:                 $datatable .= '<tr'.$css_class.'>'.
 2179:                               '<td>'.$usertypes->{$type}.'</td>'.
 2180:                               '<td class="LC_left_item">';
 2181:                 if ($context eq 'requestcourses') {
 2182:                     $datatable .= '<table><tr>';
 2183:                 }
 2184:                 my %cell;  
 2185:                 foreach my $item (@usertools) {
 2186:                     if ($context eq 'requestcourses') {
 2187:                         my ($curroption,$currlimit);
 2188:                         if (ref($settings) eq 'HASH') {
 2189:                             if (ref($settings->{$item}) eq 'HASH') {
 2190:                                 $curroption = $settings->{$item}->{$type};
 2191:                                 if ($curroption =~ /^autolimit=(\d*)$/) {
 2192:                                     $currlimit = $1; 
 2193:                                 }
 2194:                             }
 2195:                         }
 2196:                         if (!$curroption) {
 2197:                             $curroption = 'norequest';
 2198:                         }
 2199:                         $datatable .= '<th>'.$titles{$item}.'</th>';
 2200:                         foreach my $option (@options) {
 2201:                             my $val = $option;
 2202:                             if ($option eq 'norequest') {
 2203:                                 $val = 0;  
 2204:                             }
 2205:                             if ($option eq 'validate') {
 2206:                                 my $canvalidate = 0;
 2207:                                 if (ref($validations{$item}) eq 'HASH') { 
 2208:                                     if ($validations{$item}{$type}) {
 2209:                                         $canvalidate = 1;
 2210:                                     }
 2211:                                 }
 2212:                                 next if (!$canvalidate);
 2213:                             }
 2214:                             my $checked = '';
 2215:                             if ($option eq $curroption) {
 2216:                                 $checked = ' checked="checked"';
 2217:                             } elsif ($option eq 'autolimit') {
 2218:                                 if ($curroption =~ /^autolimit/) {
 2219:                                     $checked = ' checked="checked"';
 2220:                                 }                       
 2221:                             } 
 2222:                             $cell{$item} .= '<span class="LC_nobreak"><label>'.
 2223:                                   '<input type="radio" name="crsreq_'.$item.
 2224:                                   '_'.$type.'" value="'.$val.'"'.$checked.' />'.
 2225:                                   $titles{$option}.'</label>';
 2226:                             if ($option eq 'autolimit') {
 2227:                                 $cell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2228:                                                 $item.'_limit_'.$type.'" size="1" '.
 2229:                                                 'value="'.$currlimit.'" />';
 2230:                             }
 2231:                             $cell{$item} .= '</span> ';
 2232:                             if ($option eq 'autolimit') {
 2233:                                 $cell{$item} .= $titles{'unlimited'};
 2234:                             }
 2235:                         }
 2236:                     } elsif ($context eq 'requestauthor') {
 2237:                         my $curroption;
 2238:                         if (ref($settings) eq 'HASH') {
 2239:                             $curroption = $settings->{$type};
 2240:                         }
 2241:                         if (!$curroption) {
 2242:                             $curroption = 'norequest';
 2243:                         }
 2244:                         foreach my $option (@options) {
 2245:                             my $val = $option;
 2246:                             if ($option eq 'norequest') {
 2247:                                 $val = 0;
 2248:                             }
 2249:                             my $checked = '';
 2250:                             if ($option eq $curroption) {
 2251:                                 $checked = ' checked="checked"';
 2252:                             }
 2253:                             $datatable .= '<span class="LC_nobreak"><label>'.
 2254:                                   '<input type="radio" name="authorreq_'.$type.
 2255:                                   '" value="'.$val.'"'.$checked.' />'.
 2256:                                   $titles{$option}.'</label></span>&nbsp; ';
 2257:                         }
 2258:                     } else {
 2259:                         my $checked = 'checked="checked" ';
 2260:                         if (ref($settings) eq 'HASH') {
 2261:                             if (ref($settings->{$item}) eq 'HASH') {
 2262:                                 if ($settings->{$item}->{$type} == 0) {
 2263:                                     $checked = '';
 2264:                                 } elsif ($settings->{$item}->{$type} == 1) {
 2265:                                     $checked =  'checked="checked" ';
 2266:                                 }
 2267:                             }
 2268:                         }
 2269:                         $datatable .= '<span class="LC_nobreak"><label>'.
 2270:                                       '<input type="checkbox" name="'.$context.'_'.$item.
 2271:                                       '" value="'.$type.'" '.$checked.'/>'.$titles{$item}.
 2272:                                       '</label></span>&nbsp; ';
 2273:                     }
 2274:                 }
 2275:                 if ($context eq 'requestcourses') {
 2276:                     $datatable .= '</tr><tr>';
 2277:                     foreach my $item (@usertools) {
 2278:                         $datatable .= '<td style="vertical-align: top">'.$cell{$item}.'</td>';  
 2279:                     }
 2280:                     $datatable .= '</tr></table>';
 2281:                 }
 2282:                 $datatable .= '</td>';
 2283:                 unless (($context eq 'requestcourses') ||
 2284:                         ($context eq 'requestauthor')) {
 2285:                     $datatable .= 
 2286:                               '<td class="LC_right_item">'.
 2287:                               '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 2288:                               '<input type="text" name="quota_'.$type.
 2289:                               '" value="'.$currdefquota.
 2290:                               '" size="5" /></span>'.('&nbsp;' x 2).
 2291:                               '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 2292:                               '<input type="text" name="authorquota_'.$type.
 2293:                               '" value="'.$currauthorquota.
 2294:                               '" size="5" /></span></td>';
 2295:                 }
 2296:                 $datatable .= '</tr>';
 2297:             }
 2298:         }
 2299:     }
 2300:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 2301:         $defaultquota = '20';
 2302:         $authorquota = '500';
 2303:         if (ref($settings) eq 'HASH') {
 2304:             if (ref($settings->{'defaultquota'}) eq 'HASH') {
 2305:                 $defaultquota = $settings->{'defaultquota'}->{'default'};
 2306:             } elsif (defined($settings->{'default'})) {
 2307:                 $defaultquota = $settings->{'default'};
 2308:             }
 2309:             if (ref($settings->{'authorquota'}) eq 'HASH') {
 2310:                 $authorquota = $settings->{'authorquota'}->{'default'};
 2311:             }
 2312:         }
 2313:     }
 2314:     $typecount ++;
 2315:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 2316:     $datatable .= '<tr'.$css_class.'>'.
 2317:                   '<td>'.$othertitle.'</td>'.
 2318:                   '<td class="LC_left_item">';
 2319:     if ($context eq 'requestcourses') {
 2320:         $datatable .= '<table><tr>';
 2321:     }
 2322:     my %defcell;
 2323:     foreach my $item (@usertools) {
 2324:         if ($context eq 'requestcourses') {
 2325:             my ($curroption,$currlimit);
 2326:             if (ref($settings) eq 'HASH') {
 2327:                 if (ref($settings->{$item}) eq 'HASH') {
 2328:                     $curroption = $settings->{$item}->{'default'};
 2329:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 2330:                         $currlimit = $1;
 2331:                     }
 2332:                 }
 2333:             }
 2334:             if (!$curroption) {
 2335:                 $curroption = 'norequest';
 2336:             }
 2337:             $datatable .= '<th>'.$titles{$item}.'</th>';
 2338:             foreach my $option (@options) {
 2339:                 my $val = $option;
 2340:                 if ($option eq 'norequest') {
 2341:                     $val = 0;
 2342:                 }
 2343:                 if ($option eq 'validate') {
 2344:                     my $canvalidate = 0;
 2345:                     if (ref($validations{$item}) eq 'HASH') {
 2346:                         if ($validations{$item}{'default'}) {
 2347:                             $canvalidate = 1;
 2348:                         }
 2349:                     }
 2350:                     next if (!$canvalidate);
 2351:                 }
 2352:                 my $checked = '';
 2353:                 if ($option eq $curroption) {
 2354:                     $checked = ' checked="checked"';
 2355:                 } elsif ($option eq 'autolimit') {
 2356:                     if ($curroption =~ /^autolimit/) {
 2357:                         $checked = ' checked="checked"';
 2358:                     }
 2359:                 }
 2360:                 $defcell{$item} .= '<span class="LC_nobreak"><label>'.
 2361:                                   '<input type="radio" name="crsreq_'.$item.
 2362:                                   '_default" value="'.$val.'"'.$checked.' />'.
 2363:                                   $titles{$option}.'</label>';
 2364:                 if ($option eq 'autolimit') {
 2365:                     $defcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2366:                                        $item.'_limit_default" size="1" '.
 2367:                                        'value="'.$currlimit.'" />';
 2368:                 }
 2369:                 $defcell{$item} .= '</span> ';
 2370:                 if ($option eq 'autolimit') {
 2371:                     $defcell{$item} .= $titles{'unlimited'};
 2372:                 }
 2373:             }
 2374:         } elsif ($context eq 'requestauthor') {
 2375:             my $curroption;
 2376:             if (ref($settings) eq 'HASH') {
 2377:                 $curroption = $settings->{'default'};
 2378:             }
 2379:             if (!$curroption) {
 2380:                 $curroption = 'norequest';
 2381:             }
 2382:             foreach my $option (@options) {
 2383:                 my $val = $option;
 2384:                 if ($option eq 'norequest') {
 2385:                     $val = 0;
 2386:                 }
 2387:                 my $checked = '';
 2388:                 if ($option eq $curroption) {
 2389:                     $checked = ' checked="checked"';
 2390:                 }
 2391:                 $datatable .= '<span class="LC_nobreak"><label>'.
 2392:                               '<input type="radio" name="authorreq_default"'.
 2393:                               ' value="'.$val.'"'.$checked.' />'.
 2394:                               $titles{$option}.'</label></span>&nbsp; ';
 2395:             }
 2396:         } else {
 2397:             my $checked = 'checked="checked" ';
 2398:             if (ref($settings) eq 'HASH') {
 2399:                 if (ref($settings->{$item}) eq 'HASH') {
 2400:                     if ($settings->{$item}->{'default'} == 0) {
 2401:                         $checked = '';
 2402:                     } elsif ($settings->{$item}->{'default'} == 1) {
 2403:                         $checked = 'checked="checked" ';
 2404:                     }
 2405:                 }
 2406:             }
 2407:             $datatable .= '<span class="LC_nobreak"><label>'.
 2408:                           '<input type="checkbox" name="'.$context.'_'.$item.
 2409:                           '" value="default" '.$checked.'/>'.$titles{$item}.
 2410:                           '</label></span>&nbsp; ';
 2411:         }
 2412:     }
 2413:     if ($context eq 'requestcourses') {
 2414:         $datatable .= '</tr><tr>';
 2415:         foreach my $item (@usertools) {
 2416:             $datatable .= '<td style="vertical-align: top">'.$defcell{$item}.'</td>';
 2417:         }
 2418:         $datatable .= '</tr></table>';
 2419:     }
 2420:     $datatable .= '</td>';
 2421:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 2422:         $datatable .= '<td class="LC_right_item">'.
 2423:                       '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 2424:                       '<input type="text" name="defaultquota" value="'.
 2425:                       $defaultquota.'" size="5" /></span>'.('&nbsp;' x2).
 2426:                       '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 2427:                       '<input type="text" name="authorquota" value="'.
 2428:                       $authorquota.'" size="5" /></span></td>';
 2429:     }
 2430:     $datatable .= '</tr>';
 2431:     $typecount ++;
 2432:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 2433:     $datatable .= '<tr'.$css_class.'>'.
 2434:                   '<td>'.&mt('LON-CAPA Advanced Users').'<br />';
 2435:     if ($context eq 'requestcourses') {
 2436:         $datatable .= &mt('(overrides affiliation, if set)').
 2437:                       '</td>'.
 2438:                       '<td class="LC_left_item">'.
 2439:                       '<table><tr>';
 2440:     } else {
 2441:         $datatable .= &mt('(overrides affiliation, if checked)').
 2442:                       '</td>'.
 2443:                       '<td class="LC_left_item" colspan="2">'.
 2444:                       '<br />';
 2445:     }
 2446:     my %advcell;
 2447:     foreach my $item (@usertools) {
 2448:         if ($context eq 'requestcourses') {
 2449:             my ($curroption,$currlimit);
 2450:             if (ref($settings) eq 'HASH') {
 2451:                 if (ref($settings->{$item}) eq 'HASH') {
 2452:                     $curroption = $settings->{$item}->{'_LC_adv'};
 2453:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 2454:                         $currlimit = $1;
 2455:                     }
 2456:                 }
 2457:             }
 2458:             $datatable .= '<th>'.$titles{$item}.'</th>';
 2459:             my $checked = '';
 2460:             if ($curroption eq '') {
 2461:                 $checked = ' checked="checked"';
 2462:             }
 2463:             $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2464:                                '<input type="radio" name="crsreq_'.$item.
 2465:                                '__LC_adv" value=""'.$checked.' />'.
 2466:                                &mt('No override set').'</label></span>&nbsp; ';
 2467:             foreach my $option (@options) {
 2468:                 my $val = $option;
 2469:                 if ($option eq 'norequest') {
 2470:                     $val = 0;
 2471:                 }
 2472:                 if ($option eq 'validate') {
 2473:                     my $canvalidate = 0;
 2474:                     if (ref($validations{$item}) eq 'HASH') {
 2475:                         if ($validations{$item}{'_LC_adv'}) {
 2476:                             $canvalidate = 1;
 2477:                         }
 2478:                     }
 2479:                     next if (!$canvalidate);
 2480:                 }
 2481:                 my $checked = '';
 2482:                 if ($val eq $curroption) {
 2483:                     $checked = ' checked="checked"';
 2484:                 } elsif ($option eq 'autolimit') {
 2485:                     if ($curroption =~ /^autolimit/) {
 2486:                         $checked = ' checked="checked"';
 2487:                     }
 2488:                 }
 2489:                 $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2490:                                   '<input type="radio" name="crsreq_'.$item.
 2491:                                   '__LC_adv" value="'.$val.'"'.$checked.' />'.
 2492:                                   $titles{$option}.'</label>';
 2493:                 if ($option eq 'autolimit') {
 2494:                     $advcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2495:                                        $item.'_limit__LC_adv" size="1" '.
 2496:                                        'value="'.$currlimit.'" />';
 2497:                 }
 2498:                 $advcell{$item} .= '</span> ';
 2499:                 if ($option eq 'autolimit') {
 2500:                     $advcell{$item} .= $titles{'unlimited'};
 2501:                 }
 2502:             }
 2503:         } elsif ($context eq 'requestauthor') {
 2504:             my $curroption;
 2505:             if (ref($settings) eq 'HASH') {
 2506:                 $curroption = $settings->{'_LC_adv'};
 2507:             }
 2508:             my $checked = '';
 2509:             if ($curroption eq '') {
 2510:                 $checked = ' checked="checked"';
 2511:             }
 2512:             $datatable .= '<span class="LC_nobreak"><label>'.
 2513:                           '<input type="radio" name="authorreq__LC_adv"'.
 2514:                           ' value=""'.$checked.' />'.
 2515:                           &mt('No override set').'</label></span>&nbsp; ';
 2516:             foreach my $option (@options) {
 2517:                 my $val = $option;
 2518:                 if ($option eq 'norequest') {
 2519:                     $val = 0;
 2520:                 }
 2521:                 my $checked = '';
 2522:                 if ($val eq $curroption) {
 2523:                     $checked = ' checked="checked"';
 2524:                 }
 2525:                 $datatable .= '<span class="LC_nobreak"><label>'.
 2526:                               '<input type="radio" name="authorreq__LC_adv"'.
 2527:                               ' value="'.$val.'"'.$checked.' />'.
 2528:                               $titles{$option}.'</label></span>&nbsp; ';
 2529:             }
 2530:         } else {
 2531:             my $checked = 'checked="checked" ';
 2532:             if (ref($settings) eq 'HASH') {
 2533:                 if (ref($settings->{$item}) eq 'HASH') {
 2534:                     if ($settings->{$item}->{'_LC_adv'} == 0) {
 2535:                         $checked = '';
 2536:                     } elsif ($settings->{$item}->{'_LC_adv'} == 1) {
 2537:                         $checked = 'checked="checked" ';
 2538:                     }
 2539:                 }
 2540:             }
 2541:             $datatable .= '<span class="LC_nobreak"><label>'.
 2542:                           '<input type="checkbox" name="'.$context.'_'.$item.
 2543:                           '" value="_LC_adv" '.$checked.'/>'.$titles{$item}.
 2544:                           '</label></span>&nbsp; ';
 2545:         }
 2546:     }
 2547:     if ($context eq 'requestcourses') {
 2548:         $datatable .= '</tr><tr>';
 2549:         foreach my $item (@usertools) {
 2550:             $datatable .= '<td style="vertical-align: top">'.$advcell{$item}.'</td>';
 2551:         }
 2552:         $datatable .= '</tr></table>';
 2553:     }
 2554:     $datatable .= '</td></tr>';
 2555:     $$rowtotal += $typecount;
 2556:     return $datatable;
 2557: }
 2558: 
 2559: sub print_requestmail {
 2560:     my ($dom,$action,$settings,$rowtotal,$customcss,$rowstyle) = @_;
 2561:     my ($now,$datatable,%currapp);
 2562:     $now = time;
 2563:     if (ref($settings) eq 'HASH') {
 2564:         if (ref($settings->{'notify'}) eq 'HASH') {
 2565:             if ($settings->{'notify'}{'approval'} ne '') {
 2566:                 map {$currapp{$_}=1;} split(/,/,$settings->{'notify'}{'approval'});
 2567:             }
 2568:         }
 2569:     }
 2570:     my $numinrow = 2;
 2571:     my $css_class;
 2572:     if ($$rowtotal%2) {
 2573:         $css_class = 'LC_odd_row';
 2574:     }
 2575:     if ($customcss) {
 2576:         $css_class .= " $customcss";
 2577:     }
 2578:     $css_class =~ s/^\s+//;
 2579:     if ($css_class) {
 2580:         $css_class = ' class="'.$css_class.'"';
 2581:     }
 2582:     if ($rowstyle) {
 2583:         $css_class .= ' style="'.$rowstyle.'"';
 2584:     }
 2585:     my $text;
 2586:     if ($action eq 'requestcourses') {
 2587:         $text = &mt('Receive notification of course requests requiring approval');
 2588:     } elsif ($action eq 'requestauthor') {
 2589:         $text = &mt('Receive notification of Authoring Space requests requiring approval');
 2590:     } else {
 2591:        $text = &mt('Receive notification of queued requests for self-created user accounts requiring approval');
 2592:     }
 2593:     $datatable = '<tr'.$css_class.'>'.
 2594:                  ' <td>'.$text.'</td>'.
 2595:                  ' <td class="LC_left_item">';
 2596:     my ($numdc,$table,$rows) = &active_dc_picker($dom,$numinrow,'checkbox',
 2597:                                                  $action.'notifyapproval',%currapp);
 2598:     if ($numdc > 0) {
 2599:         $datatable .= $table;
 2600:     } else {
 2601:         $datatable .= &mt('There are no active Domain Coordinators');
 2602:     }
 2603:     $datatable .='</td></tr>';
 2604:     return $datatable;
 2605: }
 2606: 
 2607: sub print_studentcode {
 2608:     my ($settings,$rowtotal) = @_;
 2609:     my $rownum = 0; 
 2610:     my ($output,%current);
 2611:     my @crstypes = ('official','unofficial','community','textbook');
 2612:     if (ref($settings) eq 'HASH') {
 2613:         if (ref($settings->{'uniquecode'}) eq 'HASH') {
 2614:             foreach my $type (@crstypes) {
 2615:                 $current{$type} = $settings->{'uniquecode'}{$type};
 2616:             }
 2617:         }
 2618:     }
 2619:     $output .= '<tr>'.
 2620:                '<td class="LC_left_item">'.&mt('Generate unique six character code as course identifier?').'</td>'.
 2621:                '<td class="LC_left_item">';
 2622:     foreach my $type (@crstypes) {
 2623:         my $check = ' ';
 2624:         if ($current{$type}) {
 2625:             $check = ' checked="checked" ';
 2626:         }
 2627:         $output .= '<span class="LC_nobreak"><label>'.
 2628:                    '<input type="checkbox" name="uniquecode" value="'.$type.'"'.$check.'/>'.
 2629:                    &mt($type).'</label></span>'.('&nbsp;'x2).' ';
 2630:     }
 2631:     $output .= '</td></tr>';
 2632:     $$rowtotal ++;
 2633:     return $output;
 2634: }
 2635: 
 2636: sub print_textbookcourses {
 2637:     my ($dom,$type,$settings,$rowtotal) = @_;
 2638:     my $rownum = 0;
 2639:     my $css_class;
 2640:     my $itemcount = 1;
 2641:     my $maxnum = 0;
 2642:     my $bookshash;
 2643:     if (ref($settings) eq 'HASH') {
 2644:         $bookshash = $settings->{$type};
 2645:     }
 2646:     my %ordered;
 2647:     if (ref($bookshash) eq 'HASH') {
 2648:         foreach my $item (keys(%{$bookshash})) {
 2649:             if (ref($bookshash->{$item}) eq 'HASH') {
 2650:                 my $num = $bookshash->{$item}{'order'};
 2651:                 $ordered{$num} = $item;
 2652:             }
 2653:         }
 2654:     }
 2655:     my $confname = $dom.'-domainconfig';
 2656:     my $switchserver = &check_switchserver($dom,$confname);
 2657:     my $maxnum = scalar(keys(%ordered));
 2658:     my $datatable;
 2659:     if (keys(%ordered)) {
 2660:         my @items = sort { $a <=> $b } keys(%ordered);
 2661:         for (my $i=0; $i<@items; $i++) {
 2662:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2663:             my $key = $ordered{$items[$i]};
 2664:             my %coursehash=&Apache::lonnet::coursedescription($key);
 2665:             my $coursetitle = $coursehash{'description'};
 2666:             my ($subject,$title,$author,$publisher,$image,$imgsrc,$cdom,$cnum);
 2667:             if (ref($bookshash->{$key}) eq 'HASH') {
 2668:                 $subject = $bookshash->{$key}->{'subject'};
 2669:                 $title = $bookshash->{$key}->{'title'};
 2670:                 if ($type eq 'textbooks') {
 2671:                     $publisher = $bookshash->{$key}->{'publisher'};
 2672:                     $author = $bookshash->{$key}->{'author'};
 2673:                     $image = $bookshash->{$key}->{'image'};
 2674:                     if ($image ne '') {
 2675:                         my ($path,$imagefile) = ($image =~ m{^(.+)/([^/]+)$});
 2676:                         my $imagethumb = "$path/tn-".$imagefile;
 2677:                         $imgsrc = '<img src="'.$imagethumb.'" alt="'.&mt('Textbook image').'" />';
 2678:                     }
 2679:                 }
 2680:             }
 2681:             my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type".'_'."$key','$type'".');"';
 2682:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 2683:                          .'<select name="'.$type.'_'.$key.'"'.$chgstr.'>';
 2684:             for (my $k=0; $k<=$maxnum; $k++) {
 2685:                 my $vpos = $k+1;
 2686:                 my $selstr;
 2687:                 if ($k == $i) {
 2688:                     $selstr = ' selected="selected" ';
 2689:                 }
 2690:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2691:             }
 2692:             $datatable .= '</select>'.('&nbsp;'x2).
 2693:                 '<label><input type="checkbox" name="'.$type.'_del" value="'.$key.'" />'.
 2694:                 &mt('Delete?').'</label></span></td>'.
 2695:                 '<td colspan="2">'.
 2696:                 '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_subject_'.$i.'" value="'.$subject.'" /></span> '.
 2697:                 ('&nbsp;'x2).
 2698:                 '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_title_'.$i.'" value="'.$title.'" /></span> ';
 2699:             if ($type eq 'textbooks') {
 2700:                 $datatable .= ('&nbsp;'x2).
 2701:                               '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_publisher_'.$i.'" value="'.$publisher.'" /></span> '.
 2702:                               ('&nbsp;'x2).
 2703:                               '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_author_'.$i.'" value="'.$author.'" /></span> '.
 2704:                               ('&nbsp;'x2).
 2705:                               '<span class="LC_nobreak">'.&mt('Thumbnail:');
 2706:                 if ($image) {
 2707:                     $datatable .= $imgsrc.
 2708:                                   '<label><input type="checkbox" name="'.$type.'_image_del"'.
 2709:                                   ' value="'.$key.'" />'.&mt('Delete?').'</label></span> '.
 2710:                                   '<span class="LC_nobreak">&nbsp;'.&mt('Replace:').'&nbsp;';
 2711:                 }
 2712:                 if ($switchserver) {
 2713:                     $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2714:                 } else {
 2715:                     $datatable .= '<input type="file" name="'.$type.'_image_'.$i.'" value="" />';
 2716:                 }
 2717:             }
 2718:             $datatable .= '<input type="hidden" name="'.$type.'_id_'.$i.'" value="'.$type.'_'.$key.'" /></span> '.
 2719:                           '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 2720:                           $coursetitle.'</span></td></tr>'."\n";
 2721:             $itemcount ++;
 2722:         }
 2723:     }
 2724:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2725:     my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type"."_addbook_pos','$type'".');"';
 2726:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 2727:                   '<input type="hidden" name="'.$type.'_maxnum" value="'.$maxnum.'" />'."\n".
 2728:                   '<select name="'.$type.'_addbook_pos"'.$chgstr.'>';
 2729:     for (my $k=0; $k<$maxnum+1; $k++) {
 2730:         my $vpos = $k+1;
 2731:         my $selstr;
 2732:         if ($k == $maxnum) {
 2733:             $selstr = ' selected="selected" ';
 2734:         }
 2735:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2736:     }
 2737:     $datatable .= '</select>&nbsp;'."\n".
 2738:                   '<input type="checkbox" name="'.$type.'_addbook" value="1" />'.&mt('Add').'</span></td>'."\n".
 2739:                   '<td colspan="2">'.
 2740:                   '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_addbook_subject" value="" /></span> '."\n".
 2741:                   ('&nbsp;'x2).
 2742:                   '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_addbook_title" value="" /></span> '."\n".
 2743:                   ('&nbsp;'x2);
 2744:     if ($type eq 'textbooks') {
 2745:         $datatable .= '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_addbook_publisher" value="" /></span> '."\n".
 2746:                       ('&nbsp;'x2).
 2747:                       '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_addbook_author" value="" /></span> '."\n".
 2748:                       ('&nbsp;'x2).
 2749:                       '<span class="LC_nobreak">'.&mt('Image:').'&nbsp;';
 2750:         if ($switchserver) {
 2751:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2752:         } else {
 2753:             $datatable .= '<input type="file" name="'.$type.'_addbook_image" value="" />';
 2754:         }
 2755:         $datatable .= '</span>'."\n";
 2756:     }
 2757:     $datatable .= '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 2758:                   &Apache::loncommon::select_dom_form($env{'request.role.domain'},$type.'_addbook_cdom').
 2759:                   '<input type="text" size="25" name="'.$type.'_addbook_cnum" value="" />'.
 2760:                   &Apache::loncommon::selectcourse_link
 2761:                       ('display',$type.'_addbook_cnum',$type.'_addbook_cdom',undef,undef,undef,'Course').
 2762:                   '</span></td>'."\n".
 2763:                   '</tr>'."\n";
 2764:     $itemcount ++;
 2765:     return $datatable;
 2766: }
 2767: 
 2768: sub textbookcourses_javascript {
 2769:     my ($settings) = @_;
 2770:     return unless(ref($settings) eq 'HASH');
 2771:     my (%ordered,%total,%jstext);
 2772:     foreach my $type ('textbooks','templates') {
 2773:         $total{$type} = 0;
 2774:         if (ref($settings->{$type}) eq 'HASH') {
 2775:             foreach my $item (keys(%{$settings->{$type}})) {
 2776:                 if (ref($settings->{$type}->{$item}) eq 'HASH') {
 2777:                     my $num = $settings->{$type}->{$item}{'order'};
 2778:                     $ordered{$type}{$num} = $item;
 2779:                 }
 2780:             }
 2781:             $total{$type} = scalar(keys(%{$settings->{$type}}));
 2782:         }
 2783:         my @jsarray = ();
 2784:         foreach my $item (sort {$a <=> $b } (keys(%{$ordered{$type}}))) {
 2785:             push(@jsarray,$ordered{$type}{$item});
 2786:         }
 2787:         $jstext{$type} = '    var '.$type.' = Array('."'".join("','",@jsarray)."'".');'."\n";
 2788:     }
 2789:     return <<"ENDSCRIPT";
 2790: <script type="text/javascript">
 2791: // <![CDATA[
 2792: function reorderBooks(form,item,caller) {
 2793:     var changedVal;
 2794: $jstext{'textbooks'};
 2795: $jstext{'templates'};
 2796:     var newpos;
 2797:     var maxh;
 2798:     if (caller == 'textbooks') {  
 2799:         newpos = 'textbooks_addbook_pos';
 2800:         maxh = 1 + $total{'textbooks'};
 2801:     } else {
 2802:         newpos = 'templates_addbook_pos';
 2803:         maxh = 1 + $total{'templates'};
 2804:     }
 2805:     var current = new Array;
 2806:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 2807:     if (item == newpos) {
 2808:         changedVal = newitemVal;
 2809:     } else {
 2810:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 2811:         current[newitemVal] = newpos;
 2812:     }
 2813:     if (caller == 'textbooks') {
 2814:         for (var i=0; i<textbooks.length; i++) {
 2815:             var elementName = 'textbooks_'+textbooks[i];
 2816:             if (elementName != item) {
 2817:                 if (form.elements[elementName]) {
 2818:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 2819:                     current[currVal] = elementName;
 2820:                 }
 2821:             }
 2822:         }
 2823:     }
 2824:     if (caller == 'templates') {
 2825:         for (var i=0; i<templates.length; i++) {
 2826:             var elementName = 'templates_'+templates[i];
 2827:             if (elementName != item) {
 2828:                 if (form.elements[elementName]) {
 2829:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 2830:                     current[currVal] = elementName;
 2831:                 }
 2832:             }
 2833:         }
 2834:     }
 2835:     var oldVal;
 2836:     for (var j=0; j<maxh; j++) {
 2837:         if (current[j] == undefined) {
 2838:             oldVal = j;
 2839:         }
 2840:     }
 2841:     if (oldVal < changedVal) {
 2842:         for (var k=oldVal+1; k<=changedVal ; k++) {
 2843:            var elementName = current[k];
 2844:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 2845:         }
 2846:     } else {
 2847:         for (var k=changedVal; k<oldVal; k++) {
 2848:             var elementName = current[k];
 2849:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 2850:         }
 2851:     }
 2852:     return;
 2853: }
 2854: 
 2855: // ]]>
 2856: </script>
 2857: 
 2858: ENDSCRIPT
 2859: }
 2860: 
 2861: sub wafproxy_javascript {
 2862:     my ($dom) = @_;
 2863:     return <<"ENDSCRIPT";
 2864: <script type="text/javascript">
 2865: // <![CDATA[
 2866: function updateWAF() {
 2867:     if (document.getElementById('wafproxy_remoteip')) {
 2868:         var wafremote = 0;
 2869:         if (document.display.wafproxy_remoteip.options[document.display.wafproxy_remoteip.selectedIndex].value == 'h') {
 2870:             wafremote = 1;
 2871:         }
 2872:         var fields = new Array('header','trust');
 2873:         for (var i=0; i<fields.length; i++) {
 2874:             if (document.getElementById('wafproxy_'+fields[i])) {
 2875:                 if (wafremote == 1) {
 2876:                     document.getElementById('wafproxy_'+fields[i]).style.display = 'table-row';
 2877:                 }
 2878:                 else {
 2879:                     document.getElementById('wafproxy_'+fields[i]).style.display = 'none';
 2880:                 }
 2881:             }
 2882:         }
 2883:         if (document.getElementById('wafproxyranges_$dom')) {
 2884:             if (wafremote == 1) {
 2885:                 document.getElementById('wafproxyranges_$dom').style.display = 'inline-block';
 2886:             } else {
 2887:                 for (var i=0; i<document.display.wafproxy_vpnaccess.length; i++) {
 2888:                     if (document.display.wafproxy_vpnaccess[i].checked) {
 2889:                         if (document.display.wafproxy_vpnaccess[i].value == 0) {
 2890:                             document.getElementById('wafproxyranges_$dom').style.display = 'none';
 2891:                         }
 2892:                     }
 2893:                 }
 2894:             }
 2895:         }
 2896:     }
 2897:     return;
 2898: }
 2899: 
 2900: function checkWAF() {
 2901:     if (document.getElementById('wafproxy_remoteip')) {
 2902:         var wafvpn = 0;
 2903:         for (var i=0; i<document.display.wafproxy_vpnaccess.length; i++) {
 2904:             if (document.display.wafproxy_vpnaccess[i].checked) {
 2905:                 if (document.display.wafproxy_vpnaccess[i].value == 1) {
 2906:                     wafvpn = 1;
 2907:                 }
 2908:                 break;
 2909:             }
 2910:         }
 2911:         var vpn = new Array('vpnint','vpnext');
 2912:         for (var i=0; i<vpn.length; i++) {
 2913:             if (document.getElementById('wafproxy_show_'+vpn[i])) {
 2914:                 if (wafvpn == 1) {
 2915:                     document.getElementById('wafproxy_show_'+vpn[i]).style.display = 'table-row';
 2916:                 }
 2917:                 else {
 2918:                     document.getElementById('wafproxy_show_'+vpn[i]).style.display = 'none';
 2919:                 }
 2920:             }
 2921:         }
 2922:         if (document.getElementById('wafproxyranges_$dom')) {
 2923:             if (wafvpn == 1) {
 2924:                 document.getElementById('wafproxyranges_$dom').style.display = 'inline-block';
 2925:             }
 2926:             else if (document.display.wafproxy_remoteip.options[document.display.wafproxy_remoteip.selectedIndex].value != 'h') {
 2927:                 document.getElementById('wafproxyranges_$dom').style.display = 'none';
 2928:             }
 2929:         }
 2930:     }
 2931:     return;
 2932: }
 2933: 
 2934: function toggleWAF() {
 2935:     if (document.getElementById('wafproxy_table')) {
 2936:         var wafproxy = 0;
 2937:         for (var i=0; i<document.display.wafproxy_${dom}.length; i++) {
 2938:              if (document.display.wafproxy_${dom}[i].checked) {
 2939:                  if (document.display.wafproxy_${dom}[i].value == 1) {
 2940:                      wafproxy = 1;
 2941:                      break;
 2942:                 }
 2943:             }
 2944:         }
 2945:         if (wafproxy == 1) {
 2946:             document.getElementById('wafproxy_table').style.display='inline';
 2947:         }
 2948:         else {
 2949:            document.getElementById('wafproxy_table').style.display='none';
 2950:         }
 2951:         if (document.getElementById('wafproxyrow_${dom}')) {
 2952:             if (wafproxy == 1) {
 2953:                 document.getElementById('wafproxyrow_${dom}').style.display = 'table-row';
 2954:             }
 2955:             else {
 2956:                 document.getElementById('wafproxyrow_${dom}').style.display = 'none';
 2957:             }
 2958:         }
 2959:         if (document.getElementById('nowafproxyrow_$dom')) {
 2960:             if (wafproxy == 1) {
 2961:                 document.getElementById('nowafproxyrow_${dom}').style.display = 'none';
 2962:             }
 2963:             else {
 2964:                 document.getElementById('nowafproxyrow_${dom}').style.display = 'table-row';
 2965:             }
 2966:         }
 2967:     }
 2968:     return;
 2969: }
 2970: // ]]>
 2971: </script>
 2972: 
 2973: ENDSCRIPT
 2974: }
 2975: 
 2976: sub autoupdate_javascript {
 2977:     return <<"ENDSCRIPT";
 2978: <script type="text/javascript">
 2979: // <![CDATA[
 2980: function toggleLastActiveDays(form) {
 2981:     var radioname = 'lastactive';
 2982:     var divid = 'lastactive_div';
 2983:     var num = form.elements[radioname].length;
 2984:     if (num) {
 2985:         var setvis = '';
 2986:         for (var i=0; i<num; i++) {
 2987:             if (form.elements[radioname][i].checked) {
 2988:                 if (form.elements[radioname][i].value == '1') {
 2989:                     if (document.getElementById(divid)) {
 2990:                         document.getElementById(divid).style.display = 'inline-block';
 2991:                     }
 2992:                     setvis = 1;
 2993:                 }
 2994:                 break;
 2995:             }
 2996:         }
 2997:         if (!setvis) {
 2998:             if (document.getElementById(divid)) {
 2999:                 document.getElementById(divid).style.display = 'none';
 3000:             }
 3001:         }
 3002:     }
 3003:     return;
 3004: }
 3005: // ]]>
 3006: </script>
 3007: 
 3008: ENDSCRIPT
 3009: }
 3010: 
 3011: sub autoenroll_javascript {
 3012:     return <<"ENDSCRIPT";
 3013: <script type="text/javascript">
 3014: // <![CDATA[
 3015: function toggleFailsafe(form) {
 3016:     var radioname = 'autoenroll_failsafe';
 3017:     var divid = 'autoenroll_failsafe_div';
 3018:     var num = form.elements[radioname].length;
 3019:     if (num) {
 3020:         var setvis = '';
 3021:         for (var i=0; i<num; i++) {
 3022:             if (form.elements[radioname][i].checked) {
 3023:                 if ((form.elements[radioname][i].value == 'zero') || (form.elements[radioname][i].value == 'any')) {
 3024:                     if (document.getElementById(divid)) {
 3025:                         document.getElementById(divid).style.display = 'inline-block';
 3026:                     }
 3027:                     setvis = 1;
 3028:                 }
 3029:                 break;
 3030:             }
 3031:         }
 3032:         if (!setvis) {
 3033:             if (document.getElementById(divid)) {
 3034:                 document.getElementById(divid).style.display = 'none';
 3035:             }
 3036:         }
 3037:     }
 3038:     return;
 3039: }
 3040: // ]]>
 3041: </script>
 3042: 
 3043: ENDSCRIPT
 3044: }
 3045: 
 3046: sub saml_javascript {
 3047:     return <<"ENDSCRIPT";
 3048: <script type="text/javascript">
 3049: // <![CDATA[
 3050: function toggleSamlOptions(form,hostid) {
 3051:     var radioname = 'saml_'+hostid;
 3052:     var tablecellon = 'samloptionson_'+hostid;
 3053:     var tablecelloff = 'samloptionsoff_'+hostid;
 3054:     var num = form.elements[radioname].length;
 3055:     if (num) {
 3056:         var setvis = '';
 3057:         for (var i=0; i<num; i++) {
 3058:             if (form.elements[radioname][i].checked) {
 3059:                 if (form.elements[radioname][i].value == '1') {
 3060:                     if (document.getElementById(tablecellon)) {
 3061:                         document.getElementById(tablecellon).style.display='';
 3062:                     }
 3063:                     if (document.getElementById(tablecelloff)) {
 3064:                         document.getElementById(tablecelloff).style.display='none';
 3065:                     }
 3066:                     setvis = 1;
 3067:                 }
 3068:                 break;
 3069:             }
 3070:         }
 3071:         if (!setvis) {
 3072:             if (document.getElementById(tablecellon)) {
 3073:                 document.getElementById(tablecellon).style.display='none';
 3074:             }
 3075:             if (document.getElementById(tablecelloff)) {
 3076:                 document.getElementById(tablecelloff).style.display='';
 3077:             }
 3078:         }
 3079:     }
 3080:     return;
 3081: }
 3082: // ]]>
 3083: </script>
 3084: 
 3085: ENDSCRIPT
 3086: }
 3087: 
 3088: sub ipaccess_javascript {
 3089:     my ($settings) = @_;
 3090:     my (%ordered,$total,%jstext);
 3091:     $total = 0;
 3092:     if (ref($settings) eq 'HASH') {
 3093:         foreach my $item (keys(%{$settings})) {
 3094:             if (ref($settings->{$item}) eq 'HASH') {
 3095:                 my $num = $settings->{$item}{'order'};
 3096:                 $ordered{$num} = $item;
 3097:             }
 3098:         }
 3099:         $total = scalar(keys(%{$settings}));
 3100:     }
 3101:     my @jsarray = ();
 3102:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3103:         push(@jsarray,$ordered{$item});
 3104:     }
 3105:     my $jstext = '    var ipaccess = Array('."'".join("','",@jsarray)."'".');'."\n";
 3106:     return <<"ENDSCRIPT";
 3107: <script type="text/javascript">
 3108: // <![CDATA[
 3109: function reorderIPaccess(form,item) {
 3110:     var changedVal;
 3111: $jstext
 3112:     var newpos = 'ipaccess_pos_add';
 3113:     var maxh = 1 + $total;
 3114:     var current = new Array;
 3115:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 3116:     if (item == newpos) {
 3117:         changedVal = newitemVal;
 3118:     } else {
 3119:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3120:         current[newitemVal] = newpos;
 3121:     }
 3122:     for (var i=0; i<ipaccess.length; i++) {
 3123:         var elementName = 'ipaccess_pos_'+ipaccess[i];
 3124:         if (elementName != item) {
 3125:             if (form.elements[elementName]) {
 3126:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3127:                 current[currVal] = elementName;
 3128:             }
 3129:         }
 3130:     }
 3131:     var oldVal;
 3132:     for (var j=0; j<maxh; j++) {
 3133:         if (current[j] == undefined) {
 3134:             oldVal = j;
 3135:         }
 3136:     }
 3137:     if (oldVal < changedVal) {
 3138:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3139:            var elementName = current[k];
 3140:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3141:         }
 3142:     } else {
 3143:         for (var k=changedVal; k<oldVal; k++) {
 3144:             var elementName = current[k];
 3145:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3146:         }
 3147:     }
 3148:     return;
 3149: }
 3150: // ]]>
 3151: </script>
 3152: 
 3153: ENDSCRIPT
 3154: }
 3155: 
 3156: sub print_autoenroll {
 3157:     my ($dom,$settings,$rowtotal) = @_;
 3158:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
 3159:     my ($defdom,$runon,$runoff,$coownerson,$coownersoff,
 3160:         $failsafe,$autofailsafe,$failsafesty,%failsafechecked);
 3161:     $failsafesty = 'none';
 3162:     %failsafechecked = (
 3163:         off => ' checked="checked"',
 3164:     );
 3165:     if (ref($settings) eq 'HASH') {
 3166:         if (exists($settings->{'run'})) {
 3167:             if ($settings->{'run'} eq '0') {
 3168:                 $runoff = ' checked="checked" ';
 3169:                 $runon = ' ';
 3170:             } else {
 3171:                 $runon = ' checked="checked" ';
 3172:                 $runoff = ' ';
 3173:             }
 3174:         } else {
 3175:             if ($autorun) {
 3176:                 $runon = ' checked="checked" ';
 3177:                 $runoff = ' ';
 3178:             } else {
 3179:                 $runoff = ' checked="checked" ';
 3180:                 $runon = ' ';
 3181:             }
 3182:         }
 3183:         if (exists($settings->{'co-owners'})) {
 3184:             if ($settings->{'co-owners'} eq '0') {
 3185:                 $coownersoff = ' checked="checked" ';
 3186:                 $coownerson = ' ';
 3187:             } else {
 3188:                 $coownerson = ' checked="checked" ';
 3189:                 $coownersoff = ' ';
 3190:             }
 3191:         } else {
 3192:             $coownersoff = ' checked="checked" ';
 3193:             $coownerson = ' ';
 3194:         }
 3195:         if (exists($settings->{'sender_domain'})) {
 3196:             $defdom = $settings->{'sender_domain'};
 3197:         }
 3198:         if (exists($settings->{'failsafe'})) {
 3199:             $failsafe = $settings->{'failsafe'};
 3200:             if ($failsafe eq 'zero') {
 3201:                 $failsafechecked{'zero'} = ' checked="checked"';
 3202:                 $failsafechecked{'off'} = '';
 3203:                 $failsafesty = 'inline-block';
 3204:             } elsif ($failsafe eq 'any') {
 3205:                 $failsafechecked{'any'} = ' checked="checked"';
 3206:                 $failsafechecked{'off'} = '';
 3207:             }
 3208:             $autofailsafe = $settings->{'autofailsafe'};
 3209:         } elsif (exists($settings->{'autofailsafe'})) {
 3210:             $autofailsafe = $settings->{'autofailsafe'};
 3211:             if ($autofailsafe ne '') {
 3212:                 $failsafechecked{'zero'} = ' checked="checked"';
 3213:                 $failsafe = 'zero';
 3214:                 $failsafechecked{'off'} = '';
 3215:             }
 3216:         }
 3217:     } else {
 3218:         if ($autorun) {
 3219:             $runon = ' checked="checked" ';
 3220:             $runoff = ' ';
 3221:         } else {
 3222:             $runoff = ' checked="checked" ';
 3223:             $runon = ' ';
 3224:         }
 3225:     }
 3226:     my $domform = &Apache::loncommon::select_dom_form($defdom,'sender_domain',1);
 3227:     my $notif_sender;
 3228:     if (ref($settings) eq 'HASH') {
 3229:         $notif_sender = $settings->{'sender_uname'};
 3230:     }
 3231:     my $datatable='<tr class="LC_odd_row">'.
 3232:                   '<td>'.&mt('Auto-enrollment active?').'</td>'.
 3233:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3234:                   '<input type="radio" name="autoenroll_run"'.
 3235:                   $runon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3236:                   '<label><input type="radio" name="autoenroll_run"'.
 3237:                   $runoff.' value="0" />'.&mt('No').'</label></span></td>'.
 3238:                   '</tr><tr>'.
 3239:                   '<td>'.&mt('Notification messages - sender').
 3240:                   '</td><td class="LC_right_item"><span class="LC_nobreak">'.
 3241:                   &mt('username').':&nbsp;'.
 3242:                   '<input type="text" name="sender_uname" value="'.
 3243:                   $notif_sender.'" size="10" />&nbsp;&nbsp;'.&mt('domain').
 3244:                   ':&nbsp;'.$domform.'</span></td></tr>'.
 3245:                   '<tr class="LC_odd_row">'.
 3246:                   '<td>'.&mt('Automatically assign co-ownership').'</td>'.
 3247:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3248:                   '<input type="radio" name="autoassign_coowners"'.
 3249:                   $coownerson.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3250:                   '<label><input type="radio" name="autoassign_coowners"'.
 3251:                   $coownersoff.' value="0" />'.&mt('No').'</label></span></td>'.
 3252:                   '</tr><tr>'.
 3253:                   '<td>'.&mt('Failsafe for no drops when institutional data missing').'</td>'.
 3254:                   '<td class="LC_left_item"><span class="LC_nobreak">'.
 3255:                   '<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; '.
 3256:                   '<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 />'.
 3257:                   '<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>'.
 3258:                   '<div class="LC_floatleft" style="display:'.$failsafesty.';" id="autoenroll_failsafe_div">'.
 3259:                   '<span class="LC_nobreak">'.
 3260:                   &mt('Threshold for number of students in section to drop: [_1]',
 3261:                       '<input type="text" name="autoenroll_autofailsafe" value="'.$autofailsafe.'" size="4" />').
 3262:                   '</span></div></td></tr>';
 3263:     $$rowtotal += 4;
 3264:     return $datatable;
 3265: }
 3266: 
 3267: sub print_autoupdate {
 3268:     my ($position,$dom,$settings,$rowtotal) = @_;
 3269:     my ($enable,$datatable);
 3270:     if ($position eq 'top') {
 3271:         my %choices = &Apache::lonlocal::texthash (
 3272:                           run        => 'Auto-update active?',
 3273:                           classlists => 'Update information in classlists?',
 3274:                           unexpired  => 'Skip updates for users without active or future roles?',
 3275:                           lastactive => 'Skip updates for inactive users?',
 3276:         );
 3277:         my $itemcount = 0;
 3278:         my $updateon = ' ';
 3279:         my $updateoff = ' checked="checked" ';
 3280:         if (ref($settings) eq 'HASH') {
 3281:             if ($settings->{'run'} eq '1') {
 3282:                 $updateon = $updateoff;
 3283:                 $updateoff = ' ';
 3284:             }
 3285:         }
 3286:         $enable = '<tr class="LC_odd_row">'. 
 3287:                   '<td>'.&mt($choices{'run'}).'</td>'.
 3288:                   '<td class="LC_left_item"><span class="LC_nobreak"><label>'.
 3289:                   '<input type="radio" name="autoupdate_run"'.
 3290:                   $updateoff.'value="0" />'.&mt('No').'</label>&nbsp;'.
 3291:                   '<label><input type="radio" name="autoupdate_run"'.
 3292:                   $updateon.'value="1" />'.&mt('Yes').'</label></span></td>'.
 3293:                   '</tr>';
 3294:         my @toggles = ('classlists','unexpired');
 3295:         my %defaultchecked = ('classlists' => 'off',
 3296:                               'unexpired'  => 'off'
 3297:                               );
 3298:         $$rowtotal ++;
 3299:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 3300:                                                      \%choices,$itemcount,'','','left','no');
 3301:         $datatable = $enable.$datatable;
 3302:         $$rowtotal += $itemcount;
 3303:         my $lastactiveon = ' ';
 3304:         my $lastactiveoff = ' checked="checked" ';
 3305:         my $lastactivestyle = 'none';
 3306:         my $lastactivedays;
 3307:         my $onclick = ' onclick="javascript:toggleLastActiveDays(this.form);"';
 3308:         if (ref($settings) eq 'HASH') {
 3309:             if ($settings->{'lastactive'} =~ /^\d+$/) {
 3310:                 $lastactiveon = $lastactiveoff;
 3311:                 $lastactiveoff = ' ';
 3312:                 $lastactivestyle = 'inline-block';
 3313:                 $lastactivedays = $settings->{'lastactive'};
 3314:             }
 3315:         }
 3316:         my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 3317:         $datatable .= '<tr'.$css_class.'>'.
 3318:                       '<td>'.$choices{'lastactive'}.'</td>'.
 3319:                       '<td class="LC_left_item"><span class="LC_nobreak"><label>'.
 3320:                       '<input type="radio" name="lastactive"'.
 3321:                       $lastactiveoff.'value="0"'.$onclick.' />'.&mt('No').'</label>'.
 3322:                       '&nbsp;<label>'.
 3323:                       '<input type="radio" name="lastactive"'.
 3324:                       $lastactiveon.' value="1"'.$onclick.' />'.&mt('Yes').'</label>'.
 3325:                       '<div id="lastactive_div" style="display:'.$lastactivestyle.';">'.
 3326:                       ':&nbsp;'.&mt('inactive = no activity in last [_1] days',
 3327:                           '<input type="text" size="5" name="lastactivedays" value="'.
 3328:                           $lastactivedays.'" />').
 3329:                       '</span></td>'.
 3330:                       '</tr>';
 3331:         $$rowtotal ++;
 3332:     } elsif ($position eq 'middle') {
 3333:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3334:         my $numinrow = 3;
 3335:         my $locknamesettings;
 3336:         $datatable .= &insttypes_row($settings,$types,$usertypes,
 3337:                                      $dom,$numinrow,$othertitle,
 3338:                                     'lockablenames',$rowtotal);
 3339:         $$rowtotal ++;
 3340:     } else {
 3341:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3342:         my @fields = ('lastname','firstname','middlename','generation',
 3343:                       'permanentemail','id');
 3344:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3345:         my $numrows = 0;
 3346:         if (ref($types) eq 'ARRAY') {
 3347:             if (@{$types} > 0) {
 3348:                 $datatable = 
 3349:                     &usertype_update_row($settings,$usertypes,\%fieldtitles,
 3350:                                          \@fields,$types,\$numrows);
 3351:                     $$rowtotal += @{$types}; 
 3352:             }
 3353:         }
 3354:         $datatable .= 
 3355:             &usertype_update_row($settings,{'default' => $othertitle},
 3356:                                  \%fieldtitles,\@fields,['default'],
 3357:                                  \$numrows);
 3358:         $$rowtotal ++;     
 3359:     }
 3360:     return $datatable;
 3361: }
 3362: 
 3363: sub print_autocreate {
 3364:     my ($dom,$settings,$rowtotal) = @_;
 3365:     my (%createon,%createoff,%currhash);
 3366:     my @types = ('xml','req');
 3367:     if (ref($settings) eq 'HASH') {
 3368:         foreach my $item (@types) {
 3369:             $createoff{$item} = ' checked="checked" ';
 3370:             $createon{$item} = ' ';
 3371:             if (exists($settings->{$item})) {
 3372:                 if ($settings->{$item}) {
 3373:                     $createon{$item} = ' checked="checked" ';
 3374:                     $createoff{$item} = ' ';
 3375:                 }
 3376:             }
 3377:         }
 3378:         if ($settings->{'xmldc'} ne '') {
 3379:             $currhash{$settings->{'xmldc'}} = 1;
 3380:         }
 3381:     } else {
 3382:         foreach my $item (@types) {
 3383:             $createoff{$item} = ' checked="checked" ';
 3384:             $createon{$item} = ' ';
 3385:         }
 3386:     }
 3387:     $$rowtotal += 2;
 3388:     my $numinrow = 2;
 3389:     my $datatable='<tr class="LC_odd_row">'.
 3390:                   '<td>'.&mt('Create pending official courses from XML files').'</td>'.
 3391:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3392:                   '<input type="radio" name="autocreate_xml"'.
 3393:                   $createon{'xml'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3394:                   '<label><input type="radio" name="autocreate_xml"'.
 3395:                   $createoff{'xml'}.' value="0" />'.&mt('No').'</label></span>'.
 3396:                   '</td></tr><tr>'.
 3397:                   '<td>'.&mt('Create pending requests for official courses (if validated)').'</td>'.
 3398:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3399:                   '<input type="radio" name="autocreate_req"'.
 3400:                   $createon{'req'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3401:                   '<label><input type="radio" name="autocreate_req"'.
 3402:                   $createoff{'req'}.' value="0" />'.&mt('No').'</label></span>';
 3403:     my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 3404:                                                    'autocreate_xmldc',%currhash);
 3405:     $datatable .= '</td></tr><tr class="LC_odd_row"><td>';
 3406:     if ($numdc > 1) {
 3407:         $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)').
 3408:                       '</td><td class="LC_left_item">';
 3409:     } else {
 3410:         $datatable .= &mt('Course creation processed as:').
 3411:                       '</td><td class="LC_right_item">';
 3412:     }
 3413:     $datatable .= $dctable.'</td></tr>';
 3414:     $$rowtotal += $rows;
 3415:     return $datatable;
 3416: }
 3417: 
 3418: sub print_directorysrch {
 3419:     my ($position,$dom,$settings,$rowtotal) = @_;
 3420:     my $datatable;
 3421:     if ($position eq 'top') {
 3422:         my $instsrchon = ' ';
 3423:         my $instsrchoff = ' checked="checked" ';
 3424:         my ($exacton,$containson,$beginson);
 3425:         my $instlocalon = ' ';
 3426:         my $instlocaloff = ' checked="checked" ';
 3427:         if (ref($settings) eq 'HASH') {
 3428:             if ($settings->{'available'} eq '1') {
 3429:                 $instsrchon = $instsrchoff;
 3430:                 $instsrchoff = ' ';
 3431:             }
 3432:             if ($settings->{'localonly'} eq '1') {
 3433:                 $instlocalon = $instlocaloff;
 3434:                 $instlocaloff = ' ';
 3435:             }
 3436:             if (ref($settings->{'searchtypes'}) eq 'ARRAY') {
 3437:                 foreach my $type (@{$settings->{'searchtypes'}}) {
 3438:                     if ($type eq 'exact') {
 3439:                         $exacton = ' checked="checked" ';
 3440:                     } elsif ($type eq 'contains') {
 3441:                         $containson = ' checked="checked" ';
 3442:                     } elsif ($type eq 'begins') {
 3443:                         $beginson = ' checked="checked" ';
 3444:                     }
 3445:                 }
 3446:             } else {
 3447:                 if ($settings->{'searchtypes'} eq 'exact') {
 3448:                     $exacton = ' checked="checked" ';
 3449:                 } elsif ($settings->{'searchtypes'} eq 'contains') {
 3450:                     $containson = ' checked="checked" ';
 3451:                 } elsif ($settings->{'searchtypes'} eq 'specify') {
 3452:                     $exacton = ' checked="checked" ';
 3453:                     $containson = ' checked="checked" ';
 3454:                 }
 3455:             }
 3456:         }
 3457:         my ($searchtitles,$titleorder) = &sorted_searchtitles();
 3458:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3459: 
 3460:         my $numinrow = 4;
 3461:         my $cansrchrow = 0;
 3462:         $datatable='<tr class="LC_odd_row">'.
 3463:                    '<td colspan="2"><span class ="LC_nobreak">'.&mt('Institutional directory search available?').'</span></td>'.
 3464:                    '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3465:                    '<input type="radio" name="dirsrch_available"'.
 3466:                    $instsrchon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3467:                    '<label><input type="radio" name="dirsrch_available"'.
 3468:                    $instsrchoff.' value="0" />'.&mt('No').'</label></span></td>'.
 3469:                    '</tr><tr>'.
 3470:                    '<td colspan="2"><span class ="LC_nobreak">'.&mt('Other domains can search institution?').'</span></td>'.
 3471:                    '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3472:                    '<input type="radio" name="dirsrch_instlocalonly"'.
 3473:                    $instlocaloff.' value="0" />'.&mt('Yes').'</label>&nbsp;'.
 3474:                    '<label><input type="radio" name="dirsrch_instlocalonly"'.
 3475:                    $instlocalon.' value="1" />'.&mt('No').'</label></span></td>'.
 3476:                    '</tr>';
 3477:         $$rowtotal += 2;
 3478:         if (ref($usertypes) eq 'HASH') {
 3479:             if (keys(%{$usertypes}) > 0) {
 3480:                 $datatable .= &insttypes_row($settings,$types,$usertypes,$dom,
 3481:                                              $numinrow,$othertitle,'cansearch',
 3482:                                              $rowtotal);
 3483:                 $cansrchrow = 1;
 3484:             }
 3485:         }
 3486:         if ($cansrchrow) {
 3487:             $$rowtotal ++;
 3488:             $datatable .= '<tr>';
 3489:         } else {
 3490:             $datatable .= '<tr class="LC_odd_row">';
 3491:         }
 3492:         $datatable .= '<td><span class ="LC_nobreak">'.&mt('Supported search methods').
 3493:                       '</span></td><td class="LC_left_item" colspan="2"><table><tr>';
 3494:         foreach my $title (@{$titleorder}) {
 3495:             if (defined($searchtitles->{$title})) {
 3496:                 my $check = ' ';
 3497:                 if (ref($settings) eq 'HASH') {
 3498:                     if (ref($settings->{'searchby'}) eq 'ARRAY') {
 3499:                         if (grep(/^\Q$title\E$/,@{$settings->{'searchby'}})) {
 3500:                             $check = ' checked="checked" ';
 3501:                         }
 3502:                     }
 3503:                 }
 3504:                 $datatable .= '<td class="LC_left_item">'.
 3505:                               '<span class="LC_nobreak"><label>'.
 3506:                               '<input type="checkbox" name="searchby" '.
 3507:                               'value="'.$title.'"'.$check.'/>'.
 3508:                               $searchtitles->{$title}.'</label></span></td>';
 3509:             }
 3510:         }
 3511:         $datatable .= '</tr></table></td></tr>';
 3512:         $$rowtotal ++;
 3513:         if ($cansrchrow) {
 3514:             $datatable .= '<tr class="LC_odd_row">';
 3515:         } else {
 3516:             $datatable .= '<tr>';
 3517:         }
 3518:         $datatable .= '<td><span class ="LC_nobreak">'.&mt('Search latitude').'</span></td>'.   
 3519:                       '<td class="LC_left_item" colspan="2">'.
 3520:                       '<span class="LC_nobreak"><label>'.
 3521:                       '<input type="checkbox" name="searchtypes" '.
 3522:                       $exacton.' value="exact" />'.&mt('Exact match').
 3523:                       '</label>&nbsp;'.
 3524:                       '<label><input type="checkbox" name="searchtypes" '.
 3525:                       $beginson.' value="begins" />'.&mt('Begins with').
 3526:                       '</label>&nbsp;'.
 3527:                       '<label><input type="checkbox" name="searchtypes" '.
 3528:                       $containson.' value="contains" />'.&mt('Contains').
 3529:                       '</label></span></td></tr>';
 3530:         $$rowtotal ++;
 3531:     } else {
 3532:         my $domsrchon = ' checked="checked" ';
 3533:         my $domsrchoff = ' ';
 3534:         my $domlocalon = ' ';
 3535:         my $domlocaloff = ' checked="checked" ';
 3536:         if (ref($settings) eq 'HASH') {
 3537:             if ($settings->{'lclocalonly'} eq '1') {
 3538:                 $domlocalon = $domlocaloff;
 3539:                 $domlocaloff = ' ';
 3540:             }
 3541:             if ($settings->{'lcavailable'} eq '0') {
 3542:                 $domsrchoff = $domsrchon;
 3543:                 $domsrchon = ' ';
 3544:             }
 3545:         }
 3546:         $datatable='<tr class="LC_odd_row">'.
 3547:                       '<td colspan="2"><span class ="LC_nobreak">'.&mt('LON-CAPA directory search available?').'</span></td>'.
 3548:                       '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3549:                       '<input type="radio" name="dirsrch_domavailable"'.
 3550:                       $domsrchon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3551:                       '<label><input type="radio" name="dirsrch_domavailable"'.
 3552:                       $domsrchoff.' value="0" />'.&mt('No').'</label></span></td>'.
 3553:                       '</tr><tr>'.
 3554:                       '<td colspan="2"><span class ="LC_nobreak">'.&mt('Other domains can search LON-CAPA domain?').'</span></td>'.
 3555:                       '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3556:                       '<input type="radio" name="dirsrch_domlocalonly"'.
 3557:                       $domlocaloff.' value="0" />'.&mt('Yes').'</label>&nbsp;'.
 3558:                       '<label><input type="radio" name="dirsrch_domlocalonly"'.
 3559:                       $domlocalon.' value="1" />'.&mt('No').'</label></span></td>'.
 3560:                       '</tr>';
 3561:         $$rowtotal += 2;
 3562:     }
 3563:     return $datatable;
 3564: }
 3565: 
 3566: sub print_contacts {
 3567:     my ($position,$dom,$settings,$rowtotal) = @_;
 3568:     my $datatable;
 3569:     my @contacts = ('adminemail','supportemail');
 3570:     my (%checked,%to,%otheremails,%bccemails,%includestr,%includeloc,%currfield,
 3571:         $maxsize,$fields,$fieldtitles,$fieldoptions,$possoptions,@mailings,%lonstatus);
 3572:     if ($position eq 'top') {
 3573:         if (ref($settings) eq 'HASH') {
 3574:             foreach my $item (@contacts) {
 3575:                 if (exists($settings->{$item})) {
 3576:                     $to{$item} = $settings->{$item};
 3577:                 }
 3578:             }
 3579:         }
 3580:     } elsif ($position eq 'middle') {
 3581:         @mailings = ('errormail','packagesmail','lonstatusmail','requestsmail',
 3582:                      'updatesmail','idconflictsmail','hostipmail');
 3583:         foreach my $type (@mailings) {
 3584:             $otheremails{$type} = '';
 3585:         }
 3586:     } elsif ($position eq 'lower') {
 3587:         if (ref($settings) eq 'HASH') {
 3588:             if (ref($settings->{'lonstatus'}) eq 'HASH') {
 3589:                 %lonstatus = %{$settings->{'lonstatus'}};
 3590:             }
 3591:         }
 3592:     } else {
 3593:         @mailings = ('helpdeskmail','otherdomsmail');
 3594:         foreach my $type (@mailings) {
 3595:             $otheremails{$type} = '';
 3596:         }
 3597:         $bccemails{'helpdeskmail'} = '';
 3598:         $bccemails{'otherdomsmail'} = '';
 3599:         $includestr{'helpdeskmail'} = '';
 3600:         $includestr{'otherdomsmail'} = '';
 3601:         ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
 3602:     }
 3603:     if (ref($settings) eq 'HASH') {
 3604:         unless (($position eq 'top') || ($position eq 'lower')) {
 3605:             foreach my $type (@mailings) {
 3606:                 if (exists($settings->{$type})) {
 3607:                     if (ref($settings->{$type}) eq 'HASH') {
 3608:                         foreach my $item (@contacts) {
 3609:                             if ($settings->{$type}{$item}) {
 3610:                                 $checked{$type}{$item} = ' checked="checked" ';
 3611:                             }
 3612:                         }
 3613:                         $otheremails{$type} = $settings->{$type}{'others'};
 3614:                         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 3615:                             $bccemails{$type} = $settings->{$type}{'bcc'};
 3616:                             if ($settings->{$type}{'include'} ne '') {
 3617:                                 ($includeloc{$type},$includestr{$type}) = split(/:/,$settings->{$type}{'include'},2);
 3618:                                 $includestr{$type} = &unescape($includestr{$type});
 3619:                             }
 3620:                         }
 3621:                     }
 3622:                 } elsif ($type eq 'lonstatusmail') {
 3623:                     $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" ';
 3624:                 }
 3625:             }
 3626:         }
 3627:         if ($position eq 'bottom') {
 3628:             foreach my $type (@mailings) {
 3629:                 $bccemails{$type} = $settings->{$type}{'bcc'};
 3630:                 if ($settings->{$type}{'include'} ne '') {
 3631:                     ($includeloc{$type},$includestr{$type}) = split(/:/,$settings->{$type}{'include'},2);
 3632:                     $includestr{$type} = &unescape($includestr{$type});
 3633:                 }
 3634:             }
 3635:             if (ref($settings->{'helpform'}) eq 'HASH') {
 3636:                 if (ref($fields) eq 'ARRAY') {
 3637:                     foreach my $field (@{$fields}) {
 3638:                         $currfield{$field} = $settings->{'helpform'}{$field};
 3639:                     }
 3640:                 }
 3641:                 if (exists($settings->{'helpform'}{'maxsize'})) {
 3642:                     $maxsize = $settings->{'helpform'}{'maxsize'};
 3643:                 } else {
 3644:                     $maxsize = '1.0';
 3645:                 }
 3646:             } else {
 3647:                 if (ref($fields) eq 'ARRAY') {
 3648:                     foreach my $field (@{$fields}) {
 3649:                         $currfield{$field} = 'yes';
 3650:                     }
 3651:                 }
 3652:                 $maxsize = '1.0';
 3653:             }
 3654:         }
 3655:     } else {
 3656:         if ($position eq 'top') {
 3657:             $to{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
 3658:             $to{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
 3659:             $checked{'errormail'}{'adminemail'} = ' checked="checked" ';
 3660:             $checked{'packagesmail'}{'adminemail'} = ' checked="checked" ';
 3661:             $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" ';
 3662:             $checked{'requestsmail'}{'adminemail'} = ' checked="checked" ';
 3663:             $checked{'updatesmail'}{'adminemail'} = ' checked="checked" ';
 3664:             $checked{'idconflictsmail'}{'adminemail'} = ' checked="checked" ';
 3665:             $checked{'hostipmail'}{'adminemail'} = ' checked="checked" ';
 3666:         } elsif ($position eq 'bottom') {
 3667:             $checked{'helpdeskmail'}{'supportemail'} = ' checked="checked" ';
 3668:             $checked{'otherdomsmail'}{'supportemail'} = ' checked="checked" ';
 3669:             if (ref($fields) eq 'ARRAY') {
 3670:                 foreach my $field (@{$fields}) {
 3671:                     $currfield{$field} = 'yes';
 3672:                 }
 3673:             }
 3674:             $maxsize = '1.0';
 3675:         }
 3676:     }
 3677:     my ($titles,$short_titles) = &contact_titles();
 3678:     my $rownum = 0;
 3679:     my $css_class;
 3680:     if ($position eq 'top') {
 3681:         foreach my $item (@contacts) {
 3682:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 3683:             $datatable .= '<tr'.$css_class.'>'. 
 3684:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
 3685:                           '</span></td><td class="LC_right_item">'.
 3686:                           '<input type="text" name="'.$item.'" value="'.
 3687:                           $to{$item}.'" /></td></tr>';
 3688:             $rownum ++;
 3689:         }
 3690:     } elsif ($position eq 'bottom') {
 3691:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 3692:         $datatable .= '<tr'.$css_class.'>'.
 3693:                       '<td>'.&mt('Extra helpdesk form fields:').'<br />'.
 3694:                       &mt('(e-mail, subject, and description always shown)').
 3695:                       '</td><td class="LC_left_item">';
 3696:         if ((ref($fields) eq 'ARRAY') && (ref($fieldtitles) eq 'HASH') &&
 3697:             (ref($fieldoptions) eq 'HASH') && (ref($possoptions) eq 'HASH')) {
 3698:             $datatable .= '<table><tr><th>'.&mt('Field').'</th><th>'.&mt('Status').'</th></tr>';
 3699:             foreach my $field (@{$fields}) {
 3700:                 $datatable .= '<tr><td>'.$fieldtitles->{$field};
 3701:                 if (($field eq 'screenshot') || ($field eq 'cc')) {
 3702:                     $datatable .= ' '.&mt('(logged-in users)');
 3703:                 }
 3704:                 $datatable .='</td><td>';
 3705:                 my $clickaction;
 3706:                 if ($field eq 'screenshot') {
 3707:                     $clickaction = ' onclick="screenshotSize(this);"';
 3708:                 }
 3709:                 if (ref($possoptions->{$field}) eq 'ARRAY') {
 3710:                     foreach my $option (@{$possoptions->{$field}}) {
 3711:                         my $checked;
 3712:                         if ($currfield{$field} eq $option) {
 3713:                             $checked = ' checked="checked"';
 3714:                         }
 3715:                         $datatable .= '<span class="LC_nobreak"><label>'.
 3716:                                       '<input type="radio" name="helpform_'.$field.'" '.
 3717:                                       'value="'.$option.'"'.$checked.$clickaction.' />'.$fieldoptions->{$option}.
 3718:                                       '</label></span>'.('&nbsp;'x2);
 3719:                     }
 3720:                 }
 3721:                 if ($field eq 'screenshot') {
 3722:                     my $display;
 3723:                     if ($currfield{$field} eq 'no') {
 3724:                         $display = ' style="display:none"';
 3725:                     }
 3726:                     $datatable .= '</td></tr><tr id="help_screenshotsize"'.$display.'>'.
 3727:                                   '<td>'.&mt('Maximum size for upload (MB)').'</td><td>'.
 3728:                                   '<input type="text" size="5" name="helpform_maxsize" value="'.$maxsize.'" />';
 3729:                 }
 3730:                 $datatable .= '</td></tr>';
 3731:             }
 3732:             $datatable .= '</table>';
 3733:         }
 3734:         $datatable .= '</td></tr>'."\n";
 3735:         $rownum ++;
 3736:     }
 3737:     unless (($position eq 'top') || ($position eq 'lower')) {
 3738:         foreach my $type (@mailings) {
 3739:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 3740:             $datatable .= '<tr'.$css_class.'>'.
 3741:                           '<td><span class="LC_nobreak">'.
 3742:                           $titles->{$type}.': </span></td>'.
 3743:                           '<td class="LC_left_item">';
 3744:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 3745:                 $datatable .= '<fieldset><legend>'.&mt('E-mail recipient(s)').'</legend>';
 3746:             }
 3747:             $datatable .= '<span class="LC_nobreak">';
 3748:             foreach my $item (@contacts) {
 3749:                 $datatable .= '<label>'.
 3750:                               '<input type="checkbox" name="'.$type.'"'.
 3751:                               $checked{$type}{$item}.
 3752:                               ' value="'.$item.'" />'.$short_titles->{$item}.
 3753:                               '</label>&nbsp;';
 3754:             }
 3755:             $datatable .= '</span><br />'.&mt('Others').':&nbsp;&nbsp;'.
 3756:                           '<input type="text" name="'.$type.'_others" '.
 3757:                           'value="'.$otheremails{$type}.'"  />';
 3758:             my %locchecked;
 3759:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 3760:                 foreach my $loc ('s','b') {
 3761:                     if ($includeloc{$type} eq $loc) {
 3762:                         $locchecked{$loc} = ' checked="checked"';
 3763:                         last;
 3764:                     }
 3765:                 }
 3766:                 $datatable .= '<br />'.&mt('Bcc:').('&nbsp;'x6).
 3767:                               '<input type="text" name="'.$type.'_bcc" '.
 3768:                               'value="'.$bccemails{$type}.'"  /></fieldset>'.
 3769:                               '<fieldset><legend>'.&mt('Optional added text').'</legend>'.
 3770:                               &mt('Text automatically added to e-mail:').' '.
 3771:                               '<input type="text" name="'.$type.'_includestr" value="'.$includestr{$type}.'" /><br />'.
 3772:                               '<span class="LC_nobreak">'.&mt('Location:').'&nbsp;'.
 3773:                               '<label><input type="radio" name="'.$type.'_includeloc" value="s"'.$locchecked{'s'}.' />'.&mt('in subject').'</label>'.
 3774:                               ('&nbsp;'x2).
 3775:                               '<label><input type="radio" name="'.$type.'_includeloc" value="b"'.$locchecked{'b'}.' />'.&mt('in body').'</label>'.
 3776:                               '</span></fieldset>';
 3777:             }
 3778:             $datatable .= '</td></tr>'."\n";
 3779:             $rownum ++;
 3780:         }
 3781:     }
 3782:     if ($position eq 'middle') {
 3783:         my %choices;
 3784:         my $corelink = &core_link_msu();
 3785:         $choices{'reporterrors'} = &mt('E-mail error reports to [_1]',$corelink);
 3786:         $choices{'reportupdates'} = &mt('E-mail record of completed LON-CAPA updates to [_1]',
 3787:                                         $corelink);
 3788:         $choices{'reportstatus'} = &mt('E-mail status if errors above threshold to [_1]',$corelink);
 3789:         my @toggles = ('reporterrors','reportupdates','reportstatus');
 3790:         my %defaultchecked = ('reporterrors'  => 'on',
 3791:                               'reportupdates' => 'on',
 3792:                               'reportstatus'  => 'on');
 3793:         (my $reports,$rownum) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 3794:                                                    \%choices,$rownum);
 3795:         $datatable .= $reports;
 3796:     } elsif ($position eq 'lower') {
 3797:         my (%current,%excluded,%weights);
 3798:         my ($defaults,$names) = &Apache::loncommon::lon_status_items();
 3799:         if ($lonstatus{'threshold'} =~ /^\d+$/) {
 3800:             $current{'errorthreshold'} = $lonstatus{'threshold'};
 3801:         } else {
 3802:             $current{'errorthreshold'} = $defaults->{'threshold'};
 3803:         }
 3804:         if ($lonstatus{'sysmail'} =~ /^\d+$/) {
 3805:             $current{'errorsysmail'} = $lonstatus{'sysmail'};
 3806:         } else {
 3807:             $current{'errorsysmail'} = $defaults->{'sysmail'};
 3808:         }
 3809:         if (ref($lonstatus{'weights'}) eq 'HASH') {
 3810:             foreach my $type ('E','W','N','U') {
 3811:                 if ($lonstatus{'weights'}{$type} =~ /^\d+$/) {
 3812:                     $weights{$type} = $lonstatus{'weights'}{$type};
 3813:                 } else {
 3814:                     $weights{$type} = $defaults->{$type};
 3815:                 }
 3816:             }
 3817:         } else {
 3818:             foreach my $type ('E','W','N','U') {
 3819:                 $weights{$type} = $defaults->{$type};
 3820:             }
 3821:         }
 3822:         if (ref($lonstatus{'excluded'}) eq 'ARRAY') {
 3823:             if (@{$lonstatus{'excluded'}} > 0) {
 3824:                 map {$excluded{$_} = 1; } @{$lonstatus{'excluded'}};
 3825:             }
 3826:         }
 3827:         foreach my $item ('errorthreshold','errorsysmail') {
 3828:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 3829:             $datatable .= '<tr'.$css_class.'>'.
 3830:                           '<td class="LC_left_item"><span class="LC_nobreak">'.
 3831:                           $titles->{$item}.
 3832:                           '</span></td><td class="LC_left_item">'.
 3833:                           '<input type="text" name="'.$item.'" value="'.
 3834:                           $current{$item}.'" size="5" /></td></tr>';
 3835:             $rownum ++;
 3836:         }
 3837:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 3838:         $datatable .= '<tr'.$css_class.'>'.
 3839:                       '<td class="LC_left_item">'.
 3840:                       '<span class="LC_nobreak">'.$titles->{'errorweights'}.
 3841:                       '</span></td><td class="LC_left_item"><table><tr>';
 3842:         foreach my $type ('E','W','N','U') {
 3843:             $datatable .= '<td>'.$names->{$type}.'<br />'.
 3844:                           '<input type="text" name="errorweights_'.$type.'" value="'.
 3845:                           $weights{$type}.'" size="5" /></td>';
 3846:         }
 3847:         $datatable .= '</tr></table></tr>';
 3848:         $rownum ++;
 3849:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 3850:         $datatable .= '<tr'.$css_class.'><td class="LC_left_item">'.
 3851:                       $titles->{'errorexcluded'}.'</td>'.
 3852:                       '<td class="LC_left_item"><table>';
 3853:         my $numinrow = 4;
 3854:         my @ids = sort(values(%Apache::lonnet::serverhomeIDs));
 3855:         for (my $i=0; $i<@ids; $i++) {
 3856:             my $rem = $i%($numinrow);
 3857:             if ($rem == 0) {
 3858:                 if ($i > 0) {
 3859:                     $datatable .= '</tr>';
 3860:                 }
 3861:                 $datatable .= '<tr>';
 3862:             }
 3863:             my $check;
 3864:             if ($excluded{$ids[$i]}) {
 3865:                 $check = ' checked="checked" ';
 3866:             }
 3867:             $datatable .= '<td class="LC_left_item">'.
 3868:                           '<span class="LC_nobreak"><label>'.
 3869:                           '<input type="checkbox" name="errorexcluded" '.
 3870:                           'value="'.$ids[$i].'"'.$check.' />'.
 3871:                           $ids[$i].'</label></span></td>';
 3872:         }
 3873:         my $colsleft = $numinrow - @ids%($numinrow);
 3874:         if ($colsleft > 1 ) {
 3875:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 3876:                           '&nbsp;</td>';
 3877:         } elsif ($colsleft == 1) {
 3878:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 3879:         }
 3880:         $datatable .= '</tr></table></td></tr>';
 3881:         $rownum ++;
 3882:     } elsif ($position eq 'bottom') {
 3883:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3884:         my (@posstypes,%usertypeshash);
 3885:         if (ref($types) eq 'ARRAY') {
 3886:             @posstypes = @{$types};
 3887:         }
 3888:         if (@posstypes) {
 3889:             if (ref($usertypes) eq 'HASH') {
 3890:                 %usertypeshash = %{$usertypes};
 3891:             }
 3892:             my @overridden;
 3893:             my $numinrow = 4;
 3894:             if (ref($settings) eq 'HASH') {
 3895:                 if (ref($settings->{'overrides'}) eq 'HASH') {
 3896:                     foreach my $key (sort(keys(%{$settings->{'overrides'}}))) {
 3897:                         if (ref($settings->{'overrides'}{$key}) eq 'HASH') {
 3898:                             push(@overridden,$key);
 3899:                             foreach my $item (@contacts) {
 3900:                                 if ($settings->{'overrides'}{$key}{$item}) {
 3901:                                     $checked{'override_'.$key}{$item} = ' checked="checked" ';
 3902:                                 }
 3903:                             }
 3904:                             $otheremails{'override_'.$key} = $settings->{'overrides'}{$key}{'others'};
 3905:                             $bccemails{'override_'.$key} = $settings->{'overrides'}{$key}{'bcc'};
 3906:                             $includeloc{'override_'.$key} = '';
 3907:                             $includestr{'override_'.$key} = '';
 3908:                             if ($settings->{'overrides'}{$key}{'include'} ne '') {
 3909:                                 ($includeloc{'override_'.$key},$includestr{'override_'.$key}) =
 3910:                                     split(/:/,$settings->{'overrides'}{$key}{'include'},2);
 3911:                                 $includestr{'override_'.$key} = &unescape($includestr{'override_'.$key});
 3912:                             }
 3913:                         }
 3914:                     }
 3915:                 }
 3916:             }
 3917:             my $customclass = 'LC_helpdesk_override';
 3918:             my $optionsprefix = 'LC_options_helpdesk_';
 3919: 
 3920:             my $onclicktypes = "toggleHelpdeskRow(this.form,'overrides','$customclass','$optionsprefix');";
 3921: 
 3922:             $datatable .= &insttypes_row($settings,$types,$usertypes,$dom,
 3923:                                          $numinrow,$othertitle,'overrides',
 3924:                                          \$rownum,$onclicktypes,$customclass);
 3925:             $rownum ++;
 3926:             $usertypeshash{'default'} = $othertitle;
 3927:             foreach my $status (@posstypes) {
 3928:                 my $css_class;
 3929:                 if ($rownum%2) {
 3930:                     $css_class = 'LC_odd_row ';
 3931:                 }
 3932:                 $css_class .= $customclass;
 3933:                 my $rowid = $optionsprefix.$status;
 3934:                 my $hidden = 1;
 3935:                 my $currstyle = 'display:none';
 3936:                 if (grep(/^\Q$status\E$/,@overridden)) {
 3937:                     $currstyle = 'display:table-row';
 3938:                     $hidden = 0;
 3939:                 }
 3940:                 my $key = 'override_'.$status;
 3941:                 $datatable .= &overridden_helpdesk($checked{$key},$otheremails{$key},$bccemails{$key},
 3942:                                                   $includeloc{$key},$includestr{$key},$status,$rowid,
 3943:                                                   $usertypeshash{$status},$css_class,$currstyle,
 3944:                                                   \@contacts,$short_titles);
 3945:                 unless ($hidden) {
 3946:                     $rownum ++;
 3947:                 }
 3948:             }
 3949:         }
 3950:     }
 3951:     $$rowtotal += $rownum;
 3952:     return $datatable;
 3953: }
 3954: 
 3955: sub core_link_msu {
 3956:     return &Apache::loncommon::modal_link('http://loncapa.org/core.html',
 3957:                                           &mt('LON-CAPA core group - MSU'),600,500);
 3958: }
 3959: 
 3960: sub overridden_helpdesk {
 3961:     my ($checked,$otheremails,$bccemails,$includeloc,$includestr,$type,$rowid,
 3962:         $typetitle,$css_class,$rowstyle,$contacts,$short_titles) = @_;
 3963:     my $class = 'LC_left_item';
 3964:     if ($css_class) {
 3965:         $css_class = ' class="'.$css_class.'"';
 3966:     }
 3967:     if ($rowid) {
 3968:         $rowid = ' id="'.$rowid.'"';
 3969:     }
 3970:     if ($rowstyle) {
 3971:         $rowstyle = ' style="'.$rowstyle.'"';
 3972:     }
 3973:     my ($output,$description);
 3974:     $description = &mt('Helpdesk requests from: [_1] in this domain (overrides default)',"<b>$typetitle</b>");
 3975:     $output = '<tr'.$css_class.$rowid.$rowstyle.'>'.
 3976:               "<td>$description</td>\n".
 3977:               '<td class="'.$class.'" colspan="2">'.
 3978:               '<fieldset><legend>'.&mt('E-mail recipient(s)').'</legend>'.
 3979:               '<span class="LC_nobreak">';
 3980:     if (ref($contacts) eq 'ARRAY') {
 3981:         foreach my $item (@{$contacts}) {
 3982:             my $check;
 3983:             if (ref($checked) eq 'HASH') {
 3984:                $check = $checked->{$item};
 3985:             }
 3986:             my $title;
 3987:             if (ref($short_titles) eq 'HASH') {
 3988:                 $title = $short_titles->{$item};
 3989:             }
 3990:             $output .= '<label>'.
 3991:                        '<input type="checkbox" name="override_'.$type.'"'.$check.
 3992:                        ' value="'.$item.'" />'.$title.'</label>&nbsp;';
 3993:         }
 3994:     }
 3995:     $output .= '</span><br />'.&mt('Others').':&nbsp;&nbsp;'.
 3996:                '<input type="text" name="override_'.$type.'_others" '.
 3997:                'value="'.$otheremails.'"  />';
 3998:     my %locchecked;
 3999:     foreach my $loc ('s','b') {
 4000:         if ($includeloc eq $loc) {
 4001:             $locchecked{$loc} = ' checked="checked"';
 4002:             last;
 4003:         }
 4004:     }
 4005:     $output .= '<br />'.&mt('Bcc:').('&nbsp;'x6).
 4006:                '<input type="text" name="override_'.$type.'_bcc" '.
 4007:                'value="'.$bccemails.'"  /></fieldset>'.
 4008:                '<fieldset><legend>'.&mt('Optional added text').'</legend>'.
 4009:                &mt('Text automatically added to e-mail:').' '.
 4010:                '<input type="text" name="override_'.$type.'_includestr" value="'.$includestr.'" /><br />'.
 4011:                '<span class="LC_nobreak">'.&mt('Location:').'&nbsp;'.
 4012:                '<label><input type="radio" name="override_'.$type.'_includeloc" value="s"'.$locchecked{'s'}.' />'.&mt('in subject').'</label>'.
 4013:                ('&nbsp;'x2).
 4014:                '<label><input type="radio" name="override_'.$type.'_includeloc" value="b"'.$locchecked{'b'}.' />'.&mt('in body').'</label>'.
 4015:                '</span></fieldset>'.
 4016:                '</td></tr>'."\n";
 4017:     return $output;
 4018: }
 4019: 
 4020: sub contacts_javascript {
 4021:     return <<"ENDSCRIPT";
 4022: 
 4023: <script type="text/javascript">
 4024: // <![CDATA[
 4025: 
 4026: function screenshotSize(field) {
 4027:     if (document.getElementById('help_screenshotsize')) {
 4028:         if (field.value == 'no') {
 4029:             document.getElementById('help_screenshotsize').style.display="none";
 4030:         } else {
 4031:             document.getElementById('help_screenshotsize').style.display="";
 4032:         }
 4033:     }
 4034:     return;
 4035: }
 4036: 
 4037: function toggleHelpdeskRow(form,checkbox,target,prefix,docount) {
 4038:     if (form.elements[checkbox].length != undefined) {
 4039:         var count = 0;
 4040:         if (docount) {
 4041:             for (var i=0; i<form.elements[checkbox].length; i++) {
 4042:                 if (form.elements[checkbox][i].checked) {
 4043:                     count ++;
 4044:                 }
 4045:             }
 4046:         }
 4047:         for (var i=0; i<form.elements[checkbox].length; i++) {
 4048:             var type = form.elements[checkbox][i].value;
 4049:             if (document.getElementById(prefix+type)) {
 4050:                 if (form.elements[checkbox][i].checked) {
 4051:                     document.getElementById(prefix+type).style.display = 'table-row';
 4052:                     if (count % 2 == 1) {
 4053:                         document.getElementById(prefix+type).className = target+' LC_odd_row';
 4054:                     } else {
 4055:                         document.getElementById(prefix+type).className = target;
 4056:                     }
 4057:                     count ++;
 4058:                 } else {
 4059:                     document.getElementById(prefix+type).style.display = 'none';
 4060:                 }
 4061:             }
 4062:         }
 4063:     }
 4064:     return;
 4065: }
 4066: 
 4067: // ]]>
 4068: </script>
 4069: 
 4070: ENDSCRIPT
 4071: }
 4072: 
 4073: sub print_helpsettings {
 4074:     my ($position,$dom,$settings,$rowtotal) = @_;
 4075:     my $confname = $dom.'-domainconfig';
 4076:     my $formname = 'display';
 4077:     my ($datatable,$itemcount);
 4078:     if ($position eq 'top') {
 4079:         $itemcount = 1;
 4080:         my (%choices,%defaultchecked,@toggles);
 4081:         $choices{'submitbugs'} = &mt('Display link to: [_1]?',
 4082:                                      &Apache::loncommon::modal_link('http://bugs.loncapa.org',
 4083:                                      &mt('LON-CAPA bug tracker'),600,500));
 4084:         %defaultchecked = ('submitbugs' => 'on');
 4085:         @toggles = ('submitbugs');
 4086:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 4087:                                                      \%choices,$itemcount);
 4088:         $$rowtotal ++;
 4089:     } else {
 4090:         my $css_class;
 4091:         my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
 4092:         my (%customroles,%ordered,%current);
 4093:         if (ref($settings) eq 'HASH') {
 4094:             if (ref($settings->{'adhoc'}) eq 'HASH') {
 4095:                 %current = %{$settings->{'adhoc'}};
 4096:             }
 4097:         }
 4098:         my $count = 0;
 4099:         foreach my $key (sort(keys(%existing))) {
 4100:             if ($key=~/^rolesdef\_(\w+)$/) {
 4101:                 my $rolename = $1;
 4102:                 my (%privs,$order);
 4103:                 ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 4104:                 $customroles{$rolename} = \%privs;
 4105:                 if (ref($current{$rolename}) eq 'HASH') {
 4106:                     $order = $current{$rolename}{'order'};
 4107:                 }
 4108:                 if ($order eq '') {
 4109:                     $order = $count;
 4110:                 }
 4111:                 $ordered{$order} = $rolename;
 4112:                 $count++;
 4113:             }
 4114:         }
 4115:         my $maxnum = scalar(keys(%ordered));
 4116:         my @roles_by_num = ();
 4117:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 4118:             push(@roles_by_num,$item);
 4119:         }
 4120:         my $context = 'domprefs';
 4121:         my $crstype = 'Course';
 4122:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4123:         my @accesstypes = ('all','dh','da','none');
 4124:         my ($numstatustypes,@jsarray);
 4125:         if (ref($types) eq 'ARRAY') {
 4126:             if (@{$types} > 0) {
 4127:                 $numstatustypes = scalar(@{$types});
 4128:                 push(@accesstypes,'status');
 4129:                 @jsarray = ('bystatus');
 4130:             }
 4131:         }
 4132:         my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh','da']);
 4133:         if (keys(%domhelpdesk)) {
 4134:             push(@accesstypes,('inc','exc'));
 4135:             push(@jsarray,('notinc','notexc'));
 4136:         }
 4137:         my $hiddenstr = join("','",@jsarray);
 4138:         $datatable .= &helpsettings_javascript(\@roles_by_num,$maxnum,$hiddenstr,$formname);
 4139:         my $context = 'domprefs';
 4140:         my $crstype = 'Course';
 4141:         my $prefix = 'helproles_';
 4142:         my $add_class = 'LC_hidden';
 4143:         foreach my $num (@roles_by_num) {
 4144:             my $role = $ordered{$num};
 4145:             my ($desc,$access,@statuses);
 4146:             if (ref($current{$role}) eq 'HASH') {
 4147:                 $desc = $current{$role}{'desc'};
 4148:                 $access = $current{$role}{'access'};
 4149:                 if (ref($current{$role}{'insttypes'}) eq 'ARRAY') {
 4150:                     @statuses = @{$current{$role}{'insttypes'}};
 4151:                 }
 4152:             }
 4153:             if ($desc eq '') {
 4154:                 $desc = $role;
 4155:             }
 4156:             my $identifier = 'custhelp'.$num;
 4157:             my %full=();
 4158:             my %levels= (
 4159:                          course => {},
 4160:                          domain => {},
 4161:                          system => {},
 4162:                         );
 4163:             my %levelscurrent=(
 4164:                                course => {},
 4165:                                domain => {},
 4166:                                system => {},
 4167:                               );
 4168:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 4169:             my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4170:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4171:             my $chgstr = ' onchange="javascript:reorderHelpRoles(this.form,'."'helproles_".$num."_pos'".');"';
 4172:             $datatable .= '<tr '.$css_class.'><td valign="top"><b>'.$role.'</b><br />'.
 4173:                           '<select name="helproles_'.$num.'_pos"'.$chgstr.'>';
 4174:             for (my $k=0; $k<=$maxnum; $k++) {
 4175:                 my $vpos = $k+1;
 4176:                 my $selstr;
 4177:                 if ($k == $num) {
 4178:                     $selstr = ' selected="selected" ';
 4179:                 }
 4180:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 4181:             }
 4182:             $datatable .= '</select>'.('&nbsp;'x2).
 4183:                           '<input type="hidden" name="helproles_'.$num.'" value="'.$role.'" />'.
 4184:                           '</td>'.
 4185:                           '<td><fieldset><legend>'.&mt('Role name').'</legend>'.
 4186:                           &mt('Name shown to users:').
 4187:                           '<input type="text" name="helproles_'.$num.'_desc" value="'.$desc.'" />'.
 4188:                           '</fieldset>'.
 4189:                           &helpdeskroles_access($dom,$prefix,$num,$add_class,$current{$role},\@accesstypes,
 4190:                                                 $othertitle,$usertypes,$types,\%domhelpdesk).
 4191:                           '<fieldset>'.
 4192:                           '<legend>'.&mt('Role privileges').&adhocbutton($prefix,$num,'privs','show').'</legend>'.
 4193:                           &Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 4194:                                                                    \%levelscurrent,$identifier,
 4195:                                                                    'LC_hidden',$prefix.$num.'_privs').
 4196:                           '</fieldset></td>';
 4197:             $itemcount ++;
 4198:         }
 4199:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4200:         my $newcust = 'custhelp'.$count;
 4201:         my (%privs,%levelscurrent);
 4202:         my %full=();
 4203:         my %levels= (
 4204:                      course => {},
 4205:                      domain => {},
 4206:                      system => {},
 4207:                     );
 4208:         &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 4209:         my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4210:         my $chgstr = ' onchange="javascript:reorderHelpRoles(this.form,'."'helproles_".$count."_pos'".');"';
 4211:         $datatable .= '<tr '.$css_class.'><td valign="top"><span class="LC_nobreak"><label>'.
 4212:                       '<input type="hidden" name="helproles_maxnum" value="'.$maxnum.'" />'."\n".
 4213:                       '<select name="helproles_'.$count.'_pos"'.$chgstr.'>';
 4214:         for (my $k=0; $k<$maxnum+1; $k++) {
 4215:             my $vpos = $k+1;
 4216:             my $selstr;
 4217:             if ($k == $maxnum) {
 4218:                 $selstr = ' selected="selected" ';
 4219:             }
 4220:             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 4221:         }
 4222:         $datatable .= '</select>&nbsp;'."\n".
 4223:                       '<input type="checkbox" name="newcusthelp" value="'.$count.'" />'. &mt('Add').
 4224:                       '</label></span></td>'.
 4225:                       '<td><fieldset><legend>'.&mt('Role name').'</legend>'.
 4226:                       '<span class="LC_nobreak">'.
 4227:                       &mt('Internal name:').
 4228:                       '<input type="text" size="10" name="custhelpname'.$count.'" value="" />'.
 4229:                       '</span>'.('&nbsp;'x4).
 4230:                       '<span class="LC_nobreak">'.
 4231:                       &mt('Name shown to users:').
 4232:                       '<input type="text" size="20" name="helproles_'.$count.'_desc" value="" />'.
 4233:                       '</span></fieldset>'.
 4234:                        &helpdeskroles_access($dom,$prefix,$count,'',undef,\@accesstypes,$othertitle,
 4235:                                              $usertypes,$types,\%domhelpdesk).
 4236:                       '<fieldset><legend>'.&mt('Role privileges').'</legend>'.
 4237:                       &Apache::lonuserutils::custom_role_header($context,$crstype,
 4238:                                                                 \@templateroles,$newcust).
 4239:                       &Apache::lonuserutils::custom_role_table('Course',\%full,\%levels,
 4240:                                                                \%levelscurrent,$newcust).
 4241:                       '</fieldset>'.
 4242:                       &helpsettings_javascript(\@roles_by_num,$maxnum,$hiddenstr,$formname).
 4243:                       '</td></tr>';
 4244:         $count ++;
 4245:         $$rowtotal += $count;
 4246:     }
 4247:     return $datatable;
 4248: }
 4249: 
 4250: sub adhocbutton {
 4251:     my ($prefix,$num,$field,$visibility) = @_;
 4252:     my %lt = &Apache::lonlocal::texthash(
 4253:                                           show => 'Show details',
 4254:                                           hide => 'Hide details',
 4255:                                         );
 4256:     return '<span style="text-decoration:line-through; font-weight: normal;">'.('&nbsp;'x10).
 4257:            '</span>'.('&nbsp;'x2).'<input type="button" id="'.$prefix.$num.'_'.$field.'_vis"'.
 4258:            ' value="'.$lt{$visibility}.'" style="height:20px;" '.
 4259:            'onclick="toggleHelpdeskItem('."'$num','$field'".');" />'.('&nbsp;'x2);
 4260: }
 4261: 
 4262: sub helpsettings_javascript {
 4263:     my ($roles_by_num,$total,$hiddenstr,$formname) = @_;
 4264:     return unless(ref($roles_by_num) eq 'ARRAY');
 4265:     my %html_js_lt = &Apache::lonlocal::texthash(
 4266:                                           show => 'Show details',
 4267:                                           hide => 'Hide details',
 4268:                                         );
 4269:     &html_escape(\%html_js_lt);
 4270:     my $jstext = '    var helproles = Array('."'".join("','",@{$roles_by_num})."'".');'."\n";
 4271:     return <<"ENDSCRIPT";
 4272: <script type="text/javascript">
 4273: // <![CDATA[
 4274: 
 4275: function reorderHelpRoles(form,item) {
 4276:     var changedVal;
 4277: $jstext
 4278:     var newpos = 'helproles_${total}_pos';
 4279:     var maxh = 1 + $total;
 4280:     var current = new Array();
 4281:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 4282:     if (item == newpos) {
 4283:         changedVal = newitemVal;
 4284:     } else {
 4285:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 4286:         current[newitemVal] = newpos;
 4287:     }
 4288:     for (var i=0; i<helproles.length; i++) {
 4289:         var elementName = 'helproles_'+helproles[i]+'_pos';
 4290:         if (elementName != item) {
 4291:             if (form.elements[elementName]) {
 4292:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 4293:                 current[currVal] = elementName;
 4294:             }
 4295:         }
 4296:     }
 4297:     var oldVal;
 4298:     for (var j=0; j<maxh; j++) {
 4299:         if (current[j] == undefined) {
 4300:             oldVal = j;
 4301:         }
 4302:     }
 4303:     if (oldVal < changedVal) {
 4304:         for (var k=oldVal+1; k<=changedVal ; k++) {
 4305:            var elementName = current[k];
 4306:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 4307:         }
 4308:     } else {
 4309:         for (var k=changedVal; k<oldVal; k++) {
 4310:             var elementName = current[k];
 4311:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 4312:         }
 4313:     }
 4314:     return;
 4315: }
 4316: 
 4317: function helpdeskAccess(num) {
 4318:     var curraccess = null;
 4319:     if (document.$formname.elements['helproles_'+num+'_access'].length) {
 4320:         for (var i=0; i<document.$formname.elements['helproles_'+num+'_access'].length; i++) {
 4321:             if (document.$formname.elements['helproles_'+num+'_access'][i].checked) {
 4322:                 curraccess = document.$formname.elements['helproles_'+num+'_access'][i].value;
 4323:             }
 4324:         }
 4325:     }
 4326:     var shown = Array();
 4327:     var hidden = Array();
 4328:     if (curraccess == 'none') {
 4329:         hidden = Array('$hiddenstr');
 4330:     } else {
 4331:         if (curraccess == 'status') {
 4332:             shown = Array('bystatus');
 4333:             hidden = Array('notinc','notexc');
 4334:         } else {
 4335:             if (curraccess == 'exc') {
 4336:                 shown = Array('notexc');
 4337:                 hidden = Array('notinc','bystatus');
 4338:             }
 4339:             if (curraccess == 'inc') {
 4340:                 shown = Array('notinc');
 4341:                 hidden = Array('notexc','bystatus');
 4342:             }
 4343:             if ((curraccess == 'all') || (curraccess == 'dh') || (curraccess == 'da')) {
 4344:                 hidden = Array('notinc','notexc','bystatus');
 4345:             }
 4346:         }
 4347:     }
 4348:     if (hidden.length > 0) {
 4349:         for (var i=0; i<hidden.length; i++) {
 4350:             if (document.getElementById('helproles_'+num+'_'+hidden[i])) {
 4351:                 document.getElementById('helproles_'+num+'_'+hidden[i]).style.display = 'none';
 4352:             }
 4353:         }
 4354:     }
 4355:     if (shown.length > 0) {
 4356:         for (var i=0; i<shown.length; i++) {
 4357:             if (document.getElementById('helproles_'+num+'_'+shown[i])) {
 4358:                 if (shown[i] == 'privs') {
 4359:                     document.getElementById('helproles_'+num+'_'+shown[i]).style.display = 'block';
 4360:                 } else {
 4361:                     document.getElementById('helproles_'+num+'_'+shown[i]).style.display = 'inline-block';
 4362:                 }
 4363:             }
 4364:         }
 4365:     }
 4366:     return;
 4367: }
 4368: 
 4369: function toggleHelpdeskItem(num,field) {
 4370:     if (document.getElementById('helproles_'+num+'_'+field)) {
 4371:         if (document.getElementById('helproles_'+num+'_'+field).className.match(/(?:^|\\s)LC_hidden(?!\\S)/)) {
 4372:             document.getElementById('helproles_'+num+'_'+field).className =
 4373:                 document.getElementById('helproles_'+num+'_'+field).className.replace(/(?:^|\\s)LC_hidden(?!\\S)/g ,'');
 4374:             if (document.getElementById('helproles_'+num+'_'+field+'_vis')) {
 4375:                 document.getElementById('helproles_'+num+'_'+field+'_vis').value = '$html_js_lt{hide}';
 4376:             }
 4377:         } else {
 4378:             document.getElementById('helproles_'+num+'_'+field).className += ' LC_hidden';
 4379:             if (document.getElementById('helproles_'+num+'_'+field+'_vis')) {
 4380:                 document.getElementById('helproles_'+num+'_'+field+'_vis').value = '$html_js_lt{show}';
 4381:             }
 4382:         }
 4383:     }
 4384:     return;
 4385: }
 4386: 
 4387: // ]]>
 4388: </script>
 4389: 
 4390: ENDSCRIPT
 4391: }
 4392: 
 4393: sub helpdeskroles_access {
 4394:     my ($dom,$prefix,$num,$add_class,$current,$accesstypes,$othertitle,
 4395:         $usertypes,$types,$domhelpdesk) = @_;
 4396:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($domhelpdesk) eq 'HASH'));
 4397:     my %lt = &Apache::lonlocal::texthash(
 4398:                     'rou'    => 'Role usage',
 4399:                     'whi'    => 'Which helpdesk personnel may use this role?',
 4400:                     'all'    => 'All with domain helpdesk or helpdesk assistant role',
 4401:                     'dh'     => 'All with domain helpdesk role',
 4402:                     'da'     => 'All with domain helpdesk assistant role',
 4403:                     'none'   => 'None',
 4404:                     'status' => 'Determined based on institutional status',
 4405:                     'inc'    => 'Include all, but exclude specific personnel',
 4406:                     'exc'    => 'Exclude all, but include specific personnel',
 4407:                   );
 4408:     my %usecheck = (
 4409:                      all => ' checked="checked"',
 4410:                    );
 4411:     my %displaydiv = (
 4412:                       status => 'none',
 4413:                       inc    => 'none',
 4414:                       exc    => 'none',
 4415:                       priv   => 'block',
 4416:                      );
 4417:     my $output;
 4418:     if (ref($current) eq 'HASH') {
 4419:         if (($current->{'access'} ne '') && ($current->{'access'} ne 'all')) {
 4420:             if (grep(/^\Q$current->{access}\E$/,@{$accesstypes})) {
 4421:                 $usecheck{$current->{access}} = $usecheck{'all'};
 4422:                 delete($usecheck{'all'});
 4423:                 if ($current->{access} =~ /^(status|inc|exc)$/) {
 4424:                     my $access = $1;
 4425:                     $displaydiv{$access} = 'inline';
 4426:                 } elsif ($current->{access} eq 'none') {
 4427:                     $displaydiv{'priv'} = 'none';
 4428:                 }
 4429:             }
 4430:         }
 4431:     }
 4432:     $output = '<fieldset id="'.$prefix.$num.'_usage"><legend>'.$lt{'rou'}.'</legend>'.
 4433:               '<p>'.$lt{'whi'}.'</p>';
 4434:     foreach my $access (@{$accesstypes}) {
 4435:         $output .= '<p><label><input type="radio" name="'.$prefix.$num.'_access" value="'.$access.'" '.$usecheck{$access}.
 4436:                    ' onclick="helpdeskAccess('."'$num'".');" />'.
 4437:                    $lt{$access}.'</label>';
 4438:         if ($access eq 'status') {
 4439:             $output .= '<div id="'.$prefix.$num.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 4440:                        &Apache::lonuserutils::adhoc_status_types($dom,$prefix,$num,$current->{$access},
 4441:                                                                  $othertitle,$usertypes,$types).
 4442:                        '</div>';
 4443:         } elsif (($access eq 'inc') && (keys(%{$domhelpdesk}) > 0)) {
 4444:             $output .= '<div id="'.$prefix.$num.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 4445:                        &Apache::lonuserutils::adhoc_staff($access,$prefix,$num,$current->{$access},$domhelpdesk).
 4446:                        '</div>';
 4447:         } elsif (($access eq 'exc') && (keys(%{$domhelpdesk}) > 0)) {
 4448:             $output .= '<div id="'.$prefix.$num.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 4449:                        &Apache::lonuserutils::adhoc_staff($access,$prefix,$num,$current->{$access},$domhelpdesk).
 4450:                        '</div>';
 4451:         }
 4452:         $output .= '</p>';
 4453:     }
 4454:     $output .= '</fieldset>';
 4455:     return $output;
 4456: }
 4457: 
 4458: sub radiobutton_prefs {
 4459:     my ($settings,$toggles,$defaultchecked,$choices,$itemcount,$onclick,
 4460:         $additional,$align,$firstval) = @_;
 4461:     return unless ((ref($toggles) eq 'ARRAY') && (ref($defaultchecked) eq 'HASH') &&
 4462:                    (ref($choices) eq 'HASH'));
 4463: 
 4464:     my (%checkedon,%checkedoff,$datatable,$css_class);
 4465: 
 4466:     foreach my $item (@{$toggles}) {
 4467:         if ($defaultchecked->{$item} eq 'on') {
 4468:             $checkedon{$item} = ' checked="checked" ';
 4469:             $checkedoff{$item} = ' ';
 4470:         } elsif ($defaultchecked->{$item} eq 'off') {
 4471:             $checkedoff{$item} = ' checked="checked" ';
 4472:             $checkedon{$item} = ' ';
 4473:         }
 4474:     }
 4475:     if (ref($settings) eq 'HASH') {
 4476:         foreach my $item (@{$toggles}) {
 4477:             if ($settings->{$item} eq '1') {
 4478:                 $checkedon{$item} =  ' checked="checked" ';
 4479:                 $checkedoff{$item} = ' ';
 4480:             } elsif ($settings->{$item} eq '0') {
 4481:                 $checkedoff{$item} =  ' checked="checked" ';
 4482:                 $checkedon{$item} = ' ';
 4483:             }
 4484:         }
 4485:     }
 4486:     if ($onclick) {
 4487:         $onclick = ' onclick="'.$onclick.'"';
 4488:     }
 4489:     foreach my $item (@{$toggles}) {
 4490:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4491:         $datatable .=
 4492:             '<tr'.$css_class.'><td valign="top">'.
 4493:             '<span class="LC_nobreak">'.$choices->{$item}.
 4494:             '</span></td>';
 4495:         if ($align eq 'left') {
 4496:             $datatable .= '<td class="LC_left_item">';
 4497:         } else {
 4498:             $datatable .= '<td class="LC_right_item">';
 4499:         }
 4500:         $datatable .= '<span class="LC_nobreak">';
 4501:         if ($firstval eq 'no') {
 4502:             $datatable .=
 4503:                 '<label><input type="radio" name="'.
 4504:                 $item.'" '.$checkedoff{$item}.' value="0"'.$onclick.' />'.&mt('No').
 4505:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'" '.
 4506:                 $checkedon{$item}.' value="1"'.$onclick.' />'.&mt('Yes').'</label>';
 4507:         } else {
 4508:             $datatable .=
 4509:             '<label><input type="radio" name="'.
 4510:             $item.'" '.$checkedon{$item}.' value="1"'.$onclick.' />'.&mt('Yes').
 4511:             '</label>&nbsp;<label><input type="radio" name="'.$item.'" '.
 4512:             $checkedoff{$item}.' value="0"'.$onclick.' />'.&mt('No').'</label>';
 4513:         }
 4514:         $datatable .= '</span>'.$additional.'</td></tr>';
 4515:         $itemcount ++;
 4516:     }
 4517:     return ($datatable,$itemcount);
 4518: }
 4519: 
 4520: sub print_coursedefaults {
 4521:     my ($position,$dom,$settings,$rowtotal) = @_;
 4522:     my ($css_class,$datatable,%checkedon,%checkedoff,%defaultchecked,@toggles);
 4523:     my $itemcount = 1;
 4524:     my %choices =  &Apache::lonlocal::texthash (
 4525:         uploadquota          => 'Default quota for files uploaded directly to course/community using Course Editor (MB)',
 4526:         anonsurvey_threshold => 'Responder count needed before showing submissions for anonymous surveys',
 4527:         coursecredits        => 'Credits can be specified for courses',
 4528:         uselcmath            => 'Math preview uses LON-CAPA previewer (javascript) in place of DragMath (Java)',
 4529:         usejsme              => 'Molecule editor uses JSME (HTML5) in place of JME (Java)',
 4530:         inline_chem          => 'Use inline previewer for chemical reaction response in place of pop-up',
 4531:         texengine            => 'Default method to display mathematics',
 4532:         postsubmit           => 'Disable submit button/keypress following student submission',
 4533:         canclone             => "People who may clone a course (besides course's owner and coordinators)",
 4534:         mysqltables          => 'Lifetime (s) of "Temporary" MySQL tables (student performance data) on homeserver',
 4535:     );
 4536:     my %staticdefaults = (
 4537:                            anonsurvey_threshold => 10,
 4538:                            uploadquota          => 500,
 4539:                            postsubmit           => 60,
 4540:                            mysqltables          => 172800,
 4541:                          );
 4542:     if ($position eq 'top') {
 4543:         %defaultchecked = (
 4544:                             'uselcmath'       => 'on',
 4545:                             'usejsme'         => 'on',
 4546:                             'inline_chem'     => 'on',
 4547:                             'canclone'        => 'none',
 4548:                           );
 4549:         @toggles = ('uselcmath','usejsme','inline_chem');
 4550:         my $deftex = $Apache::lonnet::deftex;
 4551:         if (ref($settings) eq 'HASH') {
 4552:             if ($settings->{'texengine'}) {
 4553:                 if ($settings->{'texengine'} =~ /^(MathJax|mimetex|tth)$/) {
 4554:                     $deftex = $settings->{'texengine'};
 4555:                 }
 4556:             }
 4557:         }
 4558:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4559:         my $mathdisp = '<tr'.$css_class.'><td style="vertical-align: top">'.
 4560:                        '<span class="LC_nobreak">'.$choices{'texengine'}.
 4561:                        '</span></td><td class="LC_right_item">'.
 4562:                        '<select name="texengine">'."\n";
 4563:         my %texoptions = (
 4564:                             MathJax  => 'MathJax',
 4565:                             mimetex  => &mt('Convert to Images'),
 4566:                             tth      => &mt('TeX to HTML'),
 4567:                          );
 4568:         foreach my $renderer ('MathJax','mimetex','tth') {
 4569:             my $selected = '';
 4570:             if ($renderer eq $deftex) {
 4571:                 $selected = ' selected="selected"';
 4572:             }
 4573:             $mathdisp .= '<option value="'.$renderer.'"'.$selected.'>'.$texoptions{$renderer}.'</option>'."\n";
 4574:         }
 4575:         $mathdisp .= '</select></td></tr>'."\n";
 4576:         $itemcount ++;
 4577:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 4578:                                                      \%choices,$itemcount);
 4579:         $datatable = $mathdisp.$datatable;
 4580:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4581:         $datatable .=
 4582:             '<tr'.$css_class.'><td valign="top">'.
 4583:             '<span class="LC_nobreak">'.$choices{'canclone'}.
 4584:             '</span></td><td class="LC_left_item">';
 4585:         my $currcanclone = 'none';
 4586:         my $onclick;
 4587:         my @cloneoptions = ('none','domain');
 4588:         my %clonetitles = &Apache::lonlocal::texthash (
 4589:                              none     => 'No additional course requesters',
 4590:                              domain   => "Any course requester in course's domain",
 4591:                              instcode => 'Course requests for official courses ...',
 4592:                           );
 4593:         my (%codedefaults,@code_order,@posscodes);
 4594:         if (&Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
 4595:                                                     \@code_order) eq 'ok') {
 4596:             if (@code_order > 0) {
 4597:                 push(@cloneoptions,'instcode');
 4598:                 $onclick = ' onclick="toggleDisplay(this.form,'."'cloneinstcode'".');"';
 4599:             }
 4600:         }
 4601:         if (ref($settings) eq 'HASH') {
 4602:             if ($settings->{'canclone'}) {
 4603:                 if (ref($settings->{'canclone'}) eq 'HASH') {
 4604:                     if (ref($settings->{'canclone'}{'instcode'}) eq 'ARRAY') {
 4605:                         if (@code_order > 0) {
 4606:                             $currcanclone = 'instcode';
 4607:                             @posscodes = @{$settings->{'canclone'}{'instcode'}};
 4608:                         }
 4609:                     }
 4610:                 } elsif ($settings->{'canclone'} eq 'domain') {
 4611:                     $currcanclone = $settings->{'canclone'};
 4612:                 }
 4613:             }
 4614:         }
 4615:         foreach my $option (@cloneoptions) {
 4616:             my ($checked,$additional);
 4617:             if ($currcanclone eq $option) {
 4618:                 $checked = ' checked="checked"';
 4619:             }
 4620:             if ($option eq 'instcode') {
 4621:                 if (@code_order) {
 4622:                     my $show = 'none';
 4623:                     if ($checked) {
 4624:                         $show = 'block';
 4625:                     }
 4626:                     $additional = '<div id="cloneinstcode" style="display:'.$show.'" />'.
 4627:                                   &mt('Institutional codes for new and cloned course have identical:').
 4628:                                   '<br />';
 4629:                     foreach my $item (@code_order) {
 4630:                         my $codechk;
 4631:                         if ($checked) {
 4632:                             if (grep(/^\Q$item\E$/,@posscodes)) {
 4633:                                 $codechk = ' checked="checked"';
 4634:                             }
 4635:                         }
 4636:                         $additional .= '<label>'.
 4637:                                        '<input type="checkbox" name="clonecode" value="'.$item.'"'.$codechk.' />'.
 4638:                                        $item.'</label>';
 4639:                     }
 4640:                     $additional .= ('&nbsp;'x2).'('.&mt('check as many as needed').')</div>';
 4641:                 }
 4642:             }
 4643:             $datatable .=
 4644:                 '<span class="LC_nobreak"><label><input type="radio" name="canclone"'.$checked.
 4645:                 ' value="'.$option.'"'.$onclick.' />'.$clonetitles{$option}.
 4646:                 '</label>&nbsp;'.$additional.'</span><br />';
 4647:         }
 4648:         $datatable .= '</td>'.
 4649:                       '</tr>';
 4650:         $itemcount ++;
 4651:     } else {
 4652:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 4653:         my ($currdefresponder,%defcredits,%curruploadquota,%deftimeout,%currmysql);
 4654:         my $currusecredits = 0;
 4655:         my $postsubmitclient = 1;
 4656:         my @types = ('official','unofficial','community','textbook');
 4657:         if (ref($settings) eq 'HASH') {
 4658:             $currdefresponder = $settings->{'anonsurvey_threshold'};
 4659:             if (ref($settings->{'uploadquota'}) eq 'HASH') {
 4660:                 foreach my $type (keys(%{$settings->{'uploadquota'}})) {
 4661:                     $curruploadquota{$type} = $settings->{'uploadquota'}{$type};
 4662:                 }
 4663:             }
 4664:             if (ref($settings->{'coursecredits'}) eq 'HASH') {
 4665:                 foreach my $type (@types) {
 4666:                     next if ($type eq 'community');
 4667:                     $defcredits{$type} = $settings->{'coursecredits'}->{$type};
 4668:                     if ($defcredits{$type} ne '') {
 4669:                         $currusecredits = 1;
 4670:                     }
 4671:                 }
 4672:             }
 4673:             if (ref($settings->{'postsubmit'}) eq 'HASH') {
 4674:                 if ($settings->{'postsubmit'}->{'client'} eq 'off') {
 4675:                     $postsubmitclient = 0;
 4676:                     foreach my $type (@types) {
 4677:                         $deftimeout{$type} = $staticdefaults{'postsubmit'};
 4678:                     }
 4679:                 } else {
 4680:                     foreach my $type (@types) {
 4681:                         if (ref($settings->{'postsubmit'}->{'timeout'}) eq 'HASH') {
 4682:                             if ($settings->{'postsubmit'}->{'timeout'}->{$type} =~ /^\d+$/) {
 4683:                                 $deftimeout{$type} = $settings->{'postsubmit'}->{'timeout'}->{$type};
 4684:                             } else {
 4685:                                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 4686:                             }
 4687:                         } else {
 4688:                             $deftimeout{$type} = $staticdefaults{'postsubmit'};
 4689:                         }
 4690:                     }
 4691:                 }
 4692:             } else {
 4693:                 foreach my $type (@types) {
 4694:                     $deftimeout{$type} = $staticdefaults{'postsubmit'};
 4695:                 }
 4696:             }
 4697:             if (ref($settings->{'mysqltables'}) eq 'HASH') {
 4698:                 foreach my $type (keys(%{$settings->{'mysqltables'}})) {
 4699:                     $currmysql{$type} = $settings->{'mysqltables'}{$type};
 4700:                 }
 4701:             } else {
 4702:                 foreach my $type (@types) {
 4703:                     $currmysql{$type} = $staticdefaults{'mysqltables'};
 4704:                 }
 4705:             }
 4706:         } else {
 4707:             foreach my $type (@types) {
 4708:                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 4709:             }
 4710:         }
 4711:         if (!$currdefresponder) {
 4712:             $currdefresponder = $staticdefaults{'anonsurvey_threshold'};
 4713:         } elsif ($currdefresponder < 1) {
 4714:             $currdefresponder = 1;
 4715:         }
 4716:         foreach my $type (@types) {
 4717:             if ($curruploadquota{$type} eq '') {
 4718:                 $curruploadquota{$type} = $staticdefaults{'uploadquota'};
 4719:             }
 4720:         }
 4721:         $datatable .=
 4722:                 '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 4723:                 $choices{'anonsurvey_threshold'}.
 4724:                 '</span></td>'.
 4725:                 '<td class="LC_right_item"><span class="LC_nobreak">'.
 4726:                 '<input type="text" name="anonsurvey_threshold"'.
 4727:                 ' value="'.$currdefresponder.'" size="5" /></span>'.
 4728:                 '</td></tr>'."\n";
 4729:         $itemcount ++;
 4730:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 4731:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 4732:                       $choices{'uploadquota'}.
 4733:                       '</span></td>'.
 4734:                       '<td align="right" class="LC_right_item">'.
 4735:                       '<table><tr>';
 4736:         foreach my $type (@types) {
 4737:             $datatable .= '<td align="center">'.&mt($type).'<br />'.
 4738:                            '<input type="text" name="uploadquota_'.$type.'"'.
 4739:                            ' value="'.$curruploadquota{$type}.'" size="5" /></td>';
 4740:         }
 4741:         $datatable .= '</tr></table></td></tr>'."\n";
 4742:         $itemcount ++;
 4743:         my $onclick = "toggleDisplay(this.form,'credits');";
 4744:         my $display = 'none';
 4745:         if ($currusecredits) {
 4746:             $display = 'block';
 4747:         }
 4748:         my $additional = '<div id="credits" style="display: '.$display.'">'.
 4749:                          '<i>'.&mt('Default credits').'</i><br /><table><tr>';
 4750:         foreach my $type (@types) {
 4751:             next if ($type eq 'community');
 4752:             $additional .= '<td align="center">'.&mt($type).'<br />'.
 4753:                            '<input type="text" name="'.$type.'_credits"'.
 4754:                            ' value="'.$defcredits{$type}.'" size="3" /></td>';
 4755:         }
 4756:         $additional .= '</tr></table></div>'."\n";
 4757:         %defaultchecked = ('coursecredits' => 'off');
 4758:         @toggles = ('coursecredits');
 4759:         my $current = {
 4760:                         'coursecredits' => $currusecredits,
 4761:                       };
 4762:         (my $table,$itemcount) =
 4763:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 4764:                                \%choices,$itemcount,$onclick,$additional,'left');
 4765:         $datatable .= $table;
 4766:         $onclick = "toggleDisplay(this.form,'studentsubmission');";
 4767:         my $display = 'none';
 4768:         if ($postsubmitclient) {
 4769:             $display = 'block';
 4770:         }
 4771:         $additional = '<div id="studentsubmission" style="display: '.$display.'">'.
 4772:                       &mt('Number of seconds submit is disabled').'<br />'.
 4773:                       '<i>'.&mt('Enter 0 to remain disabled until page reload.').'</i><br />'.
 4774:                       '<table><tr>';
 4775:         foreach my $type (@types) {
 4776:             $additional .= '<td align="center">'.&mt($type).'<br />'.
 4777:                            '<input type="text" name="'.$type.'_timeout" value="'.
 4778:                            $deftimeout{$type}.'" size="5" /></td>';
 4779:         }
 4780:         $additional .= '</tr></table></div>'."\n";
 4781:         %defaultchecked = ('postsubmit' => 'on');
 4782:         @toggles = ('postsubmit');
 4783:         $current = {
 4784:                        'postsubmit' => $postsubmitclient,
 4785:                    };
 4786:         ($table,$itemcount) =
 4787:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 4788:                                \%choices,$itemcount,$onclick,$additional,'left');
 4789:         $datatable .= $table;
 4790:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 4791:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 4792:                       $choices{'mysqltables'}.
 4793:                       '</span></td>'.
 4794:                       '<td align="right" class="LC_right_item">'.
 4795:                       '<table><tr>';
 4796:         foreach my $type (@types) {
 4797:             $datatable .= '<td align="center">'.&mt($type).'<br />'.
 4798:                            '<input type="text" name="mysqltables_'.$type.'"'.
 4799:                            ' value="'.$currmysql{$type}.'" size="8" /></td>';
 4800:         }
 4801:         $datatable .= '</tr></table></td></tr>'."\n";
 4802:         $itemcount ++;
 4803: 
 4804:     }
 4805:     $$rowtotal += $itemcount;
 4806:     return $datatable;
 4807: }
 4808: 
 4809: sub print_selfenrollment {
 4810:     my ($position,$dom,$settings,$rowtotal) = @_;
 4811:     my ($css_class,$datatable);
 4812:     my $itemcount = 1;
 4813:     my @types = ('official','unofficial','community','textbook');
 4814:     if (($position eq 'top') || ($position eq 'middle')) {
 4815:         my ($rowsref,$titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
 4816:         my %descs = &Apache::lonuserutils::selfenroll_default_descs();
 4817:         my @rows;
 4818:         my $key;
 4819:         if ($position eq 'top') {
 4820:             $key = 'admin'; 
 4821:             if (ref($rowsref) eq 'ARRAY') {
 4822:                 @rows = @{$rowsref};
 4823:             }
 4824:         } elsif ($position eq 'middle') {
 4825:             $key = 'default';
 4826:             @rows = ('types','registered','approval','limit');
 4827:         }
 4828:         foreach my $row (@rows) {
 4829:             if (defined($titlesref->{$row})) {
 4830:                 $itemcount ++;
 4831:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4832:                 $datatable .= '<tr'.$css_class.'>'.
 4833:                               '<td>'.$titlesref->{$row}.'</td>'.
 4834:                               '<td class="LC_left_item">'.
 4835:                               '<table><tr>';
 4836:                 my (%current,%currentcap);
 4837:                 if (ref($settings) eq 'HASH') {
 4838:                     if (ref($settings->{$key}) eq 'HASH') {
 4839:                         foreach my $type (@types) {
 4840:                             if (ref($settings->{$key}->{$type}) eq 'HASH') {
 4841:                                 $current{$type} = $settings->{$key}->{$type}->{$row};
 4842:                             }
 4843:                             if (($row eq 'limit') && ($key eq 'default')) {
 4844:                                 if (ref($settings->{$key}->{$type}) eq 'HASH') {
 4845:                                     $currentcap{$type} = $settings->{$key}->{$type}->{'cap'};
 4846:                                 }
 4847:                             }
 4848:                         }
 4849:                     }
 4850:                 }
 4851:                 my %roles = (
 4852:                              '0' => &Apache::lonnet::plaintext('dc'),
 4853:                             ); 
 4854:             
 4855:                 foreach my $type (@types) {
 4856:                     unless (($row eq 'registered') && ($key eq 'default')) {
 4857:                         $datatable .= '<th>'.&mt($type).'</th>';
 4858:                     }
 4859:                 }
 4860:                 unless (($row eq 'registered') && ($key eq 'default')) {
 4861:                     $datatable .= '</tr><tr>';
 4862:                 }
 4863:                 foreach my $type (@types) {
 4864:                     if ($type eq 'community') {
 4865:                         $roles{'1'} = &mt('Community personnel');
 4866:                     } else {
 4867:                         $roles{'1'} = &mt('Course personnel');
 4868:                     }
 4869:                     $datatable .= '<td style="vertical-align: top">';
 4870:                     if ($position eq 'top') {
 4871:                         my %checked;
 4872:                         if ($current{$type} eq '0') {
 4873:                             $checked{'0'} = ' checked="checked"';
 4874:                         } else {
 4875:                             $checked{'1'} = ' checked="checked"';
 4876:                         }
 4877:                         foreach my $role ('1','0') {
 4878:                             $datatable .= '<span class="LC_nobreak"><label>'.
 4879:                                           '<input type="radio" name="selfenrolladmin_'.$row.'_'.$type.'" '.
 4880:                                           'value="'.$role.'"'.$checked{$role}.' />'.
 4881:                                           $roles{$role}.'</label></span> ';
 4882:                         }
 4883:                     } else {
 4884:                         if ($row eq 'types') {
 4885:                             my %checked;
 4886:                             if ($current{$type} =~ /^(all|dom)$/) {
 4887:                                 $checked{$1} = ' checked="checked"';
 4888:                             } else {
 4889:                                 $checked{''} = ' checked="checked"';
 4890:                             }
 4891:                             foreach my $val ('','dom','all') {
 4892:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 4893:                                               '<input type ="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 4894:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 4895:                             }
 4896:                         } elsif ($row eq 'registered') {
 4897:                             my %checked;
 4898:                             if ($current{$type} eq '1') {
 4899:                                 $checked{'1'} = ' checked="checked"';
 4900:                             } else {
 4901:                                 $checked{'0'} = ' checked="checked"';
 4902:                             }
 4903:                             foreach my $val ('0','1') {
 4904:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 4905:                                               '<input type ="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 4906:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 4907:                             }
 4908:                         } elsif ($row eq 'approval') {
 4909:                             my %checked;
 4910:                             if ($current{$type} =~ /^([12])$/) {
 4911:                                 $checked{$1} = ' checked="checked"';
 4912:                             } else {
 4913:                                 $checked{'0'} = ' checked="checked"';
 4914:                             }
 4915:                             for my $val (0..2) {
 4916:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 4917:                                               '<input type="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 4918:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 4919:                             }
 4920:                         } elsif ($row eq 'limit') {
 4921:                             my %checked;
 4922:                             if ($current{$type} =~ /^(allstudents|selfenrolled)$/) {
 4923:                                 $checked{$1} = ' checked="checked"';
 4924:                             } else {
 4925:                                 $checked{'none'} = ' checked="checked"';
 4926:                             }
 4927:                             my $cap;
 4928:                             if ($currentcap{$type} =~ /^\d+$/) {
 4929:                                 $cap = $currentcap{$type};
 4930:                             }
 4931:                             foreach my $val ('none','allstudents','selfenrolled') {
 4932:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 4933:                                               '<input type="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 4934:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 4935:                             }
 4936:                             $datatable .= '<br />'.
 4937:                                           '<span class="LC_nobreak">'.&mt('Maximum allowed: ').
 4938:                                           '<input type="text" name="selfenrolldefault_cap_'.$type.'" size = "5" value="'.$cap.'" />'.
 4939:                                           '</span>'; 
 4940:                         }
 4941:                     }
 4942:                     $datatable .= '</td>';
 4943:                 }
 4944:                 $datatable .= '</tr>';
 4945:             }
 4946:             $datatable .= '</table></td></tr>';
 4947:         }
 4948:     } elsif ($position eq 'bottom') {
 4949:         $datatable .= &print_validation_rows('selfenroll',$dom,$settings,\$itemcount);
 4950:     }
 4951:     $$rowtotal += $itemcount;
 4952:     return $datatable;
 4953: }
 4954: 
 4955: sub print_validation_rows {
 4956:     my ($caller,$dom,$settings,$rowtotal) = @_;
 4957:     my ($itemsref,$namesref,$fieldsref);
 4958:     if ($caller eq 'selfenroll') { 
 4959:         ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
 4960:     } elsif ($caller eq 'requestcourses') {
 4961:         ($itemsref,$namesref,$fieldsref) = &Apache::loncoursequeueadmin::requestcourses_validation_types();
 4962:     }
 4963:     my %currvalidation;
 4964:     if (ref($settings) eq 'HASH') {
 4965:         if (ref($settings->{'validation'}) eq 'HASH') {
 4966:             %currvalidation = %{$settings->{'validation'}};
 4967:         }
 4968:     }
 4969:     my $datatable;
 4970:     my $itemcount = 0;
 4971:     foreach my $item (@{$itemsref}) {
 4972:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 4973:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 4974:                       $namesref->{$item}.
 4975:                       '</span></td>'.
 4976:                       '<td class="LC_left_item">';
 4977:         if (($item eq 'url') || ($item eq 'button')) {
 4978:             $datatable .= '<span class="LC_nobreak">'.
 4979:                           '<input type="text" name="'.$caller.'_validation_'.$item.'"'.
 4980:                           ' value="'.$currvalidation{$item}.'" size="50" /></span>';
 4981:         } elsif ($item eq 'fields') {
 4982:             my @currfields;
 4983:             if (ref($currvalidation{$item}) eq 'ARRAY') {
 4984:                 @currfields = @{$currvalidation{$item}};
 4985:             }
 4986:             foreach my $field (@{$fieldsref}) {
 4987:                 my $check = '';
 4988:                 if (grep(/^\Q$field\E$/,@currfields)) {
 4989:                     $check = ' checked="checked"';
 4990:                 }
 4991:                 $datatable .= '<span class="LC_nobreak"><label>'.
 4992:                               '<input type="checkbox" name="'.$caller.'_validation_fields"'.
 4993:                               ' value="'.$field.'"'.$check.' />'.$field.
 4994:                               '</label></span> ';
 4995:             }
 4996:         } elsif ($item eq 'markup') {
 4997:             $datatable .= '<textarea name="'.$caller.'_validation_markup" cols="50" rows="5">'.
 4998:                            $currvalidation{$item}.
 4999:                               '</textarea>';
 5000:         }
 5001:         $datatable .= '</td></tr>'."\n";
 5002:         if (ref($rowtotal)) {
 5003:             $itemcount ++;
 5004:         }
 5005:     }
 5006:     if ($caller eq 'requestcourses') {
 5007:         my %currhash;
 5008:         if (ref($settings) eq 'HASH') {
 5009:             if (ref($settings->{'validation'}) eq 'HASH') {
 5010:                 if ($settings->{'validation'}{'dc'} ne '') {
 5011:                     $currhash{$settings->{'validation'}{'dc'}} = 1;
 5012:                 }
 5013:             }
 5014:         }
 5015:         my $numinrow = 2;
 5016:         my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 5017:                                                        'validationdc',%currhash);
 5018:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 5019:         $datatable .= '<tr'.$css_class.'><td>';
 5020:         if ($numdc > 1) {
 5021:             $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)');
 5022:         } else {
 5023:             $datatable .=  &mt('Course creation processed as: ');
 5024:         }
 5025:         $datatable .= '</td><td class="LC_left_item">'.$dctable.'</td></tr>';
 5026:         $itemcount ++;
 5027:     }
 5028:     if (ref($rowtotal)) {
 5029:         $$rowtotal += $itemcount;
 5030:     }
 5031:     return $datatable;
 5032: }
 5033: 
 5034: sub print_passwords {
 5035:     my ($position,$dom,$confname,$settings,$rowtotal) = @_;
 5036:     my ($datatable,$css_class);
 5037:     my $itemcount = 0;
 5038:     my %titles = &Apache::lonlocal::texthash (
 5039:         captcha        => '"Forgot Password" CAPTCHA validation',
 5040:         link           => 'Reset link expiration (hours)',
 5041:         case           => 'Case-sensitive usernames/e-mail',
 5042:         prelink        => 'Information required (form 1)',
 5043:         postlink       => 'Information required (form 2)',
 5044:         emailsrc       => 'LON-CAPA e-mail address type(s)',
 5045:         customtext     => 'Domain specific text (HTML)',
 5046:         intauth_cost   => 'Encryption cost for bcrypt (positive integer)',
 5047:         intauth_check  => 'Check bcrypt cost if authenticated',
 5048:         intauth_switch => 'Existing crypt-based switched to bcrypt on authentication',
 5049:         permanent      => 'Permanent e-mail address',
 5050:         critical       => 'Critical notification address',
 5051:         notify         => 'Notification address',
 5052:         min            => 'Minimum password length',
 5053:         max            => 'Maximum password length',
 5054:         chars          => 'Required characters',
 5055:         numsaved       => 'Number of previous passwords to save and disallow reuse',
 5056:     );
 5057:     if ($position eq 'top') {
 5058:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 5059:         my $shownlinklife = 2;
 5060:         my $prelink = 'both';
 5061:         my (%casesens,%postlink,%emailsrc,$nostdtext,$customurl);
 5062:         if (ref($settings) eq 'HASH') {
 5063:             if ($settings->{resetlink} =~ /^\d+(|\.\d*)$/) {
 5064:                 $shownlinklife = $settings->{resetlink};
 5065:             }
 5066:             if (ref($settings->{resetcase}) eq 'ARRAY') {
 5067:                 map { $casesens{$_} = 1; } (@{$settings->{resetcase}});
 5068:             }
 5069:             if ($settings->{resetprelink} =~ /^(both|either)$/) {
 5070:                 $prelink = $settings->{resetprelink};
 5071:             }
 5072:             if (ref($settings->{resetpostlink}) eq 'HASH') {
 5073:                 %postlink = %{$settings->{resetpostlink}};
 5074:             }
 5075:             if (ref($settings->{resetemail}) eq 'ARRAY') {
 5076:                 map { $emailsrc{$_} = 1; } (@{$settings->{resetemail}});
 5077:             }
 5078:             if ($settings->{resetremove}) {
 5079:                 $nostdtext = 1;
 5080:             }
 5081:             if ($settings->{resetcustom}) {
 5082:                 $customurl = $settings->{resetcustom};
 5083:             }
 5084:         } else {
 5085:             if (ref($types) eq 'ARRAY') {
 5086:                 foreach my $item (@{$types}) {
 5087:                     $casesens{$item} = 1;
 5088:                     $postlink{$item} = ['username','email'];
 5089:                 }
 5090:             }
 5091:             $casesens{'default'} = 1;
 5092:             $postlink{'default'} = ['username','email'];
 5093:             $prelink = 'both';
 5094:             %emailsrc = (
 5095:                           permanent => 1,
 5096:                           critical  => 1,
 5097:                           notify    => 1,
 5098:             );
 5099:         }
 5100:         $datatable = &captcha_choice('passwords',$settings,$$rowtotal);
 5101:         $itemcount ++;
 5102:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5103:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'link'}.'</td>'.
 5104:                       '<td class="LC_left_item">'.
 5105:                       '<input type="textbox" value="'.$shownlinklife.'" '.
 5106:                       'name="passwords_link" size="3" /></td></tr>';
 5107:         $itemcount ++;
 5108:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5109:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'case'}.'</td>'.
 5110:                       '<td class="LC_left_item">';
 5111:         if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 5112:             foreach my $item (@{$types}) {
 5113:                 my $checkedcase;
 5114:                 if ($casesens{$item}) {
 5115:                     $checkedcase = ' checked="checked"';
 5116:                 }
 5117:                 $datatable .= '<span class="LC_nobreak"><label>'.
 5118:                               '<input type="checkbox" name="passwords_case_sensitive" value="'.
 5119:                               $item.'"'.$checkedcase.' />'.$usertypes->{$item}.'</label>'.
 5120:                               '</span>&nbsp;&nbsp; ';
 5121:             }
 5122:         }
 5123:         my $checkedcase;
 5124:         if ($casesens{'default'}) {
 5125:             $checkedcase = ' checked="checked"';
 5126:         }
 5127:         $datatable .= '<span class="LC_nobreak"><label><input type="checkbox" '.
 5128:                       'name="passwords_case_sensitive" value="default"'.$checkedcase.' />'.
 5129:                       $othertitle.'</label></span></td>';
 5130:         $itemcount ++;
 5131:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5132:         my %checkedpre = (
 5133:                              both => ' checked="checked"',
 5134:                              either => '',
 5135:                          );
 5136:         if ($prelink eq 'either') {
 5137:             $checkedpre{either} = ' checked="checked"';
 5138:             $checkedpre{both} = '';
 5139:         }
 5140:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'prelink'}.'</td>'.
 5141:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 5142:                       '<label><input type="radio" name="passwords_prelink" value="both"'.$checkedpre{'both'}.' />'.
 5143:                       &mt('Both username and e-mail address').'</label></span>&nbsp;&nbsp; '.
 5144:                       '<span class="LC_nobreak"><label>'.
 5145:                       '<input type="radio" name="passwords_prelink" value="either"'.$checkedpre{'either'}.' />'.
 5146:                       &mt('Either username or e-mail address').'</label></span></td></tr>';
 5147:         $itemcount ++;
 5148:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5149:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'postlink'}.'</td>'.
 5150:                       '<td class="LC_left_item">';
 5151:         my %postlinked;
 5152:         if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 5153:             foreach my $item (@{$types}) {
 5154:                 undef(%postlinked);
 5155:                 $datatable .= '<fieldset style="display: inline-block;">'.
 5156:                               '<legend>'.$usertypes->{$item}.'</legend>';
 5157:                 if (ref($postlink{$item}) eq 'ARRAY') {
 5158:                     map { $postlinked{$_} = 1; } (@{$postlink{$item}});
 5159:                 }
 5160:                 foreach my $field ('email','username') {
 5161:                     my $checked;
 5162:                     if ($postlinked{$field}) {
 5163:                         $checked = ' checked="checked"';
 5164:                     }
 5165:                     $datatable .= '<span class="LC_nobreak"><label>'.
 5166:                                   '<input type="checkbox" name="passwords_postlink_'.$item.'" value="'.
 5167:                                   $field.'"'.$checked.' />'.$field.'</label>'.
 5168:                                   '<span>&nbsp;&nbsp; ';
 5169:                 }
 5170:                 $datatable .= '</fieldset>';
 5171:             }
 5172:         }
 5173:         if (ref($postlink{'default'}) eq 'ARRAY') {
 5174:             map { $postlinked{$_} = 1; } (@{$postlink{'default'}});
 5175:         }
 5176:         $datatable .= '<fieldset style="display: inline-block;">'.
 5177:                       '<legend>'.$othertitle.'</legend>';
 5178:         foreach my $field ('email','username') {
 5179:             my $checked;
 5180:             if ($postlinked{$field}) {
 5181:                 $checked = ' checked="checked"';
 5182:             }
 5183:             $datatable .= '<span class="LC_nobreak"><label>'.
 5184:                           '<input type="checkbox" name="passwords_postlink_default" value="'.
 5185:                           $field.'"'.$checked.' />'.$field.'</label>'.
 5186:                           '<span>&nbsp;&nbsp; ';
 5187:         }
 5188:         $datatable .= '</fieldset></td></tr>';
 5189:         $itemcount ++;
 5190:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5191:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'emailsrc'}.'</td>'.
 5192:                       '<td class="LC_left_item">';
 5193:         foreach my $type ('permanent','critical','notify') {
 5194:             my $checkedemail;
 5195:             if ($emailsrc{$type}) {
 5196:                 $checkedemail = ' checked="checked"';
 5197:             }
 5198:             $datatable .= '<span class="LC_nobreak"><label>'.
 5199:                           '<input type="checkbox" name="passwords_emailsrc" value="'.
 5200:                           $type.'"'.$checkedemail.' />'.$titles{$type}.'</label>'.
 5201:                           '<span>&nbsp;&nbsp; ';
 5202:         }
 5203:         $datatable .= '</td></tr>';
 5204:         $itemcount ++;
 5205:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5206:         my $switchserver = &check_switchserver($dom,$confname);
 5207:         my ($showstd,$noshowstd);
 5208:         if ($nostdtext) {
 5209:             $noshowstd = ' checked="checked"';
 5210:         } else {
 5211:             $showstd = ' checked="checked"';
 5212:         }
 5213:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'customtext'}.'</td>'.
 5214:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 5215:                       &mt('Retain standard text:').
 5216:                       '<label><input type="radio" name="passwords_stdtext" value="1"'.$showstd.' />'.
 5217:                       &mt('Yes').'</label>'.'&nbsp;'.
 5218:                       '<label><input type="radio" name="passwords_stdtext" value="0"'.$noshowstd.' />'.
 5219:                       &mt('No').'</label></span><br />'.
 5220:                       '<span class="LC_fontsize_small">'.
 5221:                       &mt('(If you use the same account ...  reset a password from this page.)').'</span><br /><br />'.
 5222:                       &mt('Include custom text:');
 5223:         if ($customurl) {
 5224:             my $link =  &Apache::loncommon::modal_link($customurl,&mt('custom text'),600,500,
 5225:                                                        undef,undef,undef,undef,'background-color:#ffffff');
 5226:             $datatable .= '<span class="LC_nobreak">&nbsp;'.$link.
 5227:                           '<label><input type="checkbox" name="passwords_custom_del"'.
 5228:                           ' value="1" />'.&mt('Delete?').'</label></span>'.
 5229:                           ' <span class="LC_nobreak">&nbsp;'.&mt('Replace:').'</span>';
 5230:         }
 5231:         if ($switchserver) {
 5232:             $datatable .= '<span class="LC_nobreak">&nbsp;'.&mt('Upload to library server: [_1]',$switchserver).'</span>';
 5233:         } else {
 5234:             $datatable .='<span class="LC_nobreak">&nbsp;'.
 5235:                          '<input type="file" name="passwords_customfile" /></span>';
 5236:         }
 5237:         $datatable .= '</td></tr>';
 5238:     } elsif ($position eq 'middle') {
 5239:         my %domconf = &Apache::lonnet::get_dom('configuration',['defaults'],$dom);
 5240:         my @items = ('intauth_cost','intauth_check','intauth_switch');
 5241:         my %defaults;
 5242:         if (ref($domconf{'defaults'}) eq 'HASH') {
 5243:             %defaults = %{$domconf{'defaults'}};
 5244:             if ($defaults{'intauth_cost'} !~ /^\d+$/) {
 5245:                 $defaults{'intauth_cost'} = 10;
 5246:             }
 5247:             if ($defaults{'intauth_check'} !~ /^(0|1|2)$/) {
 5248:                 $defaults{'intauth_check'} = 0;
 5249:             }
 5250:             if ($defaults{'intauth_switch'} !~ /^(0|1|2)$/) {
 5251:                 $defaults{'intauth_switch'} = 0;
 5252:             }
 5253:         } else {
 5254:             %defaults = (
 5255:                           'intauth_cost'   => 10,
 5256:                           'intauth_check'  => 0,
 5257:                           'intauth_switch' => 0,
 5258:                         );
 5259:         }
 5260:         foreach my $item (@items) {
 5261:             if ($itemcount%2) {
 5262:                 $css_class = '';
 5263:             } else {
 5264:                 $css_class = ' class="LC_odd_row" ';
 5265:             }
 5266:             $datatable .= '<tr'.$css_class.'>'.
 5267:                           '<td><span class="LC_nobreak">'.$titles{$item}.
 5268:                           '</span></td><td class="LC_left_item" colspan="3">';
 5269:             if ($item eq 'intauth_switch') {
 5270:                 my @options = (0,1,2);
 5271:                 my %optiondesc = &Apache::lonlocal::texthash (
 5272:                                    0 => 'No',
 5273:                                    1 => 'Yes',
 5274:                                    2 => 'Yes, and copy existing passwd file to passwd.bak file',
 5275:                                  );
 5276:                 $datatable .= '<table width="100%">';
 5277:                 foreach my $option (@options) {
 5278:                     my $checked = ' ';
 5279:                     if ($defaults{$item} eq $option) {
 5280:                         $checked = ' checked="checked"';
 5281:                     }
 5282:                     $datatable .= '<tr><td class="LC_left_item"><span class="LC_nobreak">'.
 5283:                                   '<label><input type="radio" name="'.$item.
 5284:                                   '" value="'.$option.'"'.$checked.' />'.
 5285:                                   $optiondesc{$option}.'</label></span></td></tr>';
 5286:                 }
 5287:                 $datatable .= '</table>';
 5288:             } elsif ($item eq 'intauth_check') {
 5289:                 my @options = (0,1,2);
 5290:                 my %optiondesc = &Apache::lonlocal::texthash (
 5291:                                    0 => 'No',
 5292:                                    1 => 'Yes, allow login then update passwd file using default cost (if higher)',
 5293:                                    2 => 'Yes, disallow login if stored cost is less than domain default',
 5294:                                  );
 5295:                 $datatable .= '<table width="100%">';
 5296:                 foreach my $option (@options) {
 5297:                     my $checked = ' ';
 5298:                     my $onclick;
 5299:                     if ($defaults{$item} eq $option) {
 5300:                         $checked = ' checked="checked"';
 5301:                     }
 5302:                     if ($option == 2) {
 5303:                         $onclick = ' onclick="javascript:warnIntAuth(this);"';
 5304:                     }
 5305:                     $datatable .= '<tr><td class="LC_left_item"><span class="LC_nobreak">'.
 5306:                                   '<label><input type="radio" name="'.$item.
 5307:                                   '" value="'.$option.'"'.$checked.$onclick.' />'.
 5308:                                   $optiondesc{$option}.'</label></span></td></tr>';
 5309:                 }
 5310:                 $datatable .= '</table>';
 5311:             } else {
 5312:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
 5313:                               $defaults{$item}.'" size="3" onblur="javascript:warnIntAuth(this);" />';
 5314:             }
 5315:             $datatable .= '</td></tr>';
 5316:             $itemcount ++;
 5317:         }
 5318:     } elsif ($position eq 'lower') {
 5319:         my ($min,$max,%chars,$numsaved);
 5320:         $min = $Apache::lonnet::passwdmin;
 5321:         if (ref($settings) eq 'HASH') {
 5322:             if ($settings->{min}) {
 5323:                 $min = $settings->{min};
 5324:             }
 5325:             if ($settings->{max}) {
 5326:                 $max = $settings->{max};
 5327:             }
 5328:             if (ref($settings->{chars}) eq 'ARRAY') {
 5329:                 map { $chars{$_} = 1; } (@{$settings->{chars}});
 5330:             }
 5331:             if ($settings->{numsaved}) {
 5332:                 $numsaved = $settings->{numsaved};
 5333:             }
 5334:         }
 5335:         my %rulenames = &Apache::lonlocal::texthash(
 5336:                                                      uc => 'At least one upper case letter',
 5337:                                                      lc => 'At least one lower case letter',
 5338:                                                      num => 'At least one number',
 5339:                                                      spec => 'At least one non-alphanumeric',
 5340:                                                    );
 5341:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5342:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'min'}.'</td>'.
 5343:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 5344:                       '<input type="text" name="passwords_min" value="'.$min.'" size="3" '.
 5345:                       'onblur="javascript:warnIntPass(this);" />'.
 5346:                       '<span class="LC_fontsize_small"> '.&mt('(Enter an integer: 7 or larger)').'</span>'.
 5347:                       '</span></td></tr>';
 5348:         $itemcount ++;
 5349:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5350:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'max'}.'</td>'.
 5351:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 5352:                       '<input type="text" name="passwords_max" value="'.$max.'" size="3" '.
 5353:                       'onblur="javascript:warnIntPass(this);" />'.
 5354:                       '<span class="LC_fontsize_small"> '.&mt('(Leave blank for no maximum)').'</span>'.
 5355:                       '</span></td></tr>';
 5356:         $itemcount ++;
 5357:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5358:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'chars'}.'<br />'.
 5359:                       '<span class="LC_nobreak LC_fontsize_small">'.&mt('(Leave unchecked if not required)').
 5360:                       '</span></td>';
 5361:         my $numinrow = 2;
 5362:         my @possrules = ('uc','lc','num','spec');
 5363:         $datatable .= '<td class="LC_left_item"><table>';
 5364:         for (my $i=0; $i<@possrules; $i++) {
 5365:             my ($rem,$checked);
 5366:             if ($chars{$possrules[$i]}) {
 5367:                 $checked = ' checked="checked"';
 5368:             }
 5369:             $rem = $i%($numinrow);
 5370:             if ($rem == 0) {
 5371:                 if ($i > 0) {
 5372:                     $datatable .= '</tr>';
 5373:                 }
 5374:                 $datatable .= '<tr>';
 5375:             }
 5376:             $datatable .= '<td><span class="LC_nobreak"><label>'.
 5377:                           '<input type="checkbox" name="passwords_chars" value="'.$possrules[$i].'"'.$checked.' />'.
 5378:                           $rulenames{$possrules[$i]}.'</label></span></td>';
 5379:         }
 5380:         my $rem = @possrules%($numinrow);
 5381:         my $colsleft = $numinrow - $rem;
 5382:         if ($colsleft > 1 ) {
 5383:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 5384:                           '&nbsp;</td>';
 5385:         } elsif ($colsleft == 1) {
 5386:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 5387:         }
 5388:         $datatable .='</table></td></tr>';
 5389:         $itemcount ++;
 5390:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5391:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'numsaved'}.'</td>'.
 5392:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 5393:                       '<input type="text" name="passwords_numsaved" value="'.$numsaved.'" size="3" '.
 5394:                       'onblur="javascript:warnIntPass(this);" />'.
 5395:                       '<span class="LC_fontsize_small"> '.&mt('(Leave blank to not save previous passwords)').'</span>'.
 5396:                       '</span></td></tr>';
 5397:     } else {
 5398:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 5399:         my %ownerchg = (
 5400:                           by  => {},
 5401:                           for => {},
 5402:                        );
 5403:         my %ownertitles = &Apache::lonlocal::texthash (
 5404:                             by  => 'Course owner status(es) allowed',
 5405:                             for => 'Student status(es) allowed',
 5406:                           );
 5407:         if (ref($settings) eq 'HASH') {
 5408:             if (ref($settings->{crsownerchg}) eq 'HASH') {
 5409:                 if (ref($settings->{crsownerchg}{'by'}) eq 'ARRAY') {
 5410:                     map { $ownerchg{by}{$_} = 1; } (@{$settings->{crsownerchg}{'by'}});
 5411:                 }
 5412:                 if (ref($settings->{crsownerchg}{'for'}) eq 'ARRAY') {
 5413:                     map { $ownerchg{for}{$_} = 1; } (@{$settings->{crsownerchg}{'for'}});
 5414:                 }
 5415:             }
 5416:         }
 5417:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5418:         $datatable .= '<tr '.$css_class.'>'.
 5419:                       '<td>'.
 5420:                       &mt('Requirements').'<ul>'.
 5421:                       '<li>'.&mt("Course 'type' is not a Community").'</li>'.
 5422:                       '<li>'.&mt('User is Course Coordinator and also course owner').'</li>'.
 5423:                       '<li>'.&mt("Student's only active roles are student role(s) in course(s) owned by this user").'</li>'.
 5424:                       '<li>'.&mt('User, course, and student share same domain').'</li>'.
 5425:                       '</ul>'.
 5426:                       '</td>'.
 5427:                       '<td class="LC_left_item">';
 5428:         foreach my $item ('by','for') {
 5429:             $datatable .= '<fieldset style="display: inline-block;">'.
 5430:                           '<legend>'.$ownertitles{$item}.'</legend>';
 5431:             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 5432:                 foreach my $type (@{$types}) {
 5433:                     my $checked;
 5434:                     if ($ownerchg{$item}{$type}) {
 5435:                         $checked = ' checked="checked"';
 5436:                     }
 5437:                     $datatable .= '<span class="LC_nobreak"><label>'.
 5438:                                   '<input type="checkbox" name="passwords_crsowner_'.$item.'" value="'.
 5439:                                   $type.'"'.$checked.' />'.$usertypes->{$type}.'</label>'.
 5440:                                   '</span>&nbsp;&nbsp; ';
 5441:                 }
 5442:             }
 5443:             my $checked;
 5444:             if ($ownerchg{$item}{'default'}) {
 5445:                 $checked = ' checked="checked"';
 5446:             }
 5447:             $datatable .= '<span class="LC_nobreak"><label><input type="checkbox" '.
 5448:                           'name="passwords_crsowner_'.$item.'" value="default"'.$checked.' />'.
 5449:                           $othertitle.'</label></span></fieldset>';
 5450:         }
 5451:         $datatable .= '</td></tr>';
 5452:     }
 5453:     return $datatable;
 5454: }
 5455: 
 5456: sub print_wafproxy {
 5457:     my ($position,$dom,$settings,$rowtotal) = @_;
 5458:     my $css_class;
 5459:     my $itemcount = 0;
 5460:     my $datatable;
 5461:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 5462:     my (%othercontrol,%otherdoms,%aliases,%saml,%values,$setdom,$showdom);
 5463:     my %lt = &wafproxy_titles();
 5464:     foreach my $server (sort(keys(%servers))) {
 5465:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
 5466:         next if ($serverhome eq '');
 5467:         my $serverdom;
 5468:         if ($serverhome ne $server) {
 5469:             $serverdom = &Apache::lonnet::host_domain($serverhome);
 5470:             if (($serverdom ne '') && (&Apache::lonnet::domain($serverdom) ne '')) {
 5471:                 $othercontrol{$server} = $serverdom;
 5472:             }
 5473:         } else {
 5474:             $serverdom = &Apache::lonnet::host_domain($server);
 5475:             next if (($serverdom eq '') || (&Apache::lonnet::domain($serverdom) eq ''));
 5476:             if ($serverdom ne $dom) {
 5477:                 $othercontrol{$server} = $serverdom;
 5478:             } else {
 5479:                 $setdom = 1;
 5480:                 if (ref($settings) eq 'HASH') {
 5481:                     if (ref($settings->{'alias'}) eq 'HASH') {
 5482:                         $aliases{$dom} = $settings->{'alias'};
 5483:                         if ($aliases{$dom} ne '') {
 5484:                             $showdom = 1;
 5485:                         }
 5486:                     }
 5487:                     if (ref($settings->{'saml'}) eq 'HASH') {
 5488:                         $saml{$dom} = $settings->{'saml'};
 5489:                     }
 5490:                 }
 5491:             }
 5492:         }
 5493:     }
 5494:     if ($setdom) {
 5495:         %{$values{$dom}} = ();
 5496:         if (ref($settings) eq 'HASH') {
 5497:             foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext') {
 5498:                 $values{$dom}{$item} = $settings->{$item};
 5499:             }
 5500:         }
 5501:     }
 5502:     if (keys(%othercontrol)) {
 5503:         %otherdoms = reverse(%othercontrol);
 5504:         foreach my $domain (keys(%otherdoms)) {
 5505:             %{$values{$domain}} = ();
 5506:             my %config = &Apache::lonnet::get_dom('configuration',['wafproxy'],$domain);
 5507:             if (ref($config{'wafproxy'}) eq 'HASH') {
 5508:                 $aliases{$domain} = $config{'wafproxy'}{'alias'};
 5509:                 if (exists($config{'wafproxy'}{'saml'})) {
 5510:                     $saml{$domain} = $config{'wafproxy'}{'saml'};
 5511:                 }
 5512:                 foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext') {
 5513:                     $values{$domain}{$item} = $config{'wafproxy'}{$item};
 5514:                 }
 5515:             }
 5516:         }
 5517:     }
 5518:     if ($position eq 'top') {
 5519:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 5520:         my %aliasinfo;
 5521:         foreach my $server (sort(keys(%servers))) {
 5522:             $itemcount ++;
 5523:             my $dom_in_effect;
 5524:             my $aliasrows = '<tr>'.
 5525:                             '<td class="LC_left_item" style="vertical-align: baseline;">'.
 5526:                             &mt('Hostname').': '.
 5527:                             '<span class="LC_nobreak LC_cusr_emph">'.
 5528:                             &Apache::lonnet::hostname($server).
 5529:                             '</span></td><td>&nbsp;</td>';
 5530:             if ($othercontrol{$server}) {
 5531:                 $dom_in_effect = $othercontrol{$server};
 5532:                 my ($current,$forsaml);
 5533:                 if (ref($aliases{$dom_in_effect}) eq 'HASH') {
 5534:                     $current = $aliases{$dom_in_effect}{$server};
 5535:                 }
 5536:                 if (ref($saml{$dom_in_effect}) eq 'HASH') {
 5537:                     if ($saml{$dom_in_effect}{$server}) {
 5538:                         $forsaml = 1;
 5539:                     }
 5540:                 }
 5541:                 $aliasrows .= '<td class="LC_left_item" style="vertical-align: baseline;">'.
 5542:                               &mt('Alias').':&nbsp';
 5543:                 if ($current) {
 5544:                     $aliasrows .= $current;
 5545:                     if ($forsaml) {
 5546:                          $aliasrows .= '&nbsp;('.&mt('also for SSO Auth').')';
 5547:                     }
 5548:                 } else {
 5549:                     $aliasrows .= &mt('None');
 5550:                 }
 5551:                 $aliasrows .= '&nbsp;<span class="LC_small">('.
 5552:                               &mt('controlled by domain: [_1]',
 5553:                                   '<b>'.$dom_in_effect.'</b>').')</span></td>';
 5554:             } else {
 5555:                 $dom_in_effect = $dom;
 5556:                 my ($current,$samlon,$samloff);
 5557:                 $samloff = ' checked="checked"';
 5558:                 if (ref($aliases{$dom}) eq 'HASH') {
 5559:                     if ($aliases{$dom}{$server}) {
 5560:                         $current = $aliases{$dom}{$server};
 5561:                     }
 5562:                 }
 5563:                 if (ref($saml{$dom}) eq 'HASH') {
 5564:                     if ($saml{$dom}{$server}) {
 5565:                         $samlon = $samloff;
 5566:                         undef($samloff);
 5567:                     }
 5568:                 }
 5569:                 $aliasrows .= '<td class="LC_left_item" style="vertical-align: baseline;">'.
 5570:                               &mt('Alias').':&nbsp;'.
 5571:                               '<input type="text" name="wafproxy_alias_'.$server.'" '.
 5572:                               'value="'.$current.'" size="30" />'.
 5573:                               ('&nbsp;'x2).'<span class="LC_nobreak">'.
 5574:                               &mt('Alias used for SSO Auth').':&nbsp;<label>'.
 5575:                               '<input type="radio" value="0"'.$samloff.' name="wafproxy_alias_saml_'.$server.'" />'.
 5576:                               &mt('No').'</label>&nbsp;<label>'.
 5577:                               '<input type="radio" value="1"'.$samlon.' name="wafproxy_alias_saml_'.$server.'" />'.
 5578:                               &mt('Yes').'</label></span>'.
 5579:                               '</td>';
 5580:             }
 5581:             $aliasrows .= '</tr>';
 5582:             $aliasinfo{$dom_in_effect} .= $aliasrows;
 5583:         }
 5584:         if ($aliasinfo{$dom}) {
 5585:             my ($onclick,$wafon,$wafoff,$showtable);
 5586:             $onclick = ' onclick="javascript:toggleWAF();"';
 5587:             $wafoff = ' checked="checked"';
 5588:             $showtable = ' style="display:none";';
 5589:             if ($showdom) {
 5590:                 $wafon = $wafoff;
 5591:                 $wafoff = '';
 5592:                 $showtable = ' style="display:inline;"';
 5593:             }
 5594:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 5595:             $datatable = '<tr'.$css_class.'>'.
 5596:                          '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'<br />'.
 5597:                          '<span class="LC_nobreak">'.&mt('WAF in use?').'&nbsp;<label>'.
 5598:                          '<input type="radio" name="wafproxy_'.$dom.'" value="1"'.$wafon.$onclick.' />'.
 5599:                          &mt('Yes').'</label>'.('&nbsp;'x2).'<label>'.
 5600:                          '<input type="radio" name="wafproxy_'.$dom.'" value="0"'.$wafoff.$onclick.' />'.
 5601:                          &mt('No').'</label></span></td>'.
 5602:                          '<td class="LC_left_item">'.
 5603:                          '<table id="wafproxy_table"'.$showtable.'>'.$aliasinfo{$dom}.
 5604:                          '</table></td></tr>';
 5605:             $itemcount++;
 5606:         }
 5607:         if (keys(%otherdoms)) {
 5608:             foreach my $key (sort(keys(%otherdoms))) {
 5609:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 5610:                 $datatable .= '<tr'.$css_class.'>'.
 5611:                               '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$key.'</b>').'</td>'.
 5612:                               '<td class="LC_left_item"><table>'.$aliasinfo{$key}.
 5613:                               '</table></td></tr>';
 5614:                 $itemcount++;
 5615:             }
 5616:         }
 5617:     } else {
 5618:         my %ip_methods = &remoteip_methods();
 5619:         if ($setdom) {
 5620:             $itemcount ++;
 5621:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 5622:             my ($nowafstyle,$wafstyle,$curr_remotip,$currwafdisplay,$vpndircheck,$vpnaliascheck,
 5623:                 $currwafvpn,$wafrangestyle,$alltossl,$ssltossl);
 5624:             $wafstyle = ' style="display:none;"';
 5625:             $nowafstyle = ' style="display:table-row;"';
 5626:             $currwafdisplay = ' style="display: none"';
 5627:             $wafrangestyle = ' style="display: none"';
 5628:             $curr_remotip = 'n';
 5629:             $ssltossl = ' checked="checked"';
 5630:             if ($showdom) {
 5631:                 $wafstyle = ' style="display:table-row;"';
 5632:                 $nowafstyle =  ' style="display:none;"';
 5633:                 if (keys(%{$values{$dom}})) {
 5634:                     if ($values{$dom}{remoteip} =~ /^[nmh]$/) {
 5635:                         $curr_remotip = $values{$dom}{remoteip};
 5636:                     }
 5637:                     if ($curr_remotip eq 'h') {
 5638:                         $currwafdisplay = ' style="display:table-row"';
 5639:                         $wafrangestyle = ' style="display:inline-block;"';
 5640:                     }
 5641:                     if ($values{$dom}{'sslopt'}) {
 5642:                         $alltossl = ' checked="checked"';
 5643:                         $ssltossl = '';
 5644:                     }
 5645:                 }
 5646:                 if (($values{$dom}{'vpnint'} ne '') || ($values{$dom}{'vpnext'} ne '')) {
 5647:                     $vpndircheck = ' checked="checked"';
 5648:                     $currwafvpn = ' style="display:table-row;"';
 5649:                     $wafrangestyle = ' style="display:inline-block;"';
 5650:                 } else {
 5651:                     $vpnaliascheck = ' checked="checked"';
 5652:                     $currwafvpn = ' style="display:none;"';
 5653:                 }
 5654:             }
 5655:             $datatable .= '<tr'.$css_class.' id="nowafproxyrow_'.$dom.'"'.$wafstyle.'>'.
 5656:                           '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'</td>'.
 5657:                           '<td class="LC_right_item">'.&mt('WAF not in use, nothing to set').'</td>'.
 5658:                           '</tr>'.
 5659:                           '<tr'.$css_class.' id="wafproxyrow_'.$dom.'"'.$wafstyle.'>'.
 5660:                           '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'<br /><br />'.
 5661:                           '<div id="wafproxyranges_'.$dom.'">'.&mt('Format for comma separated IP ranges').':<br />'.
 5662:                           &mt('A.B.C.D/N or A.B.C.D-E.F.G.H').'<br />'.
 5663:                           &mt('Range(s) stored in CIDR notation').'</div></td>'.
 5664:                           '<td class="LC_left_item"><table>'.
 5665:                           '<tr>'.
 5666:                           '<td valign="top">'.$lt{'remoteip'}.':&nbsp;'.
 5667:                           '<select name="wafproxy_remoteip" id="wafproxy_remoteip" onchange="javascript:updateWAF();">';
 5668:             foreach my $option ('m','h','n') {
 5669:                 my $sel;
 5670:                 if ($option eq $curr_remotip) {
 5671:                    $sel = ' selected="selected"';
 5672:                 }
 5673:                 $datatable .= '<option value="'.$option.'"'.$sel.'>'.
 5674:                               $ip_methods{$option}.'</option>';
 5675:             }
 5676:             $datatable .= '</select></td></tr>'."\n".
 5677:                           '<tr id="wafproxy_header"'.$currwafdisplay.'><td>'.
 5678:                           $lt{'ipheader'}.':&nbsp;'.
 5679:                           '<input type="text" value="'.$values{$dom}{'ipheader'}.'" '.
 5680:                           'name="wafproxy_ipheader" />'.
 5681:                           '</td></tr>'."\n".
 5682:                           '<tr id="wafproxy_trust"'.$currwafdisplay.'><td>'.
 5683:                           $lt{'trusted'}.':<br />'.
 5684:                           '<textarea name="wafproxy_trusted" rows="3" cols="80">'.
 5685:                           $values{$dom}{'trusted'}.'</textarea>'.
 5686:                           '</td></tr>'."\n".
 5687:                           '<tr><td><hr /></td></tr>'."\n".
 5688:                           '<tr>'.
 5689:                           '<td valign="top">'.$lt{'vpnaccess'}.':<br /><span class="LC_nobreak">'.
 5690:                           '<label><input type="radio" name="wafproxy_vpnaccess"'.$vpndircheck.' value="1" onclick="javascript:checkWAF();" />'.
 5691:                           $lt{'vpndirect'}.'</label>'.('&nbsp;'x2).
 5692:                           '<label><input type="radio" name="wafproxy_vpnaccess"'.$vpnaliascheck.' value="0" onclick="javascript:checkWAF();" />'.
 5693:                           $lt{'vpnaliased'}.'</label></span></td></tr>';
 5694:             foreach my $item ('vpnint','vpnext') {
 5695:                 $datatable .= '<tr id="wafproxy_show_'.$item.'"'.$currwafvpn.'>'.
 5696:                               '<td valign="top">'.$lt{$item}.':<br />'.
 5697:                               '<textarea name="wafproxy_'.$item.'" rows="3" cols="80">'.
 5698:                               $values{$dom}{$item}.'</textarea>'.
 5699:                               '</td></tr>'."\n";
 5700:             }
 5701:             $datatable .= '<tr><td><hr /></td></tr>'."\n".
 5702:                           '<tr>'.
 5703:                           '<td valign="top">'.$lt{'sslopt'}.':<br /><span class="LC_nobreak">'.
 5704:                           '<label><input type="radio" name="wafproxy_sslopt"'.$alltossl.' value="1" />'.
 5705:                           $lt{'alltossl'}.'</label>'.('&nbsp;'x2).
 5706:                           '<label><input type="radio" name="wafproxy_sslopt"'.$ssltossl.' value="0" />'.
 5707:                           $lt{'ssltossl'}.'</label></span></td></tr>'."\n".
 5708:                           '</table></td></tr>';
 5709:         }
 5710:         if (keys(%otherdoms)) {
 5711:             foreach my $domain (sort(keys(%otherdoms))) {
 5712:                 $itemcount ++;
 5713:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 5714:                 $datatable .= '<tr'.$css_class.'>'.
 5715:                               '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$domain.'</b>').'</td>'.
 5716:                               '<td class="LC_left_item"><table>';
 5717:                 foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
 5718:                     my $showval = &mt('None');
 5719:                     if ($item eq 'ssl') {
 5720:                         $showval = $lt{'ssltossl'};
 5721:                     }
 5722:                     if ($values{$domain}{$item}) {
 5723:                         $showval = $values{$domain}{$item};
 5724:                         if ($item eq 'ssl') {
 5725:                             $showval = $lt{'alltossl'};
 5726:                         } elsif ($item eq 'remoteip') {
 5727:                             $showval = $ip_methods{$values{$domain}{$item}};
 5728:                         }
 5729:                     }
 5730:                     $datatable .= '<tr>'.
 5731:                                   '<td>'.$lt{$item}.':&nbsp;'.$showval.'</td></tr>';
 5732:                 }
 5733:                 $datatable .= '</table></td></tr>';
 5734:             }
 5735:         }
 5736:     }
 5737:     $$rowtotal += $itemcount;
 5738:     return $datatable;
 5739: }
 5740: 
 5741: sub wafproxy_titles {
 5742:     return &Apache::lonlocal::texthash(
 5743:                remoteip   => "Method for determining user's IP",
 5744:                ipheader   => 'Request header containing remote IP',
 5745:                trusted    => 'Trusted IP range(s)',
 5746:                vpnaccess  => 'Access from institutional VPN',
 5747:                vpndirect  => 'via regular hostname (no WAF)',
 5748:                vpnaliased => 'via aliased hostname (WAF)',
 5749:                vpnint     => 'Internal IP Range(s) for VPN sessions',
 5750:                vpnext     => 'IP Range(s) for backend WAF connections',
 5751:                sslopt     => 'Forwarding http/https',
 5752:                alltossl   => 'WAF forwards both http and https requests to https',
 5753:                ssltossl   => 'WAF forwards http requests to http and https to https',
 5754:            );
 5755: }
 5756: 
 5757: sub remoteip_methods {
 5758:     return &Apache::lonlocal::texthash(
 5759:               m => 'Use Apache mod_remoteip',
 5760:               h => 'Use headers parsed by LON-CAPA',
 5761:               n => 'Not in use',
 5762:            );
 5763: }
 5764: 
 5765: sub print_usersessions {
 5766:     my ($position,$dom,$settings,$rowtotal) = @_;
 5767:     my ($css_class,$datatable,%checked,%choices);
 5768:     my (%by_ip,%by_location,@intdoms);
 5769:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location);
 5770: 
 5771:     my @alldoms = &Apache::lonnet::all_domains();
 5772:     my %serverhomes = %Apache::lonnet::serverhomeIDs;
 5773:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 5774:     my %altids = &id_for_thisdom(%servers);
 5775:     my $itemcount = 1;
 5776:     if ($position eq 'top') {
 5777:         if (keys(%serverhomes) > 1) {
 5778:             my %spareid = &current_offloads_to($dom,$settings,\%servers);
 5779:             my ($curroffloadnow,$curroffloadoth);
 5780:             if (ref($settings) eq 'HASH') {
 5781:                 if (ref($settings->{'offloadnow'}) eq 'HASH') {
 5782:                     $curroffloadnow = $settings->{'offloadnow'};
 5783:                 }
 5784:                 if (ref($settings->{'offloadoth'}) eq 'HASH') {
 5785:                     $curroffloadoth = $settings->{'offloadoth'};
 5786:                 }
 5787:             }
 5788:             my $other_insts = scalar(keys(%by_location));
 5789:             $datatable .= &spares_row($dom,\%servers,\%spareid,\%serverhomes,\%altids,
 5790:                                       $other_insts,$curroffloadnow,$curroffloadoth,$rowtotal);
 5791:         } else {
 5792:             $datatable .= '<tr'.$css_class.'><td colspan="2">'.
 5793:                           &mt('Nothing to set here, as the cluster to which this domain belongs only contains one server.');
 5794:         }
 5795:     } else {
 5796:         if (keys(%by_location) == 0) {
 5797:             $datatable .= '<tr'.$css_class.'><td colspan="2">'.
 5798:                           &mt('Nothing to set here, as the cluster to which this domain belongs only contains one institution.');
 5799:         } else {
 5800:             my %lt = &usersession_titles();
 5801:             my $numinrow = 5;
 5802:             my $prefix;
 5803:             my @types;
 5804:             if ($position eq 'bottom') {
 5805:                 $prefix = 'remote';
 5806:                 @types = ('version','excludedomain','includedomain');
 5807:             } else {
 5808:                 $prefix = 'hosted';
 5809:                 @types = ('excludedomain','includedomain');
 5810:             }
 5811:             my (%current,%checkedon,%checkedoff);
 5812:             my @lcversions = &Apache::lonnet::all_loncaparevs();
 5813:             my @locations = sort(keys(%by_location));
 5814:             foreach my $type (@types) {
 5815:                 $checkedon{$type} = '';
 5816:                 $checkedoff{$type} = ' checked="checked"';
 5817:             }
 5818:             if (ref($settings) eq 'HASH') {
 5819:                 if (ref($settings->{$prefix}) eq 'HASH') {
 5820:                     foreach my $key (keys(%{$settings->{$prefix}})) {
 5821:                         $current{$key} = $settings->{$prefix}{$key};
 5822:                         if ($key eq 'version') {
 5823:                             if ($current{$key} ne '') {
 5824:                                 $checkedon{$key} = ' checked="checked"';
 5825:                                 $checkedoff{$key} = '';
 5826:                             }
 5827:                         } elsif (ref($current{$key}) eq 'ARRAY') {
 5828:                             $checkedon{$key} = ' checked="checked"';
 5829:                             $checkedoff{$key} = '';
 5830:                         }
 5831:                     }
 5832:                 }
 5833:             }
 5834:             foreach my $type (@types) {
 5835:                 next if ($type ne 'version' && !@locations);
 5836:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 5837:                 $datatable .= '<tr'.$css_class.'>
 5838:                                <td><span class="LC_nobreak">'.$lt{$type}.'</span><br />
 5839:                                <span class="LC_nobreak">&nbsp;
 5840:                                <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedoff{$type}.' value="0" />'.&mt('Not in use').'</label>&nbsp;
 5841:                                <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedon{$type}.' value="1" />'.&mt('In use').'</label></span></td><td>';
 5842:                 if ($type eq 'version') {
 5843:                     my $selector = '<select name="'.$prefix.'_version">';
 5844:                     foreach my $version (@lcversions) {
 5845:                         my $selected = '';
 5846:                         if ($current{'version'} eq $version) {
 5847:                             $selected = ' selected="selected"';
 5848:                         }
 5849:                         $selector .= ' <option value="'.$version.'"'.
 5850:                                      $selected.'>'.$version.'</option>';
 5851:                     }
 5852:                     $selector .= '</select> ';
 5853:                     $datatable .= &mt('remote server must be version: [_1] or later',$selector);
 5854:                 } else {
 5855:                     $datatable.= '<div><input type="button" value="'.&mt('check all').'" '.
 5856:                                  'onclick="javascript:checkAll(document.display.'.$prefix.'_'.$type.')"'.
 5857:                                  ' />'.('&nbsp;'x2).
 5858:                                  '<input type="button" value="'.&mt('uncheck all').'" '.
 5859:                                  'onclick="javascript:uncheckAll(document.display.'.$prefix.'_'.$type.')" />'.
 5860:                                  "\n".
 5861:                                  '</div><div><table>';
 5862:                     my $rem;
 5863:                     for (my $i=0; $i<@locations; $i++) {
 5864:                         my ($showloc,$value,$checkedtype);
 5865:                         if (ref($by_location{$locations[$i]}) eq 'ARRAY') {
 5866:                             my $ip = $by_location{$locations[$i]}->[0];
 5867:                             if (ref($by_ip{$ip}) eq 'ARRAY') {
 5868:                                  $value = join(':',@{$by_ip{$ip}});
 5869:                                 $showloc = join(', ',@{$by_ip{$ip}});
 5870:                                 if (ref($current{$type}) eq 'ARRAY') {
 5871:                                     foreach my $loc (@{$by_ip{$ip}}) {  
 5872:                                         if (grep(/^\Q$loc\E$/,@{$current{$type}})) {
 5873:                                             $checkedtype = ' checked="checked"';
 5874:                                             last;
 5875:                                         }
 5876:                                     }
 5877:                                 }
 5878:                             }
 5879:                         }
 5880:                         $rem = $i%($numinrow);
 5881:                         if ($rem == 0) {
 5882:                             if ($i > 0) {
 5883:                                 $datatable .= '</tr>';
 5884:                             }
 5885:                             $datatable .= '<tr>';
 5886:                         }
 5887:                         $datatable .= '<td class="LC_left_item">'.
 5888:                                       '<span class="LC_nobreak"><label>'.
 5889:                                       '<input type="checkbox" name="'.$prefix.'_'.$type.
 5890:                                       '" value="'.$value.'"'.$checkedtype.' />'.$showloc.
 5891:                                       '</label></span></td>';
 5892:                     }
 5893:                     $rem = @locations%($numinrow);
 5894:                     my $colsleft = $numinrow - $rem;
 5895:                     if ($colsleft > 1 ) {
 5896:                         $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 5897:                                       '&nbsp;</td>';
 5898:                     } elsif ($colsleft == 1) {
 5899:                         $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 5900:                     }
 5901:                     $datatable .= '</tr></table>';
 5902:                 }
 5903:                 $datatable .= '</td></tr>';
 5904:                 $itemcount ++;
 5905:             }
 5906:         }
 5907:     }
 5908:     $$rowtotal += $itemcount;
 5909:     return $datatable;
 5910: }
 5911: 
 5912: sub build_location_hashes {
 5913:     my ($intdoms,$by_ip,$by_location) = @_;
 5914:     return unless((ref($intdoms) eq 'ARRAY') && (ref($by_ip) eq 'HASH') &&
 5915:                   (ref($by_location) eq 'HASH')); 
 5916:     my %iphost = &Apache::lonnet::get_iphost();
 5917:     my $primary_id = &Apache::lonnet::domain($env{'request.role.domain'},'primary');
 5918:     my $primary_ip = &Apache::lonnet::get_host_ip($primary_id);
 5919:     if (ref($iphost{$primary_ip}) eq 'ARRAY') {
 5920:         foreach my $id (@{$iphost{$primary_ip}}) {
 5921:             my $intdom = &Apache::lonnet::internet_dom($id);
 5922:             unless(grep(/^\Q$intdom\E$/,@{$intdoms})) {
 5923:                 push(@{$intdoms},$intdom);
 5924:             }
 5925:         }
 5926:     }
 5927:     foreach my $ip (keys(%iphost)) {
 5928:         if (ref($iphost{$ip}) eq 'ARRAY') {
 5929:             foreach my $id (@{$iphost{$ip}}) {
 5930:                 my $location = &Apache::lonnet::internet_dom($id);
 5931:                 if ($location) {
 5932:                     next if (grep(/^\Q$location\E$/,@{$intdoms}));
 5933:                     if (ref($by_ip->{$ip}) eq 'ARRAY') {
 5934:                         unless(grep(/^\Q$location\E$/,@{$by_ip->{$ip}})) {
 5935:                             push(@{$by_ip->{$ip}},$location);
 5936:                         }
 5937:                     } else {
 5938:                         $by_ip->{$ip} = [$location];
 5939:                     }
 5940:                 }
 5941:             }
 5942:         }
 5943:     }
 5944:     foreach my $ip (sort(keys(%{$by_ip}))) {
 5945:         if (ref($by_ip->{$ip}) eq 'ARRAY') {
 5946:             @{$by_ip->{$ip}} = sort(@{$by_ip->{$ip}});
 5947:             my $first = $by_ip->{$ip}->[0];
 5948:             if (ref($by_location->{$first}) eq 'ARRAY') {
 5949:                 unless (grep(/^\Q$ip\E$/,@{$by_location->{$first}})) {
 5950:                     push(@{$by_location->{$first}},$ip);
 5951:                 }
 5952:             } else {
 5953:                 $by_location->{$first} = [$ip];
 5954:             }
 5955:         }
 5956:     }
 5957:     return;
 5958: }
 5959: 
 5960: sub current_offloads_to {
 5961:     my ($dom,$settings,$servers) = @_;
 5962:     my (%spareid,%otherdomconfigs);
 5963:     if (ref($servers) eq 'HASH') {
 5964:         foreach my $lonhost (sort(keys(%{$servers}))) {
 5965:             my $gotspares;
 5966:             if (ref($settings) eq 'HASH') {
 5967:                 if (ref($settings->{'spares'}) eq 'HASH') {
 5968:                     if (ref($settings->{'spares'}{$lonhost}) eq 'HASH') {
 5969:                         $spareid{$lonhost}{'primary'} = $settings->{'spares'}{$lonhost}{'primary'};
 5970:                         $spareid{$lonhost}{'default'} = $settings->{'spares'}{$lonhost}{'default'};
 5971:                         $gotspares = 1;
 5972:                     }
 5973:                 }
 5974:             }
 5975:             unless ($gotspares) {
 5976:                 my $gotspares;
 5977:                 my $serverhomeID =
 5978:                     &Apache::lonnet::get_server_homeID($servers->{$lonhost});
 5979:                 my $serverhomedom =
 5980:                     &Apache::lonnet::host_domain($serverhomeID);
 5981:                 if ($serverhomedom ne $dom) {
 5982:                     if (ref($otherdomconfigs{$serverhomedom} eq 'HASH')) {
 5983:                         if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 5984:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 5985:                                 $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 5986:                                 $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 5987:                                 $gotspares = 1;
 5988:                             }
 5989:                         }
 5990:                     } else {
 5991:                         $otherdomconfigs{$serverhomedom} =
 5992:                             &Apache::lonnet::get_dom('configuration',['usersessions'],$serverhomedom);
 5993:                         if (ref($otherdomconfigs{$serverhomedom}) eq 'HASH') {
 5994:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 5995:                                 if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 5996:                                     if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{$lonhost}) eq 'HASH') {
 5997:                                         $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 5998:                                         $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 5999:                                         $gotspares = 1;
 6000:                                     }
 6001:                                 }
 6002:                             }
 6003:                         }
 6004:                     }
 6005:                 }
 6006:             }
 6007:             unless ($gotspares) {
 6008:                 if ($lonhost eq $Apache::lonnet::perlvar{'lonHostID'}) {
 6009:                     $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 6010:                     $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 6011:                } else {
 6012:                     my $server_hostname = &Apache::lonnet::hostname($lonhost);
 6013:                     my $server_homeID = &Apache::lonnet::get_server_homeID($server_hostname);
 6014:                     if ($server_homeID eq $Apache::lonnet::perlvar{'lonHostID'}) {
 6015:                         $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 6016:                         $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 6017:                     } else {
 6018:                         my %what = (
 6019:                              spareid => 1,
 6020:                         );
 6021:                         my ($result,$returnhash) = 
 6022:                             &Apache::lonnet::get_remote_globals($lonhost,\%what);
 6023:                         if ($result eq 'ok') { 
 6024:                             if (ref($returnhash) eq 'HASH') {
 6025:                                 if (ref($returnhash->{'spareid'}) eq 'HASH') {
 6026:                                     $spareid{$lonhost}{'primary'} = $returnhash->{'spareid'}->{'primary'};
 6027:                                     $spareid{$lonhost}{'default'} = $returnhash->{'spareid'}->{'default'};
 6028:                                 }
 6029:                             }
 6030:                         }
 6031:                     }
 6032:                 }
 6033:             }
 6034:         }
 6035:     }
 6036:     return %spareid;
 6037: }
 6038: 
 6039: sub spares_row {
 6040:     my ($dom,$servers,$spareid,$serverhomes,$altids,$other_insts,
 6041:         $curroffloadnow,$curroffloadoth,$rowtotal) = @_;
 6042:     my $css_class;
 6043:     my $numinrow = 4;
 6044:     my $itemcount = 1;
 6045:     my $datatable;
 6046:     my %typetitles = &sparestype_titles();
 6047:     if ((ref($servers) eq 'HASH') && (ref($spareid) eq 'HASH') && (ref($altids) eq 'HASH')) {
 6048:         foreach my $server (sort(keys(%{$servers}))) {
 6049:             my $serverhome = &Apache::lonnet::get_server_homeID($servers->{$server});
 6050:             my ($othercontrol,$serverdom);
 6051:             if ($serverhome ne $server) {
 6052:                 $serverdom = &Apache::lonnet::host_domain($serverhome);
 6053:                 $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 6054:             } else {
 6055:                 $serverdom = &Apache::lonnet::host_domain($server);
 6056:                 if ($serverdom ne $dom) {
 6057:                     $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 6058:                 }
 6059:             }
 6060:             next unless (ref($spareid->{$server}) eq 'HASH');
 6061:             my ($checkednow,$checkedoth);
 6062:             if (ref($curroffloadnow) eq 'HASH') {
 6063:                 if ($curroffloadnow->{$server}) {
 6064:                     $checkednow = ' checked="checked"';
 6065:                 }
 6066:             }
 6067:             if (ref($curroffloadoth) eq 'HASH') {
 6068:                 if ($curroffloadoth->{$server}) {
 6069:                     $checkedoth = ' checked="checked"';
 6070:                 }
 6071:             }
 6072:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6073:             $datatable .= '<tr'.$css_class.'>
 6074:                            <td rowspan="2">
 6075:                             <span class="LC_nobreak">'.
 6076:                           &mt('[_1] when busy, offloads to:'
 6077:                               ,'<b>'.$server.'</b>').'</span><br />'.
 6078:                           '<span class="LC_nobreak">'."\n".
 6079:                           '<label><input type="checkbox" name="offloadnow" value="'.$server.'"'.$checkednow.' />'.
 6080:                           '&nbsp;'.&mt('Switch any active user on next access').'</label></span>'.
 6081:                           "\n";
 6082:             if ($other_insts) {
 6083:                 $datatable .= '<br />'.
 6084:                               '<span class="LC_nobreak">'."\n".
 6085:                           '<label><input type="checkbox" name="offloadoth" value="'.$server.'"'.$checkedoth.' />'.
 6086:                           '&nbsp;'.&mt('Switch other institutions on next access').'</label></span>'.
 6087:                           "\n";
 6088:             }
 6089:             my (%current,%canselect);
 6090:             my @choices = 
 6091:                 &possible_newspares($server,$spareid->{$server},$serverhomes,$altids);
 6092:             foreach my $type ('primary','default') {
 6093:                 if (ref($spareid->{$server}) eq 'HASH') {
 6094:                     if (ref($spareid->{$server}{$type}) eq 'ARRAY') {
 6095:                         my @spares = @{$spareid->{$server}{$type}};
 6096:                         if (@spares > 0) {
 6097:                             if ($othercontrol) {
 6098:                                 $current{$type} = join(', ',@spares);
 6099:                             } else {
 6100:                                 $current{$type} .= '<table>';
 6101:                                 my $numspares = scalar(@spares);
 6102:                                 for (my $i=0;  $i<@spares; $i++) {
 6103:                                     my $rem = $i%($numinrow);
 6104:                                     if ($rem == 0) {
 6105:                                         if ($i > 0) {
 6106:                                             $current{$type} .= '</tr>';
 6107:                                         }
 6108:                                         $current{$type} .= '<tr>';
 6109:                                     }
 6110:                                     $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;'.
 6111:                                                        $spareid->{$server}{$type}[$i].
 6112:                                                        '</label></td>'."\n";
 6113:                                 }
 6114:                                 my $rem = @spares%($numinrow);
 6115:                                 my $colsleft = $numinrow - $rem;
 6116:                                 if ($colsleft > 1 ) {
 6117:                                     $current{$type} .= '<td colspan="'.$colsleft.
 6118:                                                        '" class="LC_left_item">'.
 6119:                                                        '&nbsp;</td>';
 6120:                                 } elsif ($colsleft == 1) {
 6121:                                     $current{$type} .= '<td class="LC_left_item">&nbsp;</td>'."\n";
 6122:                                 }
 6123:                                 $current{$type} .= '</tr></table>';
 6124:                             }
 6125:                         }
 6126:                     }
 6127:                     if ($current{$type} eq '') {
 6128:                         $current{$type} = &mt('None specified');
 6129:                     }
 6130:                     if ($othercontrol) {
 6131:                         if ($type eq 'primary') {
 6132:                             $canselect{$type} = $othercontrol;
 6133:                         }
 6134:                     } else {
 6135:                         $canselect{$type} = 
 6136:                             &mt('Add new [_1]'.$type.'[_2]:','<i>','</i>').'&nbsp;'.
 6137:                             '<select name="newspare_'.$type.'_'.$server.'" '.
 6138:                             'id="newspare_'.$type.'_'.$server.'" onchange="checkNewSpares('."'$server','$type'".');">'."\n".
 6139:                             '<option value="" selected ="selected">'.&mt('Select').'</option>'."\n";
 6140:                         if (@choices > 0) {
 6141:                             foreach my $lonhost (@choices) {
 6142:                                 $canselect{$type} .= '<option value="'.$lonhost.'">'.$lonhost.'</option>'."\n";
 6143:                             }
 6144:                         }
 6145:                         $canselect{$type} .= '</select>'."\n";
 6146:                     }
 6147:                 } else {
 6148:                     $current{$type} = &mt('Could not be determined');
 6149:                     if ($type eq 'primary') {
 6150:                         $canselect{$type} =  $othercontrol;
 6151:                     }
 6152:                 }
 6153:                 if ($type eq 'default') {
 6154:                     $datatable .= '<tr'.$css_class.'>';
 6155:                 }
 6156:                 $datatable .= '<td><i>'.$typetitles{$type}.'</i></td>'."\n".
 6157:                               '<td>'.$current{$type}.'</td>'."\n".
 6158:                               '<td>'.$canselect{$type}.'</td></tr>'."\n";
 6159:             }
 6160:             $itemcount ++;
 6161:         }
 6162:     }
 6163:     $$rowtotal += $itemcount;
 6164:     return $datatable;
 6165: }
 6166: 
 6167: sub possible_newspares {
 6168:     my ($server,$currspares,$serverhomes,$altids) = @_;
 6169:     my $serverhostname = &Apache::lonnet::hostname($server);
 6170:     my %excluded;
 6171:     if ($serverhostname ne '') {
 6172:         %excluded = (
 6173:                        $serverhostname => 1,
 6174:                     );
 6175:     }
 6176:     if (ref($currspares) eq 'HASH') {
 6177:         foreach my $type (keys(%{$currspares})) {
 6178:             if (ref($currspares->{$type}) eq 'ARRAY') {
 6179:                 if (@{$currspares->{$type}} > 0) {
 6180:                     foreach my $curr (@{$currspares->{$type}}) {
 6181:                         my $hostname = &Apache::lonnet::hostname($curr);
 6182:                         $excluded{$hostname} = 1;
 6183:                     }
 6184:                 }
 6185:             }
 6186:         }
 6187:     }
 6188:     my @choices;
 6189:     if ((ref($serverhomes) eq 'HASH') && (ref($altids) eq 'HASH')) {
 6190:         if (keys(%{$serverhomes}) > 1) {
 6191:             foreach my $name (sort(keys(%{$serverhomes}))) {
 6192:                 unless ($excluded{$name}) {
 6193:                     if (exists($altids->{$serverhomes->{$name}})) {
 6194:                         push(@choices,$altids->{$serverhomes->{$name}});
 6195:                     } else {
 6196:                         push(@choices,$serverhomes->{$name});
 6197:                     }
 6198:                 }
 6199:             }
 6200:         }
 6201:     }
 6202:     return sort(@choices);
 6203: }
 6204: 
 6205: sub print_loadbalancing {
 6206:     my ($dom,$settings,$rowtotal) = @_;
 6207:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
 6208:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
 6209:     my $numinrow = 1;
 6210:     my $datatable;
 6211:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 6212:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
 6213:     if (ref($settings) eq 'HASH') {
 6214:         %existing = %{$settings};
 6215:     }
 6216:     if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
 6217:         &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
 6218:                                   \%currtargets,\%currrules,\%currcookies);
 6219:     } else {
 6220:         return;
 6221:     }
 6222:     my ($othertitle,$usertypes,$types) =
 6223:         &Apache::loncommon::sorted_inst_types($dom);
 6224:     my $rownum = 8;
 6225:     if (ref($types) eq 'ARRAY') {
 6226:         $rownum += scalar(@{$types});
 6227:     }
 6228:     my @css_class = ('LC_odd_row','LC_even_row');
 6229:     my $balnum = 0;
 6230:     my $islast;
 6231:     my (@toshow,$disabledtext);
 6232:     if (keys(%currbalancer) > 0) {
 6233:         @toshow = sort(keys(%currbalancer));
 6234:         if (scalar(@toshow) < scalar(keys(%servers)) + 1) {
 6235:             push(@toshow,'');
 6236:         }
 6237:     } else {
 6238:         @toshow = ('');
 6239:         $disabledtext = &mt('No existing load balancer');
 6240:     }
 6241:     foreach my $lonhost (@toshow) {
 6242:         if ($balnum == scalar(@toshow)-1) {
 6243:             $islast = 1;
 6244:         } else {
 6245:             $islast = 0;
 6246:         }
 6247:         my $cssidx = $balnum%2;
 6248:         my $targets_div_style = 'display: none';
 6249:         my $disabled_div_style = 'display: block';
 6250:         my $homedom_div_style = 'display: none';
 6251:         $datatable .= '<tr class="'.$css_class[$cssidx].'">'.
 6252:                       '<td rowspan="'.$rownum.'" valign="top">'.
 6253:                       '<p>';
 6254:         if ($lonhost eq '') {
 6255:             $datatable .= '<span class="LC_nobreak">';
 6256:             if (keys(%currbalancer) > 0) {
 6257:                 $datatable .= &mt('Add balancer:');
 6258:             } else {
 6259:                 $datatable .= &mt('Enable balancer:');
 6260:             }
 6261:             $datatable .= '&nbsp;'.
 6262:                           '<select name="loadbalancing_lonhost_'.$balnum.'"'.
 6263:                           ' id="loadbalancing_lonhost_'.$balnum.'"'.
 6264:                           ' onchange="toggleTargets('."'$balnum'".');">'."\n".
 6265:                           '<option value="" selected="selected">'.&mt('None').
 6266:                           '</option>'."\n";
 6267:             foreach my $server (sort(keys(%servers))) {
 6268:                 next if ($currbalancer{$server});
 6269:                 $datatable .= '<option value="'.$server.'">'.$server.'</option>'."\n";
 6270:             }
 6271:             $datatable .=
 6272:                 '</select>'."\n".
 6273:                 '<input type="hidden" name="loadbalancing_prevlonhost_'.$balnum.'" id="loadbalancing_prevlonhost_'.$balnum.'" value="" />&nbsp;</span>'."\n";
 6274:         } else {
 6275:             $datatable .= '<i>'.$lonhost.'</i><br /><span class="LC_nobreak">'.
 6276:                           '<label><input type="checkbox" name="loadbalancing_delete" value="'.$balnum.'" id="loadbalancing_delete_'.$balnum.'" onclick="javascript:balancerDeleteChange('."'$balnum'".');" />&nbsp;'.
 6277:                            &mt('Stop balancing').'</label>'.
 6278:                            '<input type="hidden" name="loadbalancing_lonhost_'.$balnum.'" value="'.$lonhost.'" id="loadbalancing_lonhost_'.$balnum.'" /></span>';
 6279:             $targets_div_style = 'display: block';
 6280:             $disabled_div_style = 'display: none';
 6281:             if ($dom eq &Apache::lonnet::host_domain($lonhost)) {
 6282:                 $homedom_div_style = 'display: block';
 6283:             }
 6284:         }
 6285:         $datatable .= '</p></td><td rowspan="'.$rownum.'" valign="top">'.
 6286:                   '<div id="loadbalancing_disabled_'.$balnum.'" style="'.
 6287:                   $disabled_div_style.'">'.$disabledtext.'</div>'."\n".
 6288:                   '<div id="loadbalancing_targets_'.$balnum.'" style="'.$targets_div_style.'">'.&mt('Offloads to:').'<br />';
 6289:         my ($numspares,@spares) = &count_servers($lonhost,%servers);
 6290:         my @sparestypes = ('primary','default');
 6291:         my %typetitles = &sparestype_titles();
 6292:         my %hostherechecked = (
 6293:                                   no => ' checked="checked"',
 6294:                               );
 6295:         my %balcookiechecked = (
 6296:                                   no => ' checked="checked"',
 6297:                                );
 6298:         foreach my $sparetype (@sparestypes) {
 6299:             my $targettable;
 6300:             for (my $i=0; $i<$numspares; $i++) {
 6301:                 my $checked;
 6302:                 if (ref($currtargets{$lonhost}) eq 'HASH') {
 6303:                     if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 6304:                         if (grep(/^\Q$spares[$i]\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 6305:                             $checked = ' checked="checked"';
 6306:                         }
 6307:                     }
 6308:                 }
 6309:                 my ($chkboxval,$disabled);
 6310:                 if (($lonhost ne '') && (exists($servers{$lonhost}))) {
 6311:                     $chkboxval = $spares[$i];
 6312:                 }
 6313:                 if (exists($currbalancer{$spares[$i]})) {
 6314:                     $disabled = ' disabled="disabled"';
 6315:                 }
 6316:                 $targettable .=
 6317:                     '<td><span class="LC_nobreak"><label>'.
 6318:                     '<input type="checkbox" name="loadbalancing_target_'.$balnum.'_'.$sparetype.'"'.
 6319:                     $checked.$disabled.' value="'.$chkboxval.'" id="loadbalancing_target_'.$balnum.'_'.$sparetype.'_'.$i.'" onclick="checkOffloads('."this,'$balnum','$sparetype'".');" /><span id="loadbalancing_targettxt_'.$balnum.'_'.$sparetype.'_'.$i.'">&nbsp;'.$chkboxval.
 6320:                     '</span></label></span></td>';
 6321:                 my $rem = $i%($numinrow);
 6322:                 if ($rem == 0) {
 6323:                     if (($i > 0) && ($i < $numspares-1)) {
 6324:                         $targettable .= '</tr>';
 6325:                     }
 6326:                     if ($i < $numspares-1) {
 6327:                         $targettable .= '<tr>';
 6328:                     }
 6329:                 }
 6330:             }
 6331:             if ($targettable ne '') {
 6332:                 my $rem = $numspares%($numinrow);
 6333:                 my $colsleft = $numinrow - $rem;
 6334:                 if ($colsleft > 1 ) {
 6335:                     $targettable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 6336:                                     '&nbsp;</td>';
 6337:                 } elsif ($colsleft == 1) {
 6338:                     $targettable .= '<td class="LC_left_item">&nbsp;</td>';
 6339:                 }
 6340:                 $datatable .=  '<i>'.$typetitles{$sparetype}.'</i><br />'.
 6341:                                '<table><tr>'.$targettable.'</tr></table><br />';
 6342:             }
 6343:             $hostherechecked{$sparetype} = '';
 6344:             if (ref($currtargets{$lonhost}) eq 'HASH') {
 6345:                 if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 6346:                     if (grep(/^\Q$lonhost\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 6347:                         $hostherechecked{$sparetype} = ' checked="checked"';
 6348:                         $hostherechecked{'no'} = '';
 6349:                     }
 6350:                 }
 6351:             }
 6352:         }
 6353:         if ($currcookies{$lonhost}) {
 6354:             %balcookiechecked = (
 6355:                                     yes => ' checked="checked"',
 6356:                                 );
 6357:         }
 6358:         $datatable .= &mt('Hosting on balancer itself').'<br />'.
 6359:                       '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" value="no"'.
 6360:                       $hostherechecked{'no'}.' />'.&mt('No').'</label><br />';
 6361:         foreach my $sparetype (@sparestypes) {
 6362:             $datatable .= '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" '.
 6363:                           'value="'.$sparetype.'"'.$hostherechecked{$sparetype}.' /><i>'.$typetitles{$sparetype}.
 6364:                           '</i></label><br />';
 6365:         }
 6366:         $datatable .= &mt('Use balancer cookie').'<br />'.
 6367:                       '<label><input type="radio" name="loadbalancing_cookie_'.$balnum.'" value="1"'.
 6368:                       $balcookiechecked{'yes'}.' />'.&mt('Yes').'</label><br />'.
 6369:                       '<label><input type="radio" name="loadbalancing_cookie_'.$balnum.'" value="0"'.
 6370:                       $balcookiechecked{'no'}.' />'.&mt('No').'</label><br />'.
 6371:                       '</div></td></tr>'.
 6372:                       &loadbalancing_rules($dom,$intdom,$currrules{$lonhost},
 6373:                                            $othertitle,$usertypes,$types,\%servers,
 6374:                                            \%currbalancer,$lonhost,
 6375:                                            $targets_div_style,$homedom_div_style,
 6376:                                            $css_class[$cssidx],$balnum,$islast);
 6377:         $$rowtotal += $rownum;
 6378:         $balnum ++;
 6379:     }
 6380:     $datatable .= '<input type="hidden" name="loadbalancing_total" id="loadbalancing_total" value="'.$balnum.'" />';
 6381:     return $datatable;
 6382: }
 6383: 
 6384: sub get_loadbalancers_config {
 6385:     my ($servers,$existing,$currbalancer,$currtargets,$currrules,$currcookies) = @_;
 6386:     return unless ((ref($servers) eq 'HASH') &&
 6387:                    (ref($existing) eq 'HASH') && (ref($currbalancer) eq 'HASH') &&
 6388:                    (ref($currtargets) eq 'HASH') && (ref($currrules) eq 'HASH') &&
 6389:                    (ref($currcookies) eq 'HASH'));
 6390:     if (keys(%{$existing}) > 0) {
 6391:         my $oldlonhost;
 6392:         foreach my $key (sort(keys(%{$existing}))) {
 6393:             if ($key eq 'lonhost') {
 6394:                 $oldlonhost = $existing->{'lonhost'};
 6395:                 $currbalancer->{$oldlonhost} = 1;
 6396:             } elsif ($key eq 'targets') {
 6397:                 if ($oldlonhost) {
 6398:                     $currtargets->{$oldlonhost} = $existing->{'targets'};
 6399:                 }
 6400:             } elsif ($key eq 'rules') {
 6401:                 if ($oldlonhost) {
 6402:                     $currrules->{$oldlonhost} = $existing->{'rules'};
 6403:                 }
 6404:             } elsif (ref($existing->{$key}) eq 'HASH') {
 6405:                 $currbalancer->{$key} = 1;
 6406:                 $currtargets->{$key} = $existing->{$key}{'targets'};
 6407:                 $currrules->{$key} = $existing->{$key}{'rules'};
 6408:                 if ($existing->{$key}{'cookie'}) {
 6409:                     $currcookies->{$key} = 1;
 6410:                 }
 6411:             }
 6412:         }
 6413:     } else {
 6414:         my ($balancerref,$targetsref) =
 6415:                 &Apache::lonnet::get_lonbalancer_config($servers);
 6416:         if ((ref($balancerref) eq 'HASH') && (ref($targetsref) eq 'HASH')) {
 6417:             foreach my $server (sort(keys(%{$balancerref}))) {
 6418:                 $currbalancer->{$server} = 1;
 6419:                 $currtargets->{$server} = $targetsref->{$server};
 6420:             }
 6421:         }
 6422:     }
 6423:     return;
 6424: }
 6425: 
 6426: sub loadbalancing_rules {
 6427:     my ($dom,$intdom,$currrules,$othertitle,$usertypes,$types,$servers,
 6428:         $currbalancer,$lonhost,$targets_div_style,$homedom_div_style,
 6429:         $css_class,$balnum,$islast) = @_;
 6430:     my $output;
 6431:     my $num = 0;
 6432:     my ($alltypes,$othertypes,$titles) =
 6433:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
 6434:     if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH'))  {
 6435:         foreach my $type (@{$alltypes}) {
 6436:             $num ++;
 6437:             my $current;
 6438:             if (ref($currrules) eq 'HASH') {
 6439:                 $current = $currrules->{$type};
 6440:             }
 6441:             if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 6442:                 if ($dom ne &Apache::lonnet::host_domain($lonhost)) {
 6443:                     $current = '';
 6444:                 }
 6445:             }
 6446:             $output .= &loadbalance_rule_row($type,$titles->{$type},$current,
 6447:                                              $servers,$currbalancer,$lonhost,$dom,
 6448:                                              $targets_div_style,$homedom_div_style,
 6449:                                              $css_class,$balnum,$num,$islast);
 6450:         }
 6451:     }
 6452:     return $output;
 6453: }
 6454: 
 6455: sub loadbalancing_titles {
 6456:     my ($dom,$intdom,$usertypes,$types) = @_;
 6457:     my %othertypes = (
 6458:            '_LC_adv'         => &mt('Advanced users from [_1]',$dom),
 6459:            '_LC_author'      => &mt('Users from [_1] with author role',$dom),
 6460:            '_LC_internetdom' => &mt('Users not from [_1], but from [_2]',$dom,$intdom),
 6461:            '_LC_external'    => &mt('Users not from [_1]',$intdom),
 6462:            '_LC_ipchangesso' => &mt('SSO users from [_1], with IP mismatch',$dom),
 6463:            '_LC_ipchange'    => &mt('Non-SSO users with IP mismatch'),
 6464:                      );
 6465:     my @alltypes = ('_LC_adv','_LC_author','_LC_internetdom','_LC_external','_LC_ipchangesso','_LC_ipchange');
 6466:     my @available;
 6467:     if (ref($types) eq 'ARRAY') {
 6468:         @available = @{$types};
 6469:     }
 6470:     unless (grep(/^default$/,@available)) {
 6471:         push(@available,'default');
 6472:     }
 6473:     unshift(@alltypes,@available);
 6474:     my %titles;
 6475:     foreach my $type (@alltypes) {
 6476:         if ($type =~ /^_LC_/) {
 6477:             $titles{$type} = $othertypes{$type};
 6478:         } elsif ($type eq 'default') {
 6479:             $titles{$type} = &mt('All users from [_1]',$dom);
 6480:             if (ref($types) eq 'ARRAY') {
 6481:                 if (@{$types} > 0) {
 6482:                     $titles{$type} = &mt('Other users from [_1]',$dom);
 6483:                 }
 6484:             }
 6485:         } elsif (ref($usertypes) eq 'HASH') {
 6486:             $titles{$type} = $usertypes->{$type};
 6487:         }
 6488:     }
 6489:     return (\@alltypes,\%othertypes,\%titles);
 6490: }
 6491: 
 6492: sub loadbalance_rule_row {
 6493:     my ($type,$title,$current,$servers,$currbalancer,$lonhost,$dom,
 6494:         $targets_div_style,$homedom_div_style,$css_class,$balnum,$num,$islast) = @_;
 6495:     my @rulenames;
 6496:     my %ruletitles = &offloadtype_text();
 6497:     if (($type eq '_LC_ipchangesso') || ($type eq '_LC_ipchange')) {
 6498:         @rulenames = ('balancer','offloadedto','specific');
 6499:     } else {
 6500:         @rulenames = ('default','homeserver');
 6501:         if ($type eq '_LC_external') {
 6502:             push(@rulenames,'externalbalancer');
 6503:         } else {
 6504:             push(@rulenames,'specific');
 6505:         }
 6506:         push(@rulenames,'none');
 6507:     }
 6508:     my $style = $targets_div_style;
 6509:     if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 6510:         $style = $homedom_div_style;
 6511:     }
 6512:     my $space;
 6513:     if ($islast && $num == 1) {
 6514:         $space = '<div display="inline-block">&nbsp;</div>';
 6515:     }
 6516:     my $output =
 6517:         '<tr class="'.$css_class.'" id="balanceruletr_'.$balnum.'_'.$num.'"><td valign="top">'.$space.
 6518:         '<div id="balanceruletitle_'.$balnum.'_'.$type.'" style="'.$style.'">'.$title.'</div></td>'."\n".
 6519:         '<td valaign="top">'.$space.
 6520:         '<div id="balancerule_'.$balnum.'_'.$type.'" style="'.$style.'">'."\n";
 6521:     for (my $i=0; $i<@rulenames; $i++) {
 6522:         my $rule = $rulenames[$i];
 6523:         my ($checked,$extra);
 6524:         if ($rulenames[$i] eq 'default') {
 6525:             $rule = '';
 6526:         }
 6527:         if ($rulenames[$i] eq 'specific') {
 6528:             if (ref($servers) eq 'HASH') {
 6529:                 my $default;
 6530:                 if (($current ne '') && (exists($servers->{$current}))) {
 6531:                     $checked = ' checked="checked"';
 6532:                 }
 6533:                 unless ($checked) {
 6534:                     $default = ' selected="selected"';
 6535:                 }
 6536:                 $extra =
 6537:                     ':&nbsp;<select name="loadbalancing_singleserver_'.$balnum.'_'.$type.
 6538:                     '" id="loadbalancing_singleserver_'.$balnum.'_'.$type.
 6539:                     '" onchange="singleServerToggle('."'$balnum','$type'".')">'."\n".
 6540:                     '<option value=""'.$default.'></option>'."\n";
 6541:                 foreach my $server (sort(keys(%{$servers}))) {
 6542:                     if (ref($currbalancer) eq 'HASH') {
 6543:                         next if (exists($currbalancer->{$server}));
 6544:                     }
 6545:                     my $selected;
 6546:                     if ($server eq $current) {
 6547:                         $selected = ' selected="selected"';
 6548:                     }
 6549:                     $extra .= '<option value="'.$server.'"'.$selected.'>'.$server.'</option>';
 6550:                 }
 6551:                 $extra .= '</select>';
 6552:             }
 6553:         } elsif ($rule eq $current) {
 6554:             $checked = ' checked="checked"';
 6555:         }
 6556:         $output .= '<span class="LC_nobreak"><label>'.
 6557:                    '<input type="radio" name="loadbalancing_rules_'.$balnum.'_'.$type.
 6558:                    '" id="loadbalancing_rules_'.$balnum.'_'.$type.'_'.$i.'" value="'.
 6559:                    $rule.'" onclick="balanceruleChange('."this.form,'$balnum','$type'".
 6560:                    ')"'.$checked.' />&nbsp;';
 6561:         if (($rulenames[$i] eq 'specific') && ($type =~ /^_LC_ipchange/)) {
 6562:             $output .= $ruletitles{'particular'};
 6563:         } else {
 6564:             $output .= $ruletitles{$rulenames[$i]};
 6565:         }
 6566:         $output .= '</label>'.$extra.'</span><br />'."\n";
 6567:     }
 6568:     $output .= '</div></td></tr>'."\n";
 6569:     return $output;
 6570: }
 6571: 
 6572: sub offloadtype_text {
 6573:     my %ruletitles = &Apache::lonlocal::texthash (
 6574:            'default'          => 'Offloads to default destinations',
 6575:            'homeserver'       => "Offloads to user's home server",
 6576:            'externalbalancer' => "Offloads to Load Balancer in user's domain",
 6577:            'specific'         => 'Offloads to specific server',
 6578:            'none'             => 'No offload',
 6579:            'balancer'         => 'Session hosted on Load Balancer, after re-authentication',
 6580:            'offloadedto'      => 'Session hosted on offload server, after re-authentication',
 6581:            'particular'       => 'Session hosted (after re-auth) on server:',
 6582:     );
 6583:     return %ruletitles;
 6584: }
 6585: 
 6586: sub sparestype_titles {
 6587:     my %typestitles = &Apache::lonlocal::texthash (
 6588:                           'primary' => 'primary',
 6589:                           'default' => 'default',
 6590:                       );
 6591:     return %typestitles;
 6592: }
 6593: 
 6594: sub contact_titles {
 6595:     my %titles = &Apache::lonlocal::texthash (
 6596:                    'supportemail'    => 'Support E-mail address',
 6597:                    'adminemail'      => 'Default Server Admin E-mail address',
 6598:                    'errormail'       => 'Error reports to be e-mailed to',
 6599:                    'packagesmail'    => 'Package update alerts to be e-mailed to',
 6600:                    'helpdeskmail'    => "Helpdesk requests from all users in this domain",
 6601:                    'otherdomsmail'   => 'Helpdesk requests from users in other (unconfigured) domains',
 6602:                    'lonstatusmail'   => 'E-mail from nightly status check (warnings/errors)',
 6603:                    'requestsmail'    => 'E-mail from course requests requiring approval',
 6604:                    'updatesmail'     => 'E-mail from nightly check of LON-CAPA module integrity/updates',
 6605:                    'idconflictsmail' => 'E-mail from bi-nightly check for multiple users sharing same student/employee ID',
 6606:                    'hostipmail'      => 'E-mail from nightly check of hostname/IP network changes',
 6607:                    'errorthreshold'  => 'Error count threshold for status e-mail to admin(s)',
 6608:                    'errorsysmail'    => 'Error count threshold for e-mail to developer group',
 6609:                    'errorweights'    => 'Weights used to compute error count',
 6610:                    'errorexcluded'   => 'Servers with unsent updates excluded from count',
 6611:                  );
 6612:     my %short_titles = &Apache::lonlocal::texthash (
 6613:                            adminemail   => 'Admin E-mail address',
 6614:                            supportemail => 'Support E-mail',
 6615:                        );   
 6616:     return (\%titles,\%short_titles);
 6617: }
 6618: 
 6619: sub helpform_fields {
 6620:     my %titles =  &Apache::lonlocal::texthash (
 6621:                        'username'   => 'Name',
 6622:                        'user'       => 'Username/domain',
 6623:                        'phone'      => 'Phone',
 6624:                        'cc'         => 'Cc e-mail',
 6625:                        'course'     => 'Course Details',
 6626:                        'section'    => 'Sections',
 6627:                        'screenshot' => 'File upload',
 6628:     );
 6629:     my @fields = ('username','phone','user','course','section','cc','screenshot');
 6630:     my %possoptions = (
 6631:                         username     => ['yes','no','req'],
 6632:                         phone        => ['yes','no','req'],
 6633:                         user         => ['yes','no'],
 6634:                         cc           => ['yes','no'],
 6635:                         course       => ['yes','no'],
 6636:                         section      => ['yes','no'],
 6637:                         screenshot   => ['yes','no'],
 6638:                       );
 6639:     my %fieldoptions = &Apache::lonlocal::texthash (
 6640:                          'yes'  => 'Optional',
 6641:                          'req'  => 'Required',
 6642:                          'no'   => "Not shown",
 6643:     );
 6644:     return (\@fields,\%titles,\%fieldoptions,\%possoptions);
 6645: }
 6646: 
 6647: sub tool_titles {
 6648:     my %titles = &Apache::lonlocal::texthash (
 6649:                      aboutme    => 'Personal web page',
 6650:                      blog       => 'Blog',
 6651:                      webdav     => 'WebDAV',
 6652:                      portfolio  => 'Portfolio',
 6653:                      official   => 'Official courses (with institutional codes)',
 6654:                      unofficial => 'Unofficial courses',
 6655:                      community  => 'Communities',
 6656:                      textbook   => 'Textbook courses',
 6657:                  );
 6658:     return %titles;
 6659: }
 6660: 
 6661: sub courserequest_titles {
 6662:     my %titles = &Apache::lonlocal::texthash (
 6663:                                    official   => 'Official',
 6664:                                    unofficial => 'Unofficial',
 6665:                                    community  => 'Communities',
 6666:                                    textbook   => 'Textbook',
 6667:                                    norequest  => 'Not allowed',
 6668:                                    approval   => 'Approval by Dom. Coord.',
 6669:                                    validate   => 'With validation',
 6670:                                    autolimit  => 'Numerical limit',
 6671:                                    unlimited  => '(blank for unlimited)',
 6672:                  );
 6673:     return %titles;
 6674: }
 6675: 
 6676: sub authorrequest_titles {
 6677:     my %titles = &Apache::lonlocal::texthash (
 6678:                                    norequest  => 'Not allowed',
 6679:                                    approval   => 'Approval by Dom. Coord.',
 6680:                                    automatic  => 'Automatic approval',
 6681:                  );
 6682:     return %titles;
 6683: }
 6684: 
 6685: sub courserequest_conditions {
 6686:     my %conditions = &Apache::lonlocal::texthash (
 6687:        approval    => '(Processing of request subject to approval by Domain Coordinator).',
 6688:        validate   => '(Processing of request subject to institutional validation).',
 6689:                  );
 6690:     return %conditions;
 6691: }
 6692: 
 6693: 
 6694: sub print_usercreation {
 6695:     my ($position,$dom,$settings,$rowtotal) = @_;
 6696:     my $numinrow = 4;
 6697:     my $datatable;
 6698:     if ($position eq 'top') {
 6699:         $$rowtotal ++;
 6700:         my $rowcount = 0;
 6701:         my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($dom,'username');
 6702:         if (ref($rules) eq 'HASH') {
 6703:             if (keys(%{$rules}) > 0) {
 6704:                 $datatable .= &user_formats_row('username',$settings,$rules,
 6705:                                                 $ruleorder,$numinrow,$rowcount);
 6706:                 $$rowtotal ++;
 6707:                 $rowcount ++;
 6708:             }
 6709:         }
 6710:         my ($idrules,$idruleorder) = &Apache::lonnet::inst_userrules($dom,'id');
 6711:         if (ref($idrules) eq 'HASH') {
 6712:             if (keys(%{$idrules}) > 0) {
 6713:                 $datatable .= &user_formats_row('id',$settings,$idrules,
 6714:                                                 $idruleorder,$numinrow,$rowcount);
 6715:                 $$rowtotal ++;
 6716:                 $rowcount ++;
 6717:             }
 6718:         }
 6719:         if ($rowcount == 0) {
 6720:             $datatable .= '<tr><td colspan="2">'.&mt('No format rules have been defined for usernames or IDs in this domain.').'</td></tr>';  
 6721:             $$rowtotal ++;
 6722:             $rowcount ++;
 6723:         }
 6724:     } elsif ($position eq 'middle') {
 6725:         my @creators = ('author','course','requestcrs');
 6726:         my ($rules,$ruleorder) =
 6727:             &Apache::lonnet::inst_userrules($dom,'username');
 6728:         my %lt = &usercreation_types();
 6729:         my %checked;
 6730:         if (ref($settings) eq 'HASH') {
 6731:             if (ref($settings->{'cancreate'}) eq 'HASH') {
 6732:                 foreach my $item (@creators) {
 6733:                     $checked{$item} = $settings->{'cancreate'}{$item};
 6734:                 }
 6735:             } elsif (ref($settings->{'cancreate'}) eq 'ARRAY') {
 6736:                 foreach my $item (@creators) {
 6737:                     if (grep(/^\Q$item\E$/,@{$settings->{'cancreate'}})) {
 6738:                         $checked{$item} = 'none';
 6739:                     }
 6740:                 }
 6741:             }
 6742:         }
 6743:         my $rownum = 0;
 6744:         foreach my $item (@creators) {
 6745:             $rownum ++;
 6746:             if ($checked{$item} eq '') {
 6747:                 $checked{$item} = 'any';
 6748:             }
 6749:             my $css_class;
 6750:             if ($rownum%2) {
 6751:                 $css_class = '';
 6752:             } else {
 6753:                 $css_class = ' class="LC_odd_row" ';
 6754:             }
 6755:             $datatable .= '<tr'.$css_class.'>'.
 6756:                          '<td><span class="LC_nobreak">'.$lt{$item}.
 6757:                          '</span></td><td align="right">';
 6758:             my @options = ('any');
 6759:             if (ref($rules) eq 'HASH') {
 6760:                 if (keys(%{$rules}) > 0) {
 6761:                     push(@options,('official','unofficial'));
 6762:                 }
 6763:             }
 6764:             push(@options,'none');
 6765:             foreach my $option (@options) {
 6766:                 my $type = 'radio';
 6767:                 my $check = ' ';
 6768:                 if ($checked{$item} eq $option) {
 6769:                     $check = ' checked="checked" ';
 6770:                 } 
 6771:                 $datatable .= '<span class="LC_nobreak"><label>'.
 6772:                               '<input type="'.$type.'" name="can_createuser_'.
 6773:                               $item.'" value="'.$option.'"'.$check.'/>&nbsp;'.
 6774:                               $lt{$option}.'</label>&nbsp;&nbsp;</span>';
 6775:             }
 6776:             $datatable .= '</td></tr>';
 6777:         }
 6778:     } else {
 6779:         my @contexts = ('author','course','domain');
 6780:         my @authtypes = ('int','krb4','krb5','loc');
 6781:         my %checked;
 6782:         if (ref($settings) eq 'HASH') {
 6783:             if (ref($settings->{'authtypes'}) eq 'HASH') {
 6784:                 foreach my $item (@contexts) {
 6785:                     if (ref($settings->{'authtypes'}{$item}) eq 'HASH') {
 6786:                         foreach my $auth (@authtypes) {
 6787:                             if ($settings->{'authtypes'}{$item}{$auth}) {
 6788:                                 $checked{$item}{$auth} = ' checked="checked" ';
 6789:                             }
 6790:                         }
 6791:                     }
 6792:                 }
 6793:             }
 6794:         } else {
 6795:             foreach my $item (@contexts) {
 6796:                 foreach my $auth (@authtypes) {
 6797:                     $checked{$item}{$auth} = ' checked="checked" ';
 6798:                 }
 6799:             }
 6800:         }
 6801:         my %title = &context_names();
 6802:         my %authname = &authtype_names();
 6803:         my $rownum = 0;
 6804:         my $css_class; 
 6805:         foreach my $item (@contexts) {
 6806:             if ($rownum%2) {
 6807:                 $css_class = '';
 6808:             } else {
 6809:                 $css_class = ' class="LC_odd_row" ';
 6810:             }
 6811:             $datatable .=   '<tr'.$css_class.'>'.
 6812:                             '<td>'.$title{$item}.
 6813:                             '</td><td class="LC_left_item">'.
 6814:                             '<span class="LC_nobreak">';
 6815:             foreach my $auth (@authtypes) {
 6816:                 $datatable .= '<label>'. 
 6817:                               '<input type="checkbox" name="'.$item.'_auth" '.
 6818:                               $checked{$item}{$auth}.' value="'.$auth.'" />'.
 6819:                               $authname{$auth}.'</label>&nbsp;';
 6820:             }
 6821:             $datatable .= '</span></td></tr>';
 6822:             $rownum ++;
 6823:         }
 6824:         $$rowtotal += $rownum;
 6825:     }
 6826:     return $datatable;
 6827: }
 6828: 
 6829: sub print_selfcreation {
 6830:     my ($position,$dom,$settings,$rowtotal) = @_;
 6831:     my (@selfcreate,$createsettings,$processing,$emailoptions,$emailverified,
 6832:         $emaildomain,$datatable);
 6833:     if (ref($settings) eq 'HASH') {
 6834:         if (ref($settings->{'cancreate'}) eq 'HASH') {
 6835:             $createsettings = $settings->{'cancreate'};
 6836:             if (ref($createsettings) eq 'HASH') {
 6837:                 if (ref($createsettings->{'selfcreate'}) eq 'ARRAY') {
 6838:                     @selfcreate = @{$createsettings->{'selfcreate'}};
 6839:                 } elsif ($createsettings->{'selfcreate'} ne '') {
 6840:                     if ($settings->{'cancreate'}{'selfcreate'} eq 'any') {
 6841:                         @selfcreate = ('email','login','sso');
 6842:                     } elsif ($createsettings->{'selfcreate'} ne 'none') {
 6843:                         @selfcreate = ($createsettings->{'selfcreate'});
 6844:                     }
 6845:                 }
 6846:                 if (ref($createsettings->{'selfcreateprocessing'}) eq 'HASH') {
 6847:                     $processing = $createsettings->{'selfcreateprocessing'};
 6848:                 }
 6849:                 if (ref($createsettings->{'emailoptions'}) eq 'HASH') {
 6850:                     $emailoptions = $createsettings->{'emailoptions'};
 6851:                 }
 6852:                 if (ref($createsettings->{'emailverified'}) eq 'HASH') {
 6853:                     $emailverified = $createsettings->{'emailverified'};
 6854:                 }
 6855:                 if (ref($createsettings->{'emaildomain'}) eq 'HASH') {
 6856:                     $emaildomain = $createsettings->{'emaildomain'};
 6857:                 }
 6858:             }
 6859:         }
 6860:     }
 6861:     my %radiohash;
 6862:     my $numinrow = 4;
 6863:     map { $radiohash{'cancreate_'.$_} = 1; } @selfcreate;
 6864:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 6865:     if ($position eq 'top') {
 6866:         my %choices = &Apache::lonlocal::texthash (
 6867:                                                       cancreate_login      => 'Institutional Login',
 6868:                                                       cancreate_sso        => 'Institutional Single Sign On',
 6869:                                                   );
 6870:         my @toggles = sort(keys(%choices));
 6871:         my %defaultchecked = (
 6872:                                'cancreate_login' => 'off',
 6873:                                'cancreate_sso'   => 'off',
 6874:                              );
 6875:         my ($onclick,$itemcount);
 6876:         ($datatable,$itemcount) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 6877:                                                      \%choices,$itemcount,$onclick);
 6878:         $$rowtotal += $itemcount;
 6879: 
 6880:         if (ref($usertypes) eq 'HASH') {
 6881:             if (keys(%{$usertypes}) > 0) {
 6882:                 $datatable .= &insttypes_row($createsettings,$types,$usertypes,
 6883:                                              $dom,$numinrow,$othertitle,
 6884:                                              'statustocreate',$rowtotal);
 6885:                 $$rowtotal ++;
 6886:             }
 6887:         }
 6888:         my @fields = ('lastname','firstname','middlename','permanentemail','id','inststatus');
 6889:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 6890:         $fieldtitles{'inststatus'} = &mt('Institutional status');
 6891:         my $rem;
 6892:         my $numperrow = 2;
 6893:         my $css_class = $$rowtotal%2?' class="LC_odd_row"':'';
 6894:         $datatable .= '<tr'.$css_class.'>'.
 6895:                      '<td class="LC_left_item">'.&mt('Mapping of Shibboleth environment variable names to user data fields (SSO auth)').'</td>'.
 6896:                      '<td class="LC_left_item">'."\n".
 6897:                      '<table>'."\n";
 6898:         for (my $i=0; $i<@fields; $i++) {
 6899:             $rem = $i%($numperrow);
 6900:             if ($rem == 0) {
 6901:                 if ($i > 0) {
 6902:                     $datatable .= '</tr>';
 6903:                 }
 6904:                 $datatable .= '<tr>';
 6905:             }
 6906:             my $currval;
 6907:             if (ref($createsettings) eq 'HASH') {
 6908:                 if (ref($createsettings->{'shibenv'}) eq 'HASH') {
 6909:                     $currval = $createsettings->{'shibenv'}{$fields[$i]};
 6910:                 }
 6911:             }
 6912:             $datatable .= '<td class="LC_left_item">'.
 6913:                           '<span class="LC_nobreak">'.
 6914:                           '<input type="text" name="shibenv_'.$fields[$i].'" '.
 6915:                           'value="'.$currval.'" size="10" />&nbsp;'.
 6916:                           $fieldtitles{$fields[$i]}.'</span></td>';
 6917:         }
 6918:         my $colsleft = $numperrow - $rem;
 6919:         if ($colsleft > 1 ) {
 6920:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 6921:                          '&nbsp;</td>';
 6922:         } elsif ($colsleft == 1) {
 6923:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 6924:         }
 6925:         $datatable .= '</tr></table></td></tr>';
 6926:         $$rowtotal ++;
 6927:     } elsif ($position eq 'middle') {
 6928:         my %domconf = &Apache::lonnet::get_dom('configuration',['usermodification'],$dom);
 6929:         my @posstypes;
 6930:         if (ref($types) eq 'ARRAY') {
 6931:             @posstypes = @{$types};
 6932:         }
 6933:         unless (grep(/^default$/,@posstypes)) {
 6934:             push(@posstypes,'default');
 6935:         }
 6936:         my %usertypeshash;
 6937:         if (ref($usertypes) eq 'HASH') {
 6938:             %usertypeshash = %{$usertypes};
 6939:         }
 6940:         $usertypeshash{'default'} = $othertitle;
 6941:         foreach my $status (@posstypes) {
 6942:             $datatable .= &modifiable_userdata_row('selfcreate',$status,$domconf{'usermodification'},
 6943:                                                    $numinrow,$$rowtotal,\%usertypeshash);
 6944:             $$rowtotal ++;
 6945:         }
 6946:     } else {
 6947:         my %choices = &Apache::lonlocal::texthash (
 6948:                           'cancreate_email' => 'Non-institutional username (via e-mail verification)',
 6949:                                                   );
 6950:         my @toggles = sort(keys(%choices));
 6951:         my %defaultchecked = (
 6952:                                'cancreate_email' => 'off',
 6953:                              );
 6954:         my $customclass = 'LC_selfcreate_email';
 6955:         my $classprefix = 'LC_canmodify_emailusername_';
 6956:         my $optionsprefix = 'LC_options_emailusername_';
 6957:         my $display = 'none';
 6958:         my $rowstyle = 'display:none';
 6959:         if (grep(/^\Qemail\E$/,@selfcreate)) {
 6960:             $display = 'block';
 6961:             $rowstyle = 'display:table-row';
 6962:         }
 6963:         my $onclick = "toggleRows(this.form,'cancreate_email','selfassign','$customclass','$classprefix','$optionsprefix');";
 6964:         ($datatable,$$rowtotal) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 6965:                                                      \%choices,$$rowtotal,$onclick);
 6966:         $datatable .= &print_requestmail($dom,'selfcreation',$createsettings,$rowtotal,$customclass,
 6967:                                          $rowstyle);
 6968:         $$rowtotal ++;
 6969:         $datatable .= &captcha_choice('cancreate',$createsettings,$$rowtotal,$customclass,
 6970:                                       $rowstyle);
 6971:         $$rowtotal ++;
 6972:         my (@ordered,@posstypes,%usertypeshash);
 6973:         my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
 6974:         my ($emailrules,$emailruleorder) =
 6975:             &Apache::lonnet::inst_userrules($dom,'email');
 6976:         my $primary_id = &Apache::lonnet::domain($dom,'primary');
 6977:         my $intdom = &Apache::lonnet::internet_dom($primary_id);
 6978:         if (ref($types) eq 'ARRAY') {
 6979:             @posstypes = @{$types};
 6980:         }
 6981:         if (@posstypes) {
 6982:             unless (grep(/^default$/,@posstypes)) {
 6983:                 push(@posstypes,'default');
 6984:             }
 6985:             if (ref($usertypes) eq 'HASH') {
 6986:                 %usertypeshash = %{$usertypes};
 6987:             }
 6988:             my $currassign;
 6989:             if (ref($domdefaults{'inststatusguest'}) eq 'ARRAY') {
 6990:                 $currassign = {
 6991:                                   selfassign => $domdefaults{'inststatusguest'},
 6992:                               };
 6993:                 @ordered = @{$domdefaults{'inststatusguest'}};
 6994:             } else {
 6995:                 $currassign = { selfassign => [] };
 6996:             }
 6997:             my $onclicktypes = "toggleDataRow(this.form,'selfassign','$customclass','$optionsprefix',);".
 6998:                                "toggleDataRow(this.form,'selfassign','$customclass','$classprefix',1);";
 6999:             $datatable .= &insttypes_row($currassign,$types,$usertypes,$dom,
 7000:                                          $numinrow,$othertitle,'selfassign',
 7001:                                          $rowtotal,$onclicktypes,$customclass,
 7002:                                          $rowstyle);
 7003:             $$rowtotal ++;
 7004:             $usertypeshash{'default'} = $othertitle;
 7005:             foreach my $status (@posstypes) {
 7006:                 my $css_class;
 7007:                 if ($$rowtotal%2) {
 7008:                     $css_class = 'LC_odd_row ';
 7009:                 }
 7010:                 $css_class .= $customclass;
 7011:                 my $rowid = $optionsprefix.$status;
 7012:                 my $hidden = 1;
 7013:                 my $currstyle = 'display:none';
 7014:                 if (grep(/^\Q$status\E$/,@ordered)) {
 7015:                     $currstyle = $rowstyle;
 7016:                     $hidden = 0;
 7017:                 }
 7018:                 $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
 7019:                                              $emailrules,$emailruleorder,$settings,$status,$rowid,
 7020:                                              $usertypeshash{$status},$css_class,$currstyle,$intdom);
 7021:                 unless ($hidden) {
 7022:                     $$rowtotal ++;
 7023:                 }
 7024:             }
 7025:         } else {
 7026:             my $css_class;
 7027:             if ($$rowtotal%2) {
 7028:                 $css_class = 'LC_odd_row ';
 7029:             }
 7030:             $css_class .= $customclass;
 7031:             $usertypeshash{'default'} = $othertitle;
 7032:             $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
 7033:                                          $emailrules,$emailruleorder,$settings,'default','',
 7034:                                          $othertitle,$css_class,$rowstyle,$intdom);
 7035:             $$rowtotal ++;
 7036:         }
 7037:         my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 7038:         $numinrow = 1;
 7039:         if (@posstypes) {
 7040:             foreach my $status (@posstypes) {
 7041:                 my $rowid = $classprefix.$status;
 7042:                 my $datarowstyle = 'display:none';
 7043:                 if (grep(/^\Q$status\E$/,@ordered)) {
 7044:                     $datarowstyle = $rowstyle;
 7045:                 }
 7046:                 $datatable .= &modifiable_userdata_row('cancreate','emailusername_'.$status,$settings,
 7047:                                                        $numinrow,$$rowtotal,\%usertypeshash,$infofields,
 7048:                                                        $infotitles,$rowid,$customclass,$datarowstyle);
 7049:                 unless ($datarowstyle eq 'display:none') {
 7050:                     $$rowtotal ++;
 7051:                 }
 7052:             }
 7053:         } else {
 7054:             $datatable .= &modifiable_userdata_row('cancreate','emailusername_default',$settings,
 7055:                                                    $numinrow,$$rowtotal,\%usertypeshash,$infofields,
 7056:                                                    $infotitles,'',$customclass,$rowstyle);
 7057:         }
 7058:     }
 7059:     return $datatable;
 7060: }
 7061: 
 7062: sub selfcreate_javascript {
 7063:     return <<"ENDSCRIPT";
 7064: 
 7065: <script type="text/javascript">
 7066: // <![CDATA[
 7067: 
 7068: function toggleRows(form,radio,checkbox,target,prefix,altprefix) {
 7069:     var x = document.getElementsByClassName(target);
 7070:     var insttypes = 0;
 7071:     var insttypeRegExp = new RegExp(prefix);
 7072:     if ((x.length != undefined) && (x.length > 0)) {
 7073:         if (form.elements[radio].length != undefined) {
 7074:             for (var i=0; i<form.elements[radio].length; i++) {
 7075:                 if (form.elements[radio][i].checked) {
 7076:                     if (form.elements[radio][i].value == 1) {
 7077:                         for (var j=0; j<x.length; j++) {
 7078:                             if (x[j].id == 'undefined') {
 7079:                                 x[j].style.display = 'table-row';
 7080:                             } else if (insttypeRegExp.test(x[j].id)) {
 7081:                                 insttypes ++;
 7082:                             } else {
 7083:                                 x[j].style.display = 'table-row';
 7084:                             }
 7085:                         }
 7086:                     } else {
 7087:                         for (var j=0; j<x.length; j++) {
 7088:                             x[j].style.display = 'none';
 7089:                         }
 7090:                     }
 7091:                     break;
 7092:                 }
 7093:             }
 7094:             if (insttypes > 0) {
 7095:                 toggleDataRow(form,checkbox,target,altprefix);
 7096:                 toggleDataRow(form,checkbox,target,prefix,1);
 7097:             }
 7098:         }
 7099:     }
 7100:     return;
 7101: }
 7102: 
 7103: function toggleDataRow(form,checkbox,target,prefix,docount) {
 7104:     if (form.elements[checkbox].length != undefined) {
 7105:         var count = 0;
 7106:         if (docount) {
 7107:             for (var i=0; i<form.elements[checkbox].length; i++) {
 7108:                 if (form.elements[checkbox][i].checked) {
 7109:                     count ++;
 7110:                 }
 7111:             }
 7112:         }
 7113:         for (var i=0; i<form.elements[checkbox].length; i++) {
 7114:             var type = form.elements[checkbox][i].value;
 7115:             if (document.getElementById(prefix+type)) {
 7116:                 if (form.elements[checkbox][i].checked) {
 7117:                     document.getElementById(prefix+type).style.display = 'table-row';
 7118:                     if (count % 2 == 1) {
 7119:                         document.getElementById(prefix+type).className = target+' LC_odd_row';
 7120:                     } else {
 7121:                         document.getElementById(prefix+type).className = target;
 7122:                     }
 7123:                     count ++;
 7124:                 } else {
 7125:                     document.getElementById(prefix+type).style.display = 'none';
 7126:                 }
 7127:             }
 7128:         }
 7129:     }
 7130:     return;
 7131: }
 7132: 
 7133: function toggleEmailOptions(form,radio,prefix,altprefix,status) {
 7134:     var caller = radio+'_'+status;
 7135:     if (form.elements[caller].length != undefined) {
 7136:         for (var i=0; i<form.elements[caller].length; i++) {
 7137:             if (form.elements[caller][i].checked) {
 7138:                 if (document.getElementById(altprefix+'_inst_'+status)) {
 7139:                     var curr = form.elements[caller][i].value;
 7140:                     if (prefix) {
 7141:                         document.getElementById(prefix+'_'+status).style.display = 'none';
 7142:                     }
 7143:                     document.getElementById(altprefix+'_inst_'+status).style.display = 'none';
 7144:                     document.getElementById(altprefix+'_noninst_'+status).style.display = 'none';
 7145:                     if (curr == 'custom') {
 7146:                         if (prefix) {
 7147:                             document.getElementById(prefix+'_'+status).style.display = 'inline';
 7148:                         }
 7149:                     } else if (curr == 'inst') {
 7150:                         document.getElementById(altprefix+'_inst_'+status).style.display = 'inline';
 7151:                     } else if (curr == 'noninst') {
 7152:                         document.getElementById(altprefix+'_noninst_'+status).style.display = 'inline';
 7153:                     }
 7154:                     break;
 7155:                 }
 7156:             }
 7157:         }
 7158:     }
 7159: }
 7160: 
 7161: // ]]>
 7162: </script>
 7163: 
 7164: ENDSCRIPT
 7165: }
 7166: 
 7167: sub noninst_users {
 7168:     my ($processing,$emailverified,$emailoptions,$emaildomain,$emailrules,
 7169:         $emailruleorder,$settings,$type,$rowid,$typetitle,$css_class,$rowstyle,$intdom) = @_;
 7170:     my $class = 'LC_left_item';
 7171:     if ($css_class) {
 7172:         $css_class = ' class="'.$css_class.'"';
 7173:     }
 7174:     if ($rowid) {
 7175:         $rowid = ' id="'.$rowid.'"';
 7176:     }
 7177:     if ($rowstyle) {
 7178:         $rowstyle = ' style="'.$rowstyle.'"';
 7179:     }
 7180:     my ($output,$description);
 7181:     if ($type eq 'default') {
 7182:         $description = &mt('Requests for: [_1]',$typetitle);
 7183:     } else {
 7184:         $description = &mt('Requests for: [_1] (status self-reported)',$typetitle);
 7185:     }
 7186:     $output = '<tr'.$css_class.$rowid.$rowstyle.'>'.
 7187:               "<td>$description</td>\n".
 7188:               '<td class="'.$class.'" colspan="2">'.
 7189:               '<table><tr>';
 7190:     my %headers = &Apache::lonlocal::texthash(
 7191:               approve  => 'Processing',
 7192:               email    => 'E-mail',
 7193:               username => 'Username',
 7194:     );
 7195:     foreach my $item ('approve','email','username') {
 7196:         $output .= '<th>'.$headers{$item}.'</th>';
 7197:     }
 7198:     $output .= '</tr><tr>';
 7199:     foreach my $item ('approve','email','username') {
 7200:         $output .= '<td valign="top">';
 7201:         my (%choices,@options,$hashref,$defoption,$name,$onclick,$hascustom);
 7202:         if ($item eq 'approve') {
 7203:             %choices = &Apache::lonlocal::texthash (
 7204:                                                      automatic => 'Automatically approved',
 7205:                                                      approval  => 'Queued for approval',
 7206:                                                    );
 7207:             @options = ('automatic','approval');
 7208:             $hashref = $processing;
 7209:             $defoption = 'automatic';
 7210:             $name = 'cancreate_emailprocess_'.$type;
 7211:         } elsif ($item eq 'email') {
 7212:             %choices = &Apache::lonlocal::texthash (
 7213:                                                      any     => 'Any e-mail',
 7214:                                                      inst    => 'Institutional only',
 7215:                                                      noninst => 'Non-institutional only',
 7216:                                                      custom  => 'Custom restrictions',
 7217:                                                    );
 7218:             @options = ('any','inst','noninst');
 7219:             my $showcustom;
 7220:             if (ref($emailrules) eq 'HASH') {
 7221:                 if (keys(%{$emailrules}) > 0) {
 7222:                     push(@options,'custom');
 7223:                     $showcustom = 'cancreate_emailrule';
 7224:                     if (ref($settings) eq 'HASH') {
 7225:                         if (ref($settings->{'email_rule'}) eq 'ARRAY') {
 7226:                             foreach my $rule (@{$settings->{'email_rule'}}) {
 7227:                                 if (exists($emailrules->{$rule})) {
 7228:                                     $hascustom ++;
 7229:                                 }
 7230:                             }
 7231:                         } elsif (ref($settings->{'email_rule'}) eq 'HASH') {
 7232:                             if (ref($settings->{'email_rule'}{$type}) eq 'ARRAY') {
 7233:                                 foreach my $rule (@{$settings->{'email_rule'}{$type}}) {
 7234:                                     if (exists($emailrules->{$rule})) {
 7235:                                         $hascustom ++;
 7236:                                     }
 7237:                                 }
 7238:                             }
 7239:                         }
 7240:                     }
 7241:                 }
 7242:             }
 7243:             $onclick = ' onclick="toggleEmailOptions(this.form,'."'cancreate_emailoptions','$showcustom',".
 7244:                                                      "'cancreate_emaildomain','$type'".');"';
 7245:             $hashref = $emailoptions;
 7246:             $defoption = 'any';
 7247:             $name = 'cancreate_emailoptions_'.$type;
 7248:         } elsif ($item eq 'username') {
 7249:             %choices = &Apache::lonlocal::texthash (
 7250:                                                      all    => 'Same as e-mail',
 7251:                                                      first  => 'Omit @domain',
 7252:                                                      free   => 'Free to choose',
 7253:                                                    );
 7254:             @options = ('all','first','free');
 7255:             $hashref = $emailverified;
 7256:             $defoption = 'all';
 7257:             $name = 'cancreate_usernameoptions_'.$type;
 7258:         }
 7259:         foreach my $option (@options) {
 7260:             my $checked;
 7261:             if (ref($hashref) eq 'HASH') {
 7262:                 if ($type eq '') {
 7263:                     if (!exists($hashref->{'default'})) {
 7264:                         if ($option eq $defoption) {
 7265:                             $checked = ' checked="checked"';
 7266:                         }
 7267:                     } else {
 7268:                         if ($hashref->{'default'} eq $option) {
 7269:                             $checked = ' checked="checked"';
 7270:                         }
 7271:                     }
 7272:                 } else {
 7273:                     if (!exists($hashref->{$type})) {
 7274:                         if ($option eq $defoption) {
 7275:                             $checked = ' checked="checked"';
 7276:                         }
 7277:                     } else {
 7278:                         if ($hashref->{$type} eq $option) {
 7279:                             $checked = ' checked="checked"';
 7280:                         }
 7281:                     }
 7282:                 }
 7283:             } elsif (($item eq 'email') && ($hascustom)) {
 7284:                 if ($option eq 'custom') {
 7285:                     $checked = ' checked="checked"';
 7286:                 }
 7287:             } elsif ($option eq $defoption) {
 7288:                 $checked = ' checked="checked"';
 7289:             }
 7290:             $output .= '<span class="LC_nobreak"><label>'.
 7291:                        '<input type="radio" name="'.$name.'"'.
 7292:                        $checked.' value="'.$option.'"'.$onclick.' />'.
 7293:                        $choices{$option}.'</label></span><br />';
 7294:             if ($item eq 'email') {
 7295:                 if ($option eq 'custom') {
 7296:                     my $id = 'cancreate_emailrule_'.$type;
 7297:                     my $display = 'none';
 7298:                     if ($checked) {
 7299:                         $display = 'inline';
 7300:                     }
 7301:                     my $numinrow = 2;
 7302:                     $output .= '<fieldset id="'.$id.'" style="display:'.$display.';">'.
 7303:                                '<legend>'.&mt('Disallow').'</legend><table>'.
 7304:                                &user_formats_row('email',$settings,$emailrules,
 7305:                                                  $emailruleorder,$numinrow,'',$type);
 7306:                               '</table></fieldset>';
 7307:                 } elsif (($option eq 'inst') || ($option eq 'noninst')) {
 7308:                     my %text = &Apache::lonlocal::texthash (
 7309:                                                              inst    => 'must end:',
 7310:                                                              noninst => 'cannot end:',
 7311:                                                            );
 7312:                     my $value;
 7313:                     if (ref($emaildomain) eq 'HASH') {
 7314:                         if (ref($emaildomain->{$type}) eq 'HASH') {
 7315:                             $value = $emaildomain->{$type}->{$option};
 7316:                         }
 7317:                     }
 7318:                     if ($value eq '') {
 7319:                         $value = '@'.$intdom;
 7320:                     }
 7321:                     my $condition = 'cancreate_emaildomain_'.$option.'_'.$type;
 7322:                     my $display = 'none';
 7323:                     if ($checked) {
 7324:                         $display = 'inline';
 7325:                     }
 7326:                     $output .= '<div id="'.$condition.'" style="display:'.$display.';">'.
 7327:                                '<span class="LC_domprefs_email">'.$text{$option}.'</span> '.
 7328:                                '<input type="text" name="'.$condition.'" value="'.$value.'" size="10" />'.
 7329:                                '</div>';
 7330:                 }
 7331:             }
 7332:         }
 7333:         $output .= '</td>'."\n";
 7334:     }
 7335:     $output .= "</tr></table></td></tr>\n";
 7336:     return $output;
 7337: }
 7338: 
 7339: sub captcha_choice {
 7340:     my ($context,$settings,$itemcount,$customcss,$rowstyle) = @_;
 7341:     my ($keyentry,$currpub,$currpriv,%checked,$rowname,$pubtext,$privtext,
 7342:         $vertext,$currver); 
 7343:     my %lt = &captcha_phrases();
 7344:     $keyentry = 'hidden';
 7345:     my $colspan=2;
 7346:     if ($context eq 'cancreate') {
 7347:         $rowname = &mt('CAPTCHA validation');
 7348:     } elsif ($context eq 'login') {
 7349:         $rowname =  &mt('"Contact helpdesk" CAPTCHA validation');
 7350:     } elsif ($context eq 'passwords') {
 7351:         $rowname = &mt('"Forgot Password" CAPTCHA validation');
 7352:         $colspan=1;
 7353:     }
 7354:     if (ref($settings) eq 'HASH') {
 7355:         if ($settings->{'captcha'}) {
 7356:             $checked{$settings->{'captcha'}} = ' checked="checked"';
 7357:         } else {
 7358:             $checked{'original'} = ' checked="checked"';
 7359:         }
 7360:         if ($settings->{'captcha'} eq 'recaptcha') {
 7361:             $pubtext = $lt{'pub'};
 7362:             $privtext = $lt{'priv'};
 7363:             $keyentry = 'text';
 7364:             $vertext = $lt{'ver'};
 7365:             $currver = $settings->{'recaptchaversion'};
 7366:             if ($currver ne '2') {
 7367:                 $currver = 1;
 7368:             }
 7369:         }
 7370:         if (ref($settings->{'recaptchakeys'}) eq 'HASH') {
 7371:             $currpub = $settings->{'recaptchakeys'}{'public'};
 7372:             $currpriv = $settings->{'recaptchakeys'}{'private'};
 7373:         }
 7374:     } else {
 7375:         $checked{'original'} = ' checked="checked"';
 7376:     }
 7377:     my $css_class;
 7378:     if ($itemcount%2) {
 7379:         $css_class = 'LC_odd_row';
 7380:     }
 7381:     if ($customcss) {
 7382:         $css_class .= " $customcss";
 7383:     }
 7384:     $css_class =~ s/^\s+//;
 7385:     if ($css_class) {
 7386:         $css_class = ' class="'.$css_class.'"';
 7387:     }
 7388:     if ($rowstyle) {
 7389:         $css_class .= ' style="'.$rowstyle.'"';
 7390:     }
 7391:     my $output = '<tr'.$css_class.'>'.
 7392:                  '<td class="LC_left_item">'.$rowname.'</td><td class="LC_left_item" colspan="'.$colspan.'">'."\n".
 7393:                  '<table><tr><td>'."\n";
 7394:     foreach my $option ('original','recaptcha','notused') {
 7395:         $output .= '<span class="LC_nobreak"><label><input type="radio" name="'.$context.'_captcha" value="'.
 7396:                    $option.'" '.$checked{$option}.' onchange="javascript:updateCaptcha('."this,'$context'".');" />'.
 7397:                    $lt{$option}.'</label></span>';
 7398:         unless ($option eq 'notused') {
 7399:             $output .= ('&nbsp;'x2)."\n";
 7400:         }
 7401:     }
 7402: #
 7403: # Note: If reCAPTCHA is to be used for LON-CAPA servers in a domain, a domain coordinator should visit:
 7404: # https://www.google.com/recaptcha and generate a Public and Private key. For domains with multiple
 7405: # servers a single key pair will be used for all servers, so the internet domain (e.g., yourcollege.edu)
 7406: # specified for use with the key should be broad enough to accommodate all servers in the LON-CAPA domain.
 7407: #
 7408:     $output .= '</td></tr>'."\n".
 7409:                '<tr><td class="LC_zero_height">'."\n".
 7410:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchapubtxt">'.$pubtext.'</span>&nbsp;'."\n".
 7411:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapub" name="'.$context.'_recaptchapub" value="'.
 7412:                $currpub.'" size="40" /></span><br />'."\n".
 7413:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchaprivtxt">'.$privtext.'</span>&nbsp;'."\n".
 7414:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapriv" name="'.$context.'_recaptchapriv" value="'.
 7415:                $currpriv.'" size="40" /></span><br />'.
 7416:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchavertxt">'.$vertext.'</span>&nbsp;'."\n".
 7417:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchaversion" name="'.$context.'_recaptchaversion" value="'.
 7418:                $currver.'" size="3" /></span><br />'.
 7419:                '</td></tr></table>'."\n".
 7420:                '</td></tr>';
 7421:     return $output;
 7422: }
 7423: 
 7424: sub user_formats_row {
 7425:     my ($type,$settings,$rules,$ruleorder,$numinrow,$rowcount,$status) = @_;
 7426:     my $output;
 7427:     my %text = (
 7428:                    'username' => 'new usernames',
 7429:                    'id'       => 'IDs',
 7430:                );
 7431:     unless (($type eq 'email') || ($type eq 'unamemap')) {
 7432:         my $css_class = $rowcount%2?' class="LC_odd_row"':'';
 7433:         $output = '<tr '.$css_class.'>'.
 7434:                   '<td><span class="LC_nobreak">'.
 7435:                   &mt("Format rules to check for $text{$type}: ").
 7436:                   '</td><td class="LC_left_item" colspan="2"><table>';
 7437:     }
 7438:     my $rem;
 7439:     if (ref($ruleorder) eq 'ARRAY') {
 7440:         for (my $i=0; $i<@{$ruleorder}; $i++) {
 7441:             if (ref($rules->{$ruleorder->[$i]}) eq 'HASH') {
 7442:                 my $rem = $i%($numinrow);
 7443:                 if ($rem == 0) {
 7444:                     if ($i > 0) {
 7445:                         $output .= '</tr>';
 7446:                     }
 7447:                     $output .= '<tr>';
 7448:                 }
 7449:                 my $check = ' ';
 7450:                 if (ref($settings) eq 'HASH') {
 7451:                     if (ref($settings->{$type.'_rule'}) eq 'ARRAY') {
 7452:                         if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}})) {
 7453:                             $check = ' checked="checked" ';
 7454:                         }
 7455:                     } elsif ((ref($settings->{$type.'_rule'}) eq 'HASH') && ($status ne '')) {
 7456:                         if (ref($settings->{$type.'_rule'}->{$status}) eq 'ARRAY') {
 7457:                             if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}->{$status}})) {
 7458:                                 $check = ' checked="checked" ';
 7459:                             }
 7460:                         }
 7461:                     }
 7462:                 }
 7463:                 my $name = $type.'_rule';
 7464:                 if ($type eq 'email') {
 7465:                     $name .= '_'.$status;
 7466:                 }
 7467:                 $output .= '<td class="LC_left_item">'.
 7468:                            '<span class="LC_nobreak"><label>'.
 7469:                            '<input type="checkbox" name="'.$name.'" '.
 7470:                            'value="'.$ruleorder->[$i].'"'.$check.'/>'.
 7471:                            $rules->{$ruleorder->[$i]}{'name'}.'</label></span></td>';
 7472:             }
 7473:         }
 7474:         $rem = @{$ruleorder}%($numinrow);
 7475:     }
 7476:     my $colsleft;
 7477:     if ($rem) {
 7478:         $colsleft = $numinrow - $rem;
 7479:     }
 7480:     if ($colsleft > 1 ) {
 7481:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 7482:                    '&nbsp;</td>';
 7483:     } elsif ($colsleft == 1) {
 7484:         $output .= '<td class="LC_left_item">&nbsp;</td>';
 7485:     }
 7486:     $output .= '</tr>';
 7487:     unless (($type eq 'email') || ($type eq 'unamemap')) {
 7488:         $output .= '</table></td></tr>';
 7489:     }
 7490:     return $output;
 7491: }
 7492: 
 7493: sub usercreation_types {
 7494:     my %lt = &Apache::lonlocal::texthash (
 7495:                     author     => 'When adding a co-author',
 7496:                     course     => 'When adding a user to a course',
 7497:                     requestcrs => 'When requesting a course',
 7498:                     any        => 'Any',
 7499:                     official   => 'Institutional only ',
 7500:                     unofficial => 'Non-institutional only',
 7501:                     none       => 'None',
 7502:     );
 7503:     return %lt;
 7504: }
 7505: 
 7506: sub selfcreation_types {
 7507:     my %lt = &Apache::lonlocal::texthash (
 7508:                     selfcreate => 'User creates own account',
 7509:                     any        => 'Any',
 7510:                     official   => 'Institutional only ',
 7511:                     unofficial => 'Non-institutional only',
 7512:                     email      => 'E-mail address',
 7513:                     login      => 'Institutional Login',
 7514:                     sso        => 'SSO',
 7515:              );
 7516: }
 7517: 
 7518: sub authtype_names {
 7519:     my %lt = &Apache::lonlocal::texthash(
 7520:                       int    => 'Internal',
 7521:                       krb4   => 'Kerberos 4',
 7522:                       krb5   => 'Kerberos 5',
 7523:                       loc    => 'Local',
 7524:                   );
 7525:     return %lt;
 7526: }
 7527: 
 7528: sub context_names {
 7529:     my %context_title = &Apache::lonlocal::texthash(
 7530:        author => 'Creating users when an Author',
 7531:        course => 'Creating users when in a course',
 7532:        domain => 'Creating users when a Domain Coordinator',
 7533:     );
 7534:     return %context_title;
 7535: }
 7536: 
 7537: sub print_usermodification {
 7538:     my ($position,$dom,$settings,$rowtotal) = @_;
 7539:     my $numinrow = 4;
 7540:     my ($context,$datatable,$rowcount);
 7541:     if ($position eq 'top') {
 7542:         $rowcount = 0;
 7543:         $context = 'author'; 
 7544:         foreach my $role ('ca','aa') {
 7545:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
 7546:                                                    $numinrow,$rowcount);
 7547:             $$rowtotal ++;
 7548:             $rowcount ++;
 7549:         }
 7550:     } elsif ($position eq 'bottom') {
 7551:         $context = 'course';
 7552:         $rowcount = 0;
 7553:         foreach my $role ('st','ep','ta','in','cr') {
 7554:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
 7555:                                                    $numinrow,$rowcount);
 7556:             $$rowtotal ++;
 7557:             $rowcount ++;
 7558:         }
 7559:     }
 7560:     return $datatable;
 7561: }
 7562: 
 7563: sub print_defaults {
 7564:     my ($position,$dom,$settings,$rowtotal) = @_;
 7565:     my $rownum = 0;
 7566:     my ($datatable,$css_class,$titles);
 7567:     unless ($position eq 'bottom') {
 7568:         $titles = &defaults_titles($dom);
 7569:     }
 7570:     if ($position eq 'top') {
 7571:         my @items = ('auth_def','auth_arg_def','lang_def','timezone_def',
 7572:                      'datelocale_def','portal_def');
 7573:         my %defaults;
 7574:         if (ref($settings) eq 'HASH') {
 7575:             %defaults = %{$settings};
 7576:         } else {
 7577:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
 7578:             foreach my $item (@items) {
 7579:                 $defaults{$item} = $domdefaults{$item};
 7580:             }
 7581:         }
 7582:         foreach my $item (@items) {
 7583:             if ($rownum%2) {
 7584:                 $css_class = '';
 7585:             } else {
 7586:                 $css_class = ' class="LC_odd_row" ';
 7587:             }
 7588:             $datatable .= '<tr'.$css_class.'>'.
 7589:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
 7590:                           '</span></td><td class="LC_right_item" colspan="3">';
 7591:             if ($item eq 'auth_def') {
 7592:                 my @authtypes = ('internal','krb4','krb5','localauth');
 7593:                 my %shortauth = (
 7594:                                  internal => 'int',
 7595:                                  krb4 => 'krb4',
 7596:                                  krb5 => 'krb5',
 7597:                                  localauth  => 'loc'
 7598:                                 );
 7599:                 my %authnames = &authtype_names();
 7600:                 foreach my $auth (@authtypes) {
 7601:                     my $checked = ' ';
 7602:                     if ($defaults{$item} eq $auth) {
 7603:                         $checked = ' checked="checked" ';
 7604:                     }
 7605:                     $datatable .= '<label><input type="radio" name="'.$item.
 7606:                                   '" value="'.$auth.'"'.$checked.'/>'.
 7607:                                   $authnames{$shortauth{$auth}}.'</label>&nbsp;&nbsp;';
 7608:                 }
 7609:             } elsif ($item eq 'timezone_def') {
 7610:                 my $includeempty = 1;
 7611:                 $datatable .= &Apache::loncommon::select_timezone($item,$defaults{$item},undef,$includeempty);
 7612:             } elsif ($item eq 'datelocale_def') {
 7613:                 my $includeempty = 1;
 7614:                 $datatable .= &Apache::loncommon::select_datelocale($item,$defaults{$item},undef,$includeempty);
 7615:             } elsif ($item eq 'lang_def') {
 7616:                 my $includeempty = 1;
 7617:                 $datatable .= &Apache::loncommon::select_language($item,$defaults{$item},$includeempty);
 7618:             } else {
 7619:                 my $size;
 7620:                 if ($item eq 'portal_def') {
 7621:                     $size = ' size="25"';
 7622:                 }
 7623:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
 7624:                               $defaults{$item}.'"'.$size.' />';
 7625:             }
 7626:             $datatable .= '</td></tr>';
 7627:             $rownum ++;
 7628:         }
 7629:     } elsif ($position eq 'middle') {
 7630:         my %defaults;
 7631:         if (ref($settings) eq 'HASH') {
 7632:             if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
 7633:                 my $maxnum = @{$settings->{'inststatusorder'}};
 7634:                 for (my $i=0; $i<$maxnum; $i++) {
 7635:                     $css_class = $rownum%2?' class="LC_odd_row"':'';
 7636:                     my $item = $settings->{'inststatusorder'}->[$i];
 7637:                     my $title = $settings->{'inststatustypes'}->{$item};
 7638:                     my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'$item'".');"';
 7639:                     $datatable .= '<tr'.$css_class.'>'.
 7640:                                   '<td><span class="LC_nobreak">'.
 7641:                                   '<select name="inststatus_pos_'.$item.'"'.$chgstr.'>';
 7642:                     for (my $k=0; $k<=$maxnum; $k++) {
 7643:                         my $vpos = $k+1;
 7644:                         my $selstr;
 7645:                         if ($k == $i) {
 7646:                             $selstr = ' selected="selected" ';
 7647:                         }
 7648:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 7649:                     }
 7650:                     $datatable .= '</select>&nbsp;'.&mt('Internal ID:').'&nbsp;<b>'.$item.'</b>&nbsp;'.
 7651:                                   '<input type="checkbox" name="inststatus_delete" value="'.$item.'" />'.
 7652:                                   &mt('delete').'</span></td>'.
 7653:                                   '<td class="LC_left_item"><span class="LC_nobreak">'.&mt('Name displayed').':'.
 7654:                                   '<input type="text" size="20" name="inststatus_title_'.$item.'" value="'.$title.'" />'.
 7655:                                   '</span></td></tr>';
 7656:                 }
 7657:                 $css_class = $rownum%2?' class="LC_odd_row"':'';
 7658:                 my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'addinststatus_pos'".');"';
 7659:                 $datatable .= '<tr '.$css_class.'>'.
 7660:                               '<td><span class="LC_nobreak"><select name="addinststatus_pos"'.$chgstr.'>';
 7661:                 for (my $k=0; $k<=$maxnum; $k++) {
 7662:                     my $vpos = $k+1;
 7663:                     my $selstr;
 7664:                     if ($k == $maxnum) {
 7665:                         $selstr = ' selected="selected" ';
 7666:                     }
 7667:                     $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 7668:                 }
 7669:                 $datatable .= '</select>&nbsp;'.&mt('Internal ID:').
 7670:                               '<input type="text" size="10" name="addinststatus" value="" />'.
 7671:                               '&nbsp;'.&mt('(new)').
 7672:                               '</span></td><td class="LC_left_item"><span class="LC_nobreak">'.
 7673:                               &mt('Name displayed').':'.
 7674:                               '<input type="text" size="20" name="addinststatus_title" value="" /></span></td>'.
 7675:                               '</tr>'."\n";
 7676:                 $rownum ++;
 7677:             }
 7678:         }
 7679:     } else {
 7680:         my ($unamemaprules,$ruleorder) =
 7681:             &Apache::lonnet::inst_userrules($dom,'unamemap');
 7682:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 7683:         if ((ref($unamemaprules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 7684:             my $numinrow = 2;
 7685:             $datatable .= '<tr'.$css_class.'><td>'.&mt('Available conversions').'</td><td><table>'.
 7686:                           &user_formats_row('unamemap',$settings,$unamemaprules,
 7687:                                             $ruleorder,$numinrow).
 7688:                           '</table></td></tr>';
 7689:         }
 7690:         if ($datatable eq '') {
 7691:             $datatable .= '<tr'.$css_class.'><td colspan="2">'.
 7692:                           &mt('No rules set for domain in customized localenroll.pm').
 7693:                           '</td></tr>';
 7694:         }
 7695:     }
 7696:     $$rowtotal += $rownum;
 7697:     return $datatable;
 7698: }
 7699: 
 7700: sub get_languages_hash {
 7701:     my %langchoices;
 7702:     foreach my $id (&Apache::loncommon::languageids()) {
 7703:         my $code = &Apache::loncommon::supportedlanguagecode($id);
 7704:         if ($code ne '') {
 7705:             $langchoices{$code} =  &Apache::loncommon::plainlanguagedescription($id);
 7706:         }
 7707:     }
 7708:     return %langchoices;
 7709: }
 7710: 
 7711: sub defaults_titles {
 7712:     my ($dom) = @_;
 7713:     my %titles = &Apache::lonlocal::texthash (
 7714:                    'auth_def'      => 'Default authentication type',
 7715:                    'auth_arg_def'  => 'Default authentication argument',
 7716:                    'lang_def'      => 'Default language',
 7717:                    'timezone_def'  => 'Default timezone',
 7718:                    'datelocale_def' => 'Default locale for dates',
 7719:                    'portal_def'     => 'Portal/Default URL',
 7720:                    'intauth_cost'   => 'Encryption cost for bcrypt (positive integer)',
 7721:                    'intauth_check'  => 'Check bcrypt cost if authenticated',
 7722:                    'intauth_switch' => 'Existing crypt-based switched to bcrypt on authentication',
 7723:                  );
 7724:     if ($dom) {
 7725:         my $uprimary_id = &Apache::lonnet::domain($dom,'primary');
 7726:         my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 7727:         my $protocol = $Apache::lonnet::protocol{$uprimary_id};
 7728:         $protocol = 'http' if ($protocol ne 'https');
 7729:         if ($uint_dom) {
 7730:             $titles{'portal_def'} .= ' '.&mt('(for example: [_1])',$protocol.'://loncapa.'.
 7731:                                          $uint_dom);
 7732:         }
 7733:     }
 7734:     return (\%titles);
 7735: }
 7736: 
 7737: sub print_scantron {
 7738:     my ($r,$position,$dom,$confname,$settings,$rowtotal) = @_;
 7739:     if ($position eq 'top') {
 7740:         return &print_scantronformat($r,$dom,$confname,$settings,\$rowtotal);
 7741:     } else {
 7742:         return &print_scantronconfig($dom,$settings,\$rowtotal);
 7743:     }
 7744: }
 7745: 
 7746: sub scantron_javascript {
 7747:     return <<"ENDSCRIPT";
 7748: 
 7749: <script type="text/javascript">
 7750: // <![CDATA[
 7751: 
 7752: function toggleScantron(form) {
 7753:     var csvfieldset = new Array();
 7754:     if (document.getElementById('scantroncsv_cols')) {
 7755:         csvfieldset.push(document.getElementById('scantroncsv_cols'));
 7756:     }
 7757:     if (document.getElementById('scantroncsv_options')) {
 7758:         csvfieldset.push(document.getElementById('scantroncsv_options'));
 7759:     }
 7760:     if (csvfieldset.length) {
 7761:         if (document.getElementById('scantronconfcsv')) {
 7762:             var scantroncsv = document.getElementById('scantronconfcsv');
 7763:             if (scantroncsv.checked) {
 7764:                 for (var i=0; i<csvfieldset.length; i++) {
 7765:                     csvfieldset[i].style.display = 'block';
 7766:                 }
 7767:             } else {
 7768:                 for (var i=0; i<csvfieldset.length; i++) {
 7769:                     csvfieldset[i].style.display = 'none';
 7770:                 }
 7771:                 var csvselects = document.getElementsByClassName('scantronconfig_csv');
 7772:                 if (csvselects.length) {
 7773:                     for (var j=0; j<csvselects.length; j++) {
 7774:                         csvselects[j].selectedIndex = 0;
 7775:                     }
 7776:                 }
 7777:             }
 7778:         }
 7779:     }
 7780:     return;
 7781: }
 7782: // ]]>
 7783: </script>
 7784: 
 7785: ENDSCRIPT
 7786: 
 7787: }
 7788: 
 7789: sub print_scantronformat {
 7790:     my ($r,$dom,$confname,$settings,$rowtotal) = @_;
 7791:     my $itemcount = 1;
 7792:     my ($datatable,$css_class,$scantronurl,$is_custom,%error,%scantronurls,
 7793:         %confhash);
 7794:     my $switchserver = &check_switchserver($dom,$confname);
 7795:     my %lt = &Apache::lonlocal::texthash (
 7796:                 default => 'Default bubblesheet format file error',
 7797:                 custom  => 'Custom bubblesheet format file error',
 7798:              );
 7799:     my %scantronfiles = (
 7800:         default => 'default.tab',
 7801:         custom => 'custom.tab',
 7802:     );
 7803:     foreach my $key (keys(%scantronfiles)) {
 7804:         $scantronurls{$key} = '/res/'.$dom.'/'.$confname.'/scantron/'
 7805:                               .$scantronfiles{$key};
 7806:     }
 7807:     my @defaultinfo = &Apache::lonnet::stat_file($scantronurls{'default'});
 7808:     if ((!@defaultinfo) || ($defaultinfo[0] eq 'no_such_dir')) {
 7809:         if (!$switchserver) {
 7810:             my $servadm = $r->dir_config('lonAdmEMail');
 7811:             my ($configuserok,$author_ok) = &config_check($dom,$confname,$servadm);
 7812:             if ($configuserok eq 'ok') {
 7813:                 if ($author_ok eq 'ok') {
 7814:                     my %legacyfile = (
 7815:  default => $Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab',
 7816:  custom  => $Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab',
 7817:                     );
 7818:                     my %md5chk;
 7819:                     foreach my $type (keys(%legacyfile)) {
 7820:                         ($md5chk{$type}) = split(/ /,`md5sum $legacyfile{$type}`);
 7821:                         chomp($md5chk{$type});
 7822:                     }
 7823:                     if ($md5chk{'default'} ne $md5chk{'custom'}) {
 7824:                         foreach my $type (keys(%legacyfile)) {
 7825:                             ($scantronurls{$type},my $error) =
 7826:                                 &legacy_scantronformat($r,$dom,$confname,
 7827:                                                  $type,$legacyfile{$type},
 7828:                                                  $scantronurls{$type},
 7829:                                                  $scantronfiles{$type});
 7830:                             if ($error ne '') {
 7831:                                 $error{$type} = $error;
 7832:                             }
 7833:                         }
 7834:                         if (keys(%error) == 0) {
 7835:                             $is_custom = 1;
 7836:                             $confhash{'scantron'}{'scantronformat'} =
 7837:                                 $scantronurls{'custom'};
 7838:                             my $putresult =
 7839:                                 &Apache::lonnet::put_dom('configuration',
 7840:                                                          \%confhash,$dom);
 7841:                             if ($putresult ne 'ok') {
 7842:                                 $error{'custom'} =
 7843:                                     '<span class="LC_error">'.
 7844:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
 7845:                             }
 7846:                         }
 7847:                     } else {
 7848:                         ($scantronurls{'default'},my $error) =
 7849:                             &legacy_scantronformat($r,$dom,$confname,
 7850:                                           'default',$legacyfile{'default'},
 7851:                                           $scantronurls{'default'},
 7852:                                           $scantronfiles{'default'});
 7853:                         if ($error eq '') {
 7854:                             $confhash{'scantron'}{'scantronformat'} = ''; 
 7855:                             my $putresult =
 7856:                                 &Apache::lonnet::put_dom('configuration',
 7857:                                                          \%confhash,$dom);
 7858:                             if ($putresult ne 'ok') {
 7859:                                 $error{'default'} =
 7860:                                     '<span class="LC_error">'.
 7861:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
 7862:                             }
 7863:                         } else {
 7864:                             $error{'default'} = $error;
 7865:                         }
 7866:                     }
 7867:                 }
 7868:             }
 7869:         } else {
 7870:             $error{'default'} = &mt("Unable to copy default bubblesheet formatfile to domain's RES space: [_1]",$switchserver);
 7871:         }
 7872:     }
 7873:     if (ref($settings) eq 'HASH') {
 7874:         if ($settings->{'scantronformat'} eq "/res/$dom/$confname/scantron/custom.tab") {
 7875:             my @info = &Apache::lonnet::stat_file($settings->{'scantronformat'});
 7876:             if ((!@info) || ($info[0] eq 'no_such_dir')) {
 7877:                 $scantronurl = '';
 7878:             } else {
 7879:                 $scantronurl = $settings->{'scantronformat'};
 7880:             }
 7881:             $is_custom = 1;
 7882:         } else {
 7883:             $scantronurl = $scantronurls{'default'};
 7884:         }
 7885:     } else {
 7886:         if ($is_custom) {
 7887:             $scantronurl = $scantronurls{'custom'};
 7888:         } else {
 7889:             $scantronurl = $scantronurls{'default'};
 7890:         }
 7891:     }
 7892:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7893:     $datatable .= '<tr'.$css_class.'>';
 7894:     if (!$is_custom) {
 7895:         $datatable .= '<td>'.&mt('Default in use:').'<br />'.
 7896:                       '<span class="LC_nobreak">';
 7897:         if ($scantronurl) {
 7898:             $datatable .= &Apache::loncommon::modal_link($scantronurl,&mt('Default bubblesheet format file'),600,500,
 7899:                                                          undef,undef,undef,undef,'background-color:#ffffff');
 7900:         } else {
 7901:             $datatable = &mt('File unavailable for display');
 7902:         }
 7903:         $datatable .= '</span></td>';
 7904:         if (keys(%error) == 0) { 
 7905:             $datatable .= '<td valign="bottom">';
 7906:             if (!$switchserver) {
 7907:                 $datatable .= &mt('Upload:').'<br />';
 7908:             }
 7909:         } else {
 7910:             my $errorstr;
 7911:             foreach my $key (sort(keys(%error))) {
 7912:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
 7913:             }
 7914:             $datatable .= '<td>'.$errorstr;
 7915:         }
 7916:     } else {
 7917:         if (keys(%error) > 0) {
 7918:             my $errorstr;
 7919:             foreach my $key (sort(keys(%error))) {
 7920:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
 7921:             } 
 7922:             $datatable .= '<td>'.$errorstr.'</td><td>&nbsp;';
 7923:         } elsif ($scantronurl) {
 7924:             my $link =  &Apache::loncommon::modal_link($scantronurl,&mt('Custom bubblesheet format file'),600,500,
 7925:                                                        undef,undef,undef,undef,'background-color:#ffffff');
 7926:             $datatable .= '<td><span class="LC_nobreak">'.
 7927:                           $link.
 7928:                           '<label><input type="checkbox" name="scantronformat_del"'.
 7929:                           ' value="1" />'.&mt('Delete?').'</label></span></td>'.
 7930:                           '<td><span class="LC_nobreak">&nbsp;'.
 7931:                           &mt('Replace:').'</span><br />';
 7932:         }
 7933:     }
 7934:     if (keys(%error) == 0) {
 7935:         if ($switchserver) {
 7936:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 7937:         } else {
 7938:             $datatable .='<span class="LC_nobreak">&nbsp;'.
 7939:                          '<input type="file" name="scantronformat" /></span>';
 7940:         }
 7941:     }
 7942:     $datatable .= '</td></tr>';
 7943:     $$rowtotal ++;
 7944:     return $datatable;
 7945: }
 7946: 
 7947: sub legacy_scantronformat {
 7948:     my ($r,$dom,$confname,$file,$legacyfile,$newurl,$newfile) = @_;
 7949:     my ($url,$error);
 7950:     my @statinfo = &Apache::lonnet::stat_file($newurl);
 7951:     if ((!@statinfo) || ($statinfo[0] eq 'no_such_dir')) {
 7952:         (my $result,$url) =
 7953:             &publishlogo($r,'copy',$legacyfile,$dom,$confname,'scantron',
 7954:                          '','',$newfile);
 7955:         if ($result ne 'ok') {
 7956:             $error = &mt("An error occurred publishing the [_1] bubblesheet format file in RES space. Error was: [_2].",$newfile,$result);
 7957:         }
 7958:     }
 7959:     return ($url,$error);
 7960: }
 7961: 
 7962: sub print_scantronconfig {
 7963:     my ($dom,$settings,$rowtotal) = @_;
 7964:     my $itemcount = 2;
 7965:     my $is_checked = ' checked="checked"';
 7966:     my %optionson = (
 7967:                      hdr => ' checked="checked"',
 7968:                      pad => ' checked="checked"',
 7969:                      rem => ' checked="checked"',
 7970:                     );
 7971:     my %optionsoff = (
 7972:                       hdr => '',
 7973:                       pad => '',
 7974:                       rem => '',
 7975:                      );
 7976:     my $currcsvsty = 'none';
 7977:     my ($datatable,%csvfields,%checked,%onclick,%csvoptions);
 7978:     my @fields = &scantroncsv_fields();
 7979:     my %titles = &scantronconfig_titles();
 7980:     if (ref($settings) eq 'HASH') {
 7981:         if (ref($settings->{config}) eq 'HASH') {
 7982:             if ($settings->{config}->{dat}) {
 7983:                 $checked{'dat'} = $is_checked;
 7984:             }
 7985:             if (ref($settings->{config}->{csv}) eq 'HASH') {
 7986:                 if (ref($settings->{config}->{csv}->{fields}) eq 'HASH') {
 7987:                     %csvfields = %{$settings->{config}->{csv}->{fields}};
 7988:                     if (keys(%csvfields) > 0) {
 7989:                         $checked{'csv'} = $is_checked;
 7990:                         $currcsvsty = 'block';
 7991:                     }
 7992:                 }
 7993:                 if (ref($settings->{config}->{csv}->{options}) eq 'HASH') {
 7994:                     %csvoptions = %{$settings->{config}->{csv}->{options}};
 7995:                     foreach my $option (keys(%optionson)) {
 7996:                         unless ($csvoptions{$option}) {
 7997:                             $optionsoff{$option} = $optionson{$option};
 7998:                             $optionson{$option} = '';
 7999:                         }
 8000:                     }
 8001:                 }
 8002:             }
 8003:         } else {
 8004:             $checked{'dat'} = $is_checked;
 8005:         }
 8006:     } else {
 8007:         $checked{'dat'} = $is_checked;
 8008:     }
 8009:     $onclick{'csv'} = ' onclick="toggleScantron(this.form);"';
 8010:     my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
 8011:     $datatable = '<tr '.$css_class.'><td>'.&mt('Supported formats').'</td>'.
 8012:                  '<td class="LC_left_item" valign="top"><span class="LC_nobreak">';
 8013:     foreach my $item ('dat','csv') {
 8014:         my $id;
 8015:         if ($item eq 'csv') {
 8016:             $id = 'id="scantronconfcsv" ';
 8017:         }
 8018:         $datatable .= '<label><input type="checkbox" name="scantronconfig" '.$id.'value="'.$item.'"'.$checked{$item}.$onclick{$item}.' />'.
 8019:                       $titles{$item}.'</label>'.('&nbsp;'x3);
 8020:         if ($item eq 'csv') {
 8021:             $datatable .= '<fieldset style="display:'.$currcsvsty.'" id="scantroncsv_cols">'.
 8022:                           '<legend>'.&mt('CSV Column Mapping').'</legend>'.
 8023:                           '<table><tr><th>'.&mt('Field').'</th><th>'.&mt('Location').'</th></tr>'."\n";
 8024:             foreach my $col (@fields) {
 8025:                 my $selnone;
 8026:                 if ($csvfields{$col} eq '') {
 8027:                     $selnone = ' selected="selected"';
 8028:                 }
 8029:                 $datatable .= '<tr><td>'.$titles{$col}.'</td>'.
 8030:                               '<td><select name="scantronconfig_csv_'.$col.'" class="scantronconfig_csv">'.
 8031:                               '<option value=""'.$selnone.'></option>';
 8032:                 for (my $i=0; $i<20; $i++) {
 8033:                     my $shown = $i+1;
 8034:                     my $sel;
 8035:                     unless ($selnone) {
 8036:                         if (exists($csvfields{$col})) {
 8037:                             if ($csvfields{$col} == $i) {
 8038:                                 $sel = ' selected="selected"';
 8039:                             }
 8040:                         }
 8041:                     }
 8042:                     $datatable .= '<option value="'.$i.'"'.$sel.'>'.$shown.'</option>';
 8043:                 }
 8044:                 $datatable .= '</select></td></tr>';
 8045:            }
 8046:            $datatable .= '</table></fieldset>'.
 8047:                          '<fieldset style="display:'.$currcsvsty.'" id="scantroncsv_options">'.
 8048:                          '<legend>'.&mt('CSV Options').'</legend>';
 8049:            foreach my $option ('hdr','pad','rem') {
 8050:                $datatable .= '<span class="LC_nobreak">'.$titles{$option}.':'.
 8051:                          '<label><input type="radio" name="scantroncsv_'.$option.'" value="1"'.$optionson{$option}.' />'.
 8052:                          &mt('Yes').'</label>'.('&nbsp;'x2)."\n".
 8053:                          '<label><input type="radio" name="scantroncsv_'.$option.'" value="0"'.$optionsoff{$option}.' />'.&mt('No').'</label></span><br />';
 8054:            }
 8055:            $datatable .= '</fieldset>';
 8056:            $itemcount ++;
 8057:         }
 8058:     }
 8059:     $datatable .= '</td></tr>';
 8060:     $$rowtotal ++;
 8061:     return $datatable;
 8062: }
 8063: 
 8064: sub scantronconfig_titles {
 8065:     return &Apache::lonlocal::texthash(
 8066:                                           dat => 'Standard format (.dat)',
 8067:                                           csv => 'Comma separated values (.csv)',
 8068:                                           hdr => 'Remove first line in file (contains column titles)',
 8069:                                           pad => 'Prepend 0s to PaperID',
 8070:                                           rem => 'Remove leading spaces (except Question Response columns)',
 8071:                                           CODE => 'CODE',
 8072:                                           ID   => 'Student ID',
 8073:                                           PaperID => 'Paper ID',
 8074:                                           FirstName => 'First Name',
 8075:                                           LastName => 'Last Name',
 8076:                                           FirstQuestion => 'First Question Response',
 8077:                                           Section => 'Section',
 8078:     );
 8079: }
 8080: 
 8081: sub scantroncsv_fields {
 8082:     return ('PaperID','LastName','FirstName','ID','Section','CODE','FirstQuestion');
 8083: }
 8084: 
 8085: sub print_coursecategories {
 8086:     my ($position,$dom,$hdritem,$settings,$rowtotal) = @_;
 8087:     my $datatable;
 8088:     if ($position eq 'top') {
 8089:         my (%checked);
 8090:         my @catitems = ('unauth','auth');
 8091:         my @cattypes = ('std','domonly','codesrch','none');
 8092:         $checked{'unauth'} = 'std';
 8093:         $checked{'auth'} = 'std';
 8094:         if (ref($settings) eq 'HASH') {
 8095:             foreach my $type (@cattypes) {
 8096:                 if ($type eq $settings->{'unauth'}) {
 8097:                     $checked{'unauth'} = $type;
 8098:                 }
 8099:                 if ($type eq $settings->{'auth'}) {
 8100:                     $checked{'auth'} = $type;
 8101:                 }
 8102:             }
 8103:         }
 8104:         my %lt = &Apache::lonlocal::texthash (
 8105:                                                unauth   => 'Catalog type for unauthenticated users',
 8106:                                                auth     => 'Catalog type for authenticated users',
 8107:                                                none     => 'No catalog',
 8108:                                                std      => 'Standard catalog',
 8109:                                                domonly  => 'Domain-only catalog',
 8110:                                                codesrch => "Code search form",
 8111:                                              );
 8112:        my $itemcount = 0;
 8113:        foreach my $item (@catitems) {
 8114:            my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
 8115:            $datatable .= '<tr '.$css_class.'>'.
 8116:                          '<td>'.$lt{$item}.'</td>'.
 8117:                          '<td class="LC_right_item"><span class="LC_nobreak">';
 8118:            foreach my $type (@cattypes) {
 8119:                my $ischecked;
 8120:                if ($checked{$item} eq $type) {
 8121:                    $ischecked=' checked="checked"';
 8122:                }
 8123:                $datatable .= '<label>'.
 8124:                              '<input type="radio" name="coursecat_'.$item.'" value="'.$type.'"'.$ischecked.
 8125:                              ' />'.$lt{$type}.'</label>&nbsp;';
 8126:            }
 8127:            $datatable .= '</span></td></tr>';
 8128:            $itemcount ++;
 8129:         }
 8130:         $$rowtotal += $itemcount;
 8131:     } elsif ($position eq 'middle') {
 8132:         my $toggle_cats_crs = ' ';
 8133:         my $toggle_cats_dom = ' checked="checked" ';
 8134:         my $can_cat_crs = ' ';
 8135:         my $can_cat_dom = ' checked="checked" ';
 8136:         my $toggle_catscomm_comm = ' ';
 8137:         my $toggle_catscomm_dom = ' checked="checked" ';
 8138:         my $can_catcomm_comm = ' ';
 8139:         my $can_catcomm_dom = ' checked="checked" ';
 8140: 
 8141:         if (ref($settings) eq 'HASH') {
 8142:             if ($settings->{'togglecats'} eq 'crs') {
 8143:                 $toggle_cats_crs = $toggle_cats_dom;
 8144:                 $toggle_cats_dom = ' ';
 8145:             }
 8146:             if ($settings->{'categorize'} eq 'crs') {
 8147:                 $can_cat_crs = $can_cat_dom;
 8148:                 $can_cat_dom = ' ';
 8149:             }
 8150:             if ($settings->{'togglecatscomm'} eq 'comm') {
 8151:                 $toggle_catscomm_comm = $toggle_catscomm_dom;
 8152:                 $toggle_catscomm_dom = ' ';
 8153:             }
 8154:             if ($settings->{'categorizecomm'} eq 'comm') {
 8155:                 $can_catcomm_comm = $can_catcomm_dom;
 8156:                 $can_catcomm_dom = ' ';
 8157:             }
 8158:         }
 8159:         my %title = &Apache::lonlocal::texthash (
 8160:                      togglecats     => 'Show/Hide a course in catalog',
 8161:                      togglecatscomm => 'Show/Hide a community in catalog',
 8162:                      categorize     => 'Assign a category to a course',
 8163:                      categorizecomm => 'Assign a category to a community',
 8164:                     );
 8165:         my %level = &Apache::lonlocal::texthash (
 8166:                      dom  => 'Set in Domain',
 8167:                      crs  => 'Set in Course',
 8168:                      comm => 'Set in Community',
 8169:                     );
 8170:         $datatable = '<tr class="LC_odd_row">'.
 8171:                   '<td>'.$title{'togglecats'}.'</td>'.
 8172:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 8173:                   '<input type="radio" name="togglecats"'.
 8174:                   $toggle_cats_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 8175:                   '<label><input type="radio" name="togglecats"'.
 8176:                   $toggle_cats_crs.' value="crs" />'.$level{'crs'}.'</label></span></td>'.
 8177:                   '</tr><tr>'.
 8178:                   '<td>'.$title{'categorize'}.'</td>'.
 8179:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 8180:                   '<label><input type="radio" name="categorize"'.
 8181:                   $can_cat_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 8182:                   '<label><input type="radio" name="categorize"'.
 8183:                   $can_cat_crs.'value="crs" />'.$level{'crs'}.'</label></span></td>'.
 8184:                   '</tr><tr class="LC_odd_row">'.
 8185:                   '<td>'.$title{'togglecatscomm'}.'</td>'.
 8186:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 8187:                   '<input type="radio" name="togglecatscomm"'.
 8188:                   $toggle_catscomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 8189:                   '<label><input type="radio" name="togglecatscomm"'.
 8190:                   $toggle_catscomm_comm.' value="comm" />'.$level{'comm'}.'</label></span></td>'.
 8191:                   '</tr><tr>'.
 8192:                   '<td>'.$title{'categorizecomm'}.'</td>'.
 8193:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 8194:                   '<label><input type="radio" name="categorizecomm"'.
 8195:                   $can_catcomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 8196:                   '<label><input type="radio" name="categorizecomm"'.
 8197:                   $can_catcomm_comm.'value="comm" />'.$level{'comm'}.'</label></span></td>'.
 8198:                   '</tr>';
 8199:         $$rowtotal += 4;
 8200:     } else {
 8201:         my $css_class;
 8202:         my $itemcount = 1;
 8203:         my $cathash; 
 8204:         if (ref($settings) eq 'HASH') {
 8205:             $cathash = $settings->{'cats'};
 8206:         }
 8207:         if (ref($cathash) eq 'HASH') {
 8208:             my (@cats,@trails,%allitems,%idx,@jsarray);
 8209:             &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,
 8210:                                                    \%allitems,\%idx,\@jsarray);
 8211:             my $maxdepth = scalar(@cats);
 8212:             my $colattrib = '';
 8213:             if ($maxdepth > 2) {
 8214:                 $colattrib = ' colspan="2" ';
 8215:             }
 8216:             my @path;
 8217:             if (@cats > 0) {
 8218:                 if (ref($cats[0]) eq 'ARRAY') {
 8219:                     my $numtop = @{$cats[0]};
 8220:                     my $maxnum = $numtop;
 8221:                     my %default_names = (
 8222:                           instcode    => &mt('Official courses'),
 8223:                           communities => &mt('Communities'),
 8224:                     );
 8225: 
 8226:                     if ((!grep(/^instcode$/,@{$cats[0]})) || 
 8227:                         ($cathash->{'instcode::0'} eq '') ||
 8228:                         (!grep(/^communities$/,@{$cats[0]})) || 
 8229:                         ($cathash->{'communities::0'} eq '')) {
 8230:                         $maxnum ++;
 8231:                     }
 8232:                     my $lastidx;
 8233:                     for (my $i=0; $i<$numtop; $i++) {
 8234:                         my $parent = $cats[0][$i];
 8235:                         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8236:                         my $item = &escape($parent).'::0';
 8237:                         my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$item','$idx{$item}'".');"';
 8238:                         $lastidx = $idx{$item};
 8239:                         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 8240:                                       .'<select name="'.$item.'"'.$chgstr.'>';
 8241:                         for (my $k=0; $k<=$maxnum; $k++) {
 8242:                             my $vpos = $k+1;
 8243:                             my $selstr;
 8244:                             if ($k == $i) {
 8245:                                 $selstr = ' selected="selected" ';
 8246:                             }
 8247:                             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 8248:                         }
 8249:                         $datatable .= '</select></span></td><td>';
 8250:                         if ($parent eq 'instcode' || $parent eq 'communities') {
 8251:                             $datatable .=  '<span class="LC_nobreak">'
 8252:                                            .$default_names{$parent}.'</span>';
 8253:                             if ($parent eq 'instcode') {
 8254:                                 $datatable .= '<br /><span class="LC_nobreak">('
 8255:                                               .&mt('with institutional codes')
 8256:                                               .')</span></td><td'.$colattrib.'>';
 8257:                             } else {
 8258:                                 $datatable .= '<table><tr><td>';
 8259:                             }
 8260:                             $datatable .= '<span class="LC_nobreak">'
 8261:                                           .'<label><input type="radio" name="'
 8262:                                           .$parent.'" value="1" checked="checked" />'
 8263:                                           .&mt('Display').'</label>';
 8264:                             if ($parent eq 'instcode') {
 8265:                                 $datatable .= '&nbsp;';
 8266:                             } else {
 8267:                                 $datatable .= '</span></td></tr><tr><td>'
 8268:                                               .'<span class="LC_nobreak">';
 8269:                             }
 8270:                             $datatable .= '<label><input type="radio" name="'
 8271:                                           .$parent.'" value="0" />'
 8272:                                           .&mt('Do not display').'</label></span>';
 8273:                             if ($parent eq 'communities') {
 8274:                                 $datatable .= '</td></tr></table>';
 8275:                             }
 8276:                             $datatable .= '</td>';
 8277:                         } else {
 8278:                             $datatable .= $parent
 8279:                                           .'&nbsp;<span class="LC_nobreak"><label>'
 8280:                                           .'<input type="checkbox" name="deletecategory" '
 8281:                                           .'value="'.$item.'" />'.&mt('Delete').'</label></span></td>';
 8282:                         }
 8283:                         my $depth = 1;
 8284:                         push(@path,$parent);
 8285:                         $datatable .= &build_category_rows($itemcount,\@cats,$depth,$parent,\@path,\%idx);
 8286:                         pop(@path);
 8287:                         $datatable .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
 8288:                         $itemcount ++;
 8289:                     }
 8290:                     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8291:                     my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','$lastidx'".');"';
 8292:                     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="addcategory_pos"'.$chgstr.'>';
 8293:                     for (my $k=0; $k<=$maxnum; $k++) {
 8294:                         my $vpos = $k+1;
 8295:                         my $selstr;
 8296:                         if ($k == $numtop) {
 8297:                             $selstr = ' selected="selected" ';
 8298:                         }
 8299:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 8300:                     }
 8301:                     $datatable .= '</select></span></td><td colspan="2">'.&mt('Add category:').'&nbsp;'
 8302:                                   .'<input type="text" size="20" name="addcategory_name" value="" /></td>'
 8303:                                   .'</tr>'."\n";
 8304:                     $itemcount ++;
 8305:                     foreach my $default ('instcode','communities') {
 8306:                         if ((!grep(/^\Q$default\E$/,@{$cats[0]})) || ($cathash->{$default.'::0'} eq '')) {
 8307:                             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8308:                             my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','$lastidx'".');"';
 8309:                             $datatable .= '<tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr><tr '.$css_class.'><td>'.
 8310:                                           '<span class="LC_nobreak"><select name="'.$default.'_pos"'.$chgstr.'>';
 8311:                             for (my $k=0; $k<=$maxnum; $k++) {
 8312:                                 my $vpos = $k+1;
 8313:                                 my $selstr;
 8314:                                 if ($k == $maxnum) {
 8315:                                     $selstr = ' selected="selected" ';
 8316:                                 }
 8317:                                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 8318:                             }
 8319:                             $datatable .= '</select></span></td>'.
 8320:                                           '<td><span class="LC_nobreak">'.
 8321:                                           $default_names{$default}.'</span>';
 8322:                             if ($default eq 'instcode') {
 8323:                                 $datatable .= '<br /><span class="LC_nobreak">(' 
 8324:                                               .&mt('with institutional codes').')</span>';
 8325:                             }
 8326:                             $datatable .= '</td>'
 8327:                                           .'<td><span class="LC_nobreak"><label><input type="radio" name="'.$default.'" value="1" />'
 8328:                                           .&mt('Display').'</label>&nbsp;'
 8329:                                           .'<label><input type="radio" name="'.$default.'" value="0" checked="checked"/>'
 8330:                                           .&mt('Do not display').'</label></span></td></tr>';
 8331:                         }
 8332:                     }
 8333:                 }
 8334:             } else {
 8335:                 $datatable .= &initialize_categories($itemcount);
 8336:             }
 8337:         } else {
 8338:             $datatable .= '<tr><td class="LC_right_item">'.$hdritem->{'header'}->[1]->{'col2'}.'</td></tr>'
 8339:                           .&initialize_categories($itemcount);
 8340:         }
 8341:         $$rowtotal += $itemcount;
 8342:     }
 8343:     return $datatable;
 8344: }
 8345: 
 8346: sub print_serverstatuses {
 8347:     my ($dom,$settings,$rowtotal) = @_;
 8348:     my $datatable;
 8349:     my @pages = &serverstatus_pages();
 8350:     my (%namedaccess,%machineaccess);
 8351:     foreach my $type (@pages) {
 8352:         $namedaccess{$type} = '';
 8353:         $machineaccess{$type}= '';
 8354:     }
 8355:     if (ref($settings) eq 'HASH') {
 8356:         foreach my $type (@pages) {
 8357:             if (exists($settings->{$type})) {
 8358:                 if (ref($settings->{$type}) eq 'HASH') {
 8359:                     foreach my $key (keys(%{$settings->{$type}})) {
 8360:                         if ($key eq 'namedusers') {
 8361:                             $namedaccess{$type} = $settings->{$type}->{$key};
 8362:                         } elsif ($key eq 'machines') {
 8363:                             $machineaccess{$type} = $settings->{$type}->{$key};
 8364:                         }
 8365:                     }
 8366:                 }
 8367:             }
 8368:         }
 8369:     }
 8370:     my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
 8371:     my $rownum = 0;
 8372:     my $css_class;
 8373:     foreach my $type (@pages) {
 8374:         $rownum ++;
 8375:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 8376:         $datatable .= '<tr'.$css_class.'>'.
 8377:                       '<td><span class="LC_nobreak">'.
 8378:                       $titles->{$type}.'</span></td>'.
 8379:                       '<td class="LC_left_item">'.
 8380:                       '<input type="text" name="'.$type.'_namedusers" '.
 8381:                       'value="'.$namedaccess{$type}.'" size="30" /></td>'.
 8382:                       '<td class="LC_right_item">'.
 8383:                       '<span class="LC_nobreak">'.
 8384:                       '<input type="text" name="'.$type.'_machines" '.
 8385:                       'value="'.$machineaccess{$type}.'" size="10" />'.
 8386:                       '</span></td></tr>'."\n";
 8387:     }
 8388:     $$rowtotal += $rownum;
 8389:     return $datatable;
 8390: }
 8391: 
 8392: sub serverstatus_pages {
 8393:     return ('userstatus','lonstatus','loncron','server-status','codeversions',
 8394:             'checksums','clusterstatus','metadata_keywords','metadata_harvest',
 8395:             'takeoffline','takeonline','showenv','toggledebug','ping','domconf',
 8396:             'uniquecodes','diskusage','coursecatalog');
 8397: }
 8398: 
 8399: sub defaults_javascript {
 8400:     my ($settings) = @_;
 8401:     return unless (ref($settings) eq 'HASH');
 8402:     if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
 8403:         my $maxnum = scalar(@{$settings->{'inststatusorder'}});
 8404:         if ($maxnum eq '') {
 8405:             $maxnum = 0;
 8406:         }
 8407:         $maxnum ++;
 8408:         my $jstext = '    var inststatuses = Array('."'".join("','",@{$settings->{'inststatusorder'}})."'".');';  
 8409:         return <<"ENDSCRIPT";
 8410: <script type="text/javascript">
 8411: // <![CDATA[
 8412: function reorderTypes(form,caller) {
 8413:     var changedVal;
 8414: $jstext 
 8415:     var newpos = 'addinststatus_pos';
 8416:     var current = new Array;
 8417:     var maxh = $maxnum;
 8418:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 8419:     var oldVal;
 8420:     if (caller == newpos) {
 8421:         changedVal = newitemVal;
 8422:     } else {
 8423:         var curritem = 'inststatus_pos_'+caller;
 8424:         changedVal = form.elements[curritem].options[form.elements[curritem].selectedIndex].value;
 8425:         current[newitemVal] = newpos;
 8426:     }
 8427:     for (var i=0; i<inststatuses.length; i++) {
 8428:         if (inststatuses[i] != caller) {
 8429:             var elementName = 'inststatus_pos_'+inststatuses[i];
 8430:             if (form.elements[elementName]) {
 8431:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 8432:                 current[currVal] = elementName;
 8433:             }
 8434:         }
 8435:     }
 8436:     for (var j=0; j<maxh; j++) {
 8437:         if (current[j] == undefined) {
 8438:             oldVal = j;
 8439:         }
 8440:     }
 8441:     if (oldVal < changedVal) {
 8442:         for (var k=oldVal+1; k<=changedVal ; k++) {
 8443:            var elementName = current[k];
 8444:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 8445:         }
 8446:     } else {
 8447:         for (var k=changedVal; k<oldVal; k++) {
 8448:             var elementName = current[k];
 8449:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 8450:         }
 8451:     }
 8452:     return;
 8453: }
 8454: 
 8455: // ]]>
 8456: </script>
 8457: 
 8458: ENDSCRIPT
 8459:     }
 8460: }
 8461: 
 8462: sub passwords_javascript {
 8463:     my %intalert = &Apache::lonlocal::texthash (
 8464:         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.',
 8465:         authcost => 'Warning: bcrypt encryption cost for internal authentication must be an integer.',
 8466:         passmin => 'Warning: minimum password length must be a positive integer greater than 6.',
 8467:         passmax => 'Warning: maximum password length must be a positive integer (or blank).',
 8468:         passexp => 'Warning: days before password expiration must be a positive integer (or blank).',
 8469:         passnum => 'Warning: number of previous passwords to save must be a positive integer (or blank).',
 8470:     );
 8471:     &js_escape(\%intalert);
 8472:     my $defmin = $Apache::lonnet::passwdmin;
 8473:     my $intauthjs = <<"ENDSCRIPT";
 8474: 
 8475: function warnIntAuth(field) {
 8476:     if (field.name == 'intauth_check') {
 8477:         if (field.value == '2') {
 8478:             alert('$intalert{authcheck}');
 8479:         }
 8480:     }
 8481:     if (field.name == 'intauth_cost') {
 8482:         field.value.replace(/\s/g,'');
 8483:         if (field.value != '') {
 8484:             var regexdigit=/^\\d+\$/;
 8485:             if (!regexdigit.test(field.value)) {
 8486:                 alert('$intalert{authcost}');
 8487:             }
 8488:         }
 8489:     }
 8490:     return;
 8491: }
 8492: 
 8493: function warnIntPass(field) {
 8494:     field.value.replace(/^\s+/,'');
 8495:     field.value.replace(/\s+\$/,'');
 8496:     var regexdigit=/^\\d+\$/;
 8497:     if (field.name == 'passwords_min') {
 8498:         if (field.value == '') {
 8499:             alert('$intalert{passmin}');
 8500:             field.value = '$defmin';
 8501:         } else {
 8502:             if (!regexdigit.test(field.value)) {
 8503:                 alert('$intalert{passmin}');
 8504:                 field.value = '$defmin';
 8505:             }
 8506:             var minval = parseInt(field.value,10);
 8507:             if (minval < $defmin) {
 8508:                 alert('$intalert{passmin}');
 8509:                 field.value = '$defmin';
 8510:             }
 8511:         }
 8512:     } else {
 8513:         if (field.value == '0') {
 8514:             field.value = '';
 8515:         }
 8516:         if (field.value != '') {
 8517:             if (field.name == 'passwords_expire') {
 8518:                 var regexpposnum=/^\\d+(|\\.\\d*)\$/;
 8519:                 if (!regexpposnum.test(field.value)) {
 8520:                     alert('$intalert{passexp}');
 8521:                     field.value = '';
 8522:                 } else {
 8523:                     var expval = parseFloat(field.value);
 8524:                     if (expval == 0) {
 8525:                         alert('$intalert{passexp}');
 8526:                         field.value = '';
 8527:                     }
 8528:                 }
 8529:             } else {
 8530:                 if (!regexdigit.test(field.value)) {
 8531:                     if (field.name == 'passwords_max') {
 8532:                         alert('$intalert{passmax}');
 8533:                     } else {
 8534:                         if (field.name == 'passwords_numsaved') {
 8535:                             alert('$intalert{passnum}');
 8536:                         }
 8537:                     }
 8538:                     field.value = '';
 8539:                 }
 8540:             }
 8541:         }
 8542:     }
 8543:     return;
 8544: }
 8545: 
 8546: ENDSCRIPT
 8547:     return &Apache::lonhtmlcommon::scripttag($intauthjs);
 8548: }
 8549: 
 8550: sub coursecategories_javascript {
 8551:     my ($settings) = @_;
 8552:     my ($output,$jstext,$cathash);
 8553:     if (ref($settings) eq 'HASH') {
 8554:         $cathash = $settings->{'cats'};
 8555:     }
 8556:     if (ref($cathash) eq 'HASH') {
 8557:         my (@cats,@jsarray,%idx);
 8558:         &Apache::loncommon::gather_categories($cathash,\@cats,\%idx,\@jsarray);
 8559:         if (@jsarray > 0) {
 8560:             $jstext = '    var categories = Array('.scalar(@jsarray).');'."\n";
 8561:             for (my $i=0; $i<@jsarray; $i++) {
 8562:                 if (ref($jsarray[$i]) eq 'ARRAY') {
 8563:                     my $catstr = join('","',@{$jsarray[$i]});
 8564:                     $jstext .= '    categories['.$i.'] = Array("'.$catstr.'");'."\n";
 8565:                 }
 8566:             }
 8567:         }
 8568:     } else {
 8569:         $jstext  = '    var categories = Array(1);'."\n".
 8570:                    '    categories[0] = Array("instcode_pos");'."\n"; 
 8571:     }
 8572:     my $instcode_reserved = &mt('The name: [_1] is a reserved category.','"instcode"');
 8573:     my $communities_reserved = &mt('The name: [_1] is a reserved category.','"communities"');
 8574:     my $choose_again = "\n".&mt('Please use a different name for the new top level category.'); 
 8575:     &js_escape(\$instcode_reserved);
 8576:     &js_escape(\$communities_reserved);
 8577:     &js_escape(\$choose_again);
 8578:     $output = <<"ENDSCRIPT";
 8579: <script type="text/javascript">
 8580: // <![CDATA[
 8581: function reorderCats(form,parent,item,idx) {
 8582:     var changedVal;
 8583: $jstext
 8584:     var newpos = 'addcategory_pos';
 8585:     if (parent == '') {
 8586:         var has_instcode = 0;
 8587:         var maxtop = categories[idx].length;
 8588:         for (var j=0; j<maxtop; j++) {
 8589:             if (categories[idx][j] == 'instcode::0') {
 8590:                 has_instcode == 1;
 8591:             }
 8592:         }
 8593:         if (has_instcode == 0) {
 8594:             categories[idx][maxtop] = 'instcode_pos';
 8595:         }
 8596:     } else {
 8597:         newpos += '_'+parent;
 8598:     }
 8599:     var maxh = 1 + categories[idx].length;
 8600:     var current = new Array;
 8601:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 8602:     if (item == newpos) {
 8603:         changedVal = newitemVal;
 8604:     } else {
 8605:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 8606:         current[newitemVal] = newpos;
 8607:     }
 8608:     for (var i=0; i<categories[idx].length; i++) {
 8609:         var elementName = categories[idx][i];
 8610:         if (elementName != item) {
 8611:             if (form.elements[elementName]) {
 8612:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 8613:                 current[currVal] = elementName;
 8614:             }
 8615:         }
 8616:     }
 8617:     var oldVal;
 8618:     for (var j=0; j<maxh; j++) {
 8619:         if (current[j] == undefined) {
 8620:             oldVal = j;
 8621:         }
 8622:     }
 8623:     if (oldVal < changedVal) {
 8624:         for (var k=oldVal+1; k<=changedVal ; k++) {
 8625:            var elementName = current[k];
 8626:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 8627:         }
 8628:     } else {
 8629:         for (var k=changedVal; k<oldVal; k++) {
 8630:             var elementName = current[k];
 8631:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 8632:         }
 8633:     }
 8634:     return;
 8635: }
 8636: 
 8637: function categoryCheck(form) {
 8638:     if (form.elements['addcategory_name'].value == 'instcode') {
 8639:         alert('$instcode_reserved\\n$choose_again');
 8640:         return false;
 8641:     }
 8642:     if (form.elements['addcategory_name'].value == 'communities') {
 8643:         alert('$communities_reserved\\n$choose_again');
 8644:         return false;
 8645:     }
 8646:     return true;
 8647: }
 8648: 
 8649: // ]]>
 8650: </script>
 8651: 
 8652: ENDSCRIPT
 8653:     return $output;
 8654: }
 8655: 
 8656: sub initialize_categories {
 8657:     my ($itemcount) = @_;
 8658:     my ($datatable,$css_class,$chgstr);
 8659:     my %default_names = &Apache::lonlocal::texthash (
 8660:                       instcode    => 'Official courses (with institutional codes)',
 8661:                       communities => 'Communities',
 8662:                         );
 8663:     my $select0 = ' selected="selected"';
 8664:     my $select1 = '';
 8665:     foreach my $default ('instcode','communities') {
 8666:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8667:         $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','0'".');"';
 8668:         if ($default eq 'communities') {
 8669:             $select1 = $select0;
 8670:             $select0 = '';
 8671:         }
 8672:         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 8673:                      .'<select name="'.$default.'_pos">'
 8674:                      .'<option value="0"'.$select0.'>1</option>'
 8675:                      .'<option value="1"'.$select1.'>2</option>'
 8676:                      .'<option value="2">3</option></select>&nbsp;'
 8677:                      .$default_names{$default}
 8678:                      .'</span></td><td><span class="LC_nobreak">'
 8679:                      .'<label><input type="radio" name="'.$default.'" value="1" checked="checked" />'
 8680:                      .&mt('Display').'</label>&nbsp;<label>'
 8681:                      .'<input type="radio" name="'.$default.'" value="0" />'.&mt('Do not display')
 8682:                  .'</label></span></td></tr>';
 8683:         $itemcount ++;
 8684:     }
 8685:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8686:     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','0'".');"';
 8687:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 8688:                   .'<select name="addcategory_pos"'.$chgstr.'>'
 8689:                   .'<option value="0">1</option>'
 8690:                   .'<option value="1">2</option>'
 8691:                   .'<option value="2" selected="selected">3</option></select>&nbsp;'
 8692:                   .&mt('Add category').'</span></td><td><span class="LC_nobreak">'.&mt('Name:')
 8693:                   .'&nbsp;<input type="text" size="20" name="addcategory_name" value="" /></span>'
 8694:                   .'</td></tr>';
 8695:     return $datatable;
 8696: }
 8697: 
 8698: sub build_category_rows {
 8699:     my ($itemcount,$cats,$depth,$parent,$path,$idx) = @_;
 8700:     my ($text,$name,$item,$chgstr);
 8701:     if (ref($cats) eq 'ARRAY') {
 8702:         my $maxdepth = scalar(@{$cats});
 8703:         if (ref($cats->[$depth]) eq 'HASH') {
 8704:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
 8705:                 my $numchildren = @{$cats->[$depth]{$parent}};
 8706:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8707:                 $text .= '<td><table class="LC_data_table">';
 8708:                 my ($idxnum,$parent_name,$parent_item);
 8709:                 my $higher = $depth - 1;
 8710:                 if ($higher == 0) {
 8711:                     $parent_name = &escape($parent).'::'.$higher;
 8712:                 } else {
 8713:                     if (ref($path) eq 'ARRAY') {
 8714:                         $parent_name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
 8715:                     }
 8716:                 }
 8717:                 $parent_item = 'addcategory_pos_'.$parent_name;
 8718:                 for (my $j=0; $j<=$numchildren; $j++) {
 8719:                     if ($j < $numchildren) {
 8720:                         $name = $cats->[$depth]{$parent}[$j];
 8721:                         $item = &escape($name).':'.&escape($parent).':'.$depth;
 8722:                         $idxnum = $idx->{$item};
 8723:                     } else {
 8724:                         $name = $parent_name;
 8725:                         $item = $parent_item;
 8726:                     }
 8727:                     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'$parent_name','$item','$idxnum'".');"';
 8728:                     $text .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="'.$item.'"'.$chgstr.'>';
 8729:                     for (my $i=0; $i<=$numchildren; $i++) {
 8730:                         my $vpos = $i+1;
 8731:                         my $selstr;
 8732:                         if ($j == $i) {
 8733:                             $selstr = ' selected="selected" ';
 8734:                         }
 8735:                         $text .= '<option value="'.$i.'"'.$selstr.'>'.$vpos.'</option>';
 8736:                     }
 8737:                     $text .= '</select>&nbsp;';
 8738:                     if ($j < $numchildren) {
 8739:                         my $deeper = $depth+1;
 8740:                         $text .= $name.'&nbsp;'
 8741:                                  .'<label><input type="checkbox" name="deletecategory" value="'
 8742:                                  .$item.'" />'.&mt('Delete').'</label></span></td><td>';
 8743:                         if(ref($path) eq 'ARRAY') {
 8744:                             push(@{$path},$name);
 8745:                             $text .= &build_category_rows($itemcount,$cats,$deeper,$name,$path,$idx);
 8746:                             pop(@{$path});
 8747:                         }
 8748:                     } else {
 8749:                         $text .= &mt('Add subcategory:').'&nbsp;</span><input type="text" size="20" name="addcategory_name_';
 8750:                         if ($j == $numchildren) {
 8751:                             $text .= $name;
 8752:                         } else {
 8753:                             $text .= $item;
 8754:                         }
 8755:                         $text .= '" value="" />';
 8756:                     }
 8757:                     $text .= '</td></tr>';
 8758:                 }
 8759:                 $text .= '</table></td>';
 8760:             } else {
 8761:                 my $higher = $depth-1;
 8762:                 if ($higher == 0) {
 8763:                     $name = &escape($parent).'::'.$higher;
 8764:                 } else {
 8765:                     if (ref($path) eq 'ARRAY') {
 8766:                         $name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
 8767:                     }
 8768:                 }
 8769:                 my $colspan;
 8770:                 if ($parent ne 'instcode') {
 8771:                     $colspan = $maxdepth - $depth - 1;
 8772:                     $text .= '<td colspan="'.$colspan.'">'.&mt('Add subcategory:').'<input type="text" size="20" name="subcat_'.$name.'" value="" /></td>';
 8773:                 }
 8774:             }
 8775:         }
 8776:     }
 8777:     return $text;
 8778: }
 8779: 
 8780: sub modifiable_userdata_row {
 8781:     my ($context,$item,$settings,$numinrow,$rowcount,$usertypes,$fieldsref,$titlesref,
 8782:         $rowid,$customcss,$rowstyle) = @_;
 8783:     my ($role,$rolename,$statustype);
 8784:     $role = $item;
 8785:     if ($context eq 'cancreate') {
 8786:         if ($item =~ /^(emailusername)_(.+)$/) {
 8787:             $role = $1;
 8788:             $statustype = $2;
 8789:             if (ref($usertypes) eq 'HASH') {
 8790:                 if ($usertypes->{$statustype}) {
 8791:                     $rolename = &mt('Data provided by [_1]',$usertypes->{$statustype});
 8792:                 } else {
 8793:                     $rolename = &mt('Data provided by user');
 8794:                 }
 8795:             }
 8796:         }
 8797:     } elsif ($context eq 'selfcreate') {
 8798:         if (ref($usertypes) eq 'HASH') {
 8799:             $rolename = $usertypes->{$role};
 8800:         } else {
 8801:             $rolename = $role;
 8802:         }
 8803:     } else {
 8804:         if ($role eq 'cr') {
 8805:             $rolename = &mt('Custom role');
 8806:         } else {
 8807:             $rolename = &Apache::lonnet::plaintext($role);
 8808:         }
 8809:     }
 8810:     my (@fields,%fieldtitles);
 8811:     if (ref($fieldsref) eq 'ARRAY') {
 8812:         @fields = @{$fieldsref};
 8813:     } else {
 8814:         @fields = ('lastname','firstname','middlename','generation',
 8815:                    'permanentemail','id');
 8816:     }
 8817:     if ((ref($titlesref) eq 'HASH')) {
 8818:         %fieldtitles = %{$titlesref};
 8819:     } else {
 8820:         %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 8821:     }
 8822:     my $output;
 8823:     my $css_class;
 8824:     if ($rowcount%2) {
 8825:         $css_class = 'LC_odd_row';
 8826:     }
 8827:     if ($customcss) {
 8828:         $css_class .= " $customcss";
 8829:     }
 8830:     $css_class =~ s/^\s+//;
 8831:     if ($css_class) {
 8832:         $css_class = ' class="'.$css_class.'"';
 8833:     }
 8834:     if ($rowstyle) {
 8835:         $css_class .= ' style="'.$rowstyle.'"';
 8836:     }
 8837:     if ($rowid) {
 8838:         $rowid = ' id="'.$rowid.'"';
 8839:     }
 8840: 
 8841:     $output = '<tr '.$css_class.$rowid.'>'.
 8842:               '<td><span class="LC_nobreak">'.$rolename.'</span></td>'.
 8843:               '<td class="LC_left_item" colspan="2"><table>';
 8844:     my $rem;
 8845:     my %checks;
 8846:     if (ref($settings) eq 'HASH') {
 8847:         if (ref($settings->{$context}) eq 'HASH') {
 8848:             if (ref($settings->{$context}->{$role}) eq 'HASH') {
 8849:                 my $hashref = $settings->{$context}->{$role};
 8850:                 if ($role eq 'emailusername') {
 8851:                     if ($statustype) {
 8852:                         if (ref($settings->{$context}->{$role}->{$statustype}) eq 'HASH') {
 8853:                             $hashref = $settings->{$context}->{$role}->{$statustype};
 8854:                             if (ref($hashref) eq 'HASH') { 
 8855:                                 foreach my $field (@fields) {
 8856:                                     if ($hashref->{$field}) {
 8857:                                         $checks{$field} = $hashref->{$field};
 8858:                                     }
 8859:                                 }
 8860:                             }
 8861:                         }
 8862:                     }
 8863:                 } else {
 8864:                     if (ref($hashref) eq 'HASH') {
 8865:                         foreach my $field (@fields) {
 8866:                             if ($hashref->{$field}) {
 8867:                                 $checks{$field} = ' checked="checked" ';
 8868:                             }
 8869:                         }
 8870:                     }
 8871:                 }
 8872:             }
 8873:         }
 8874:     }
 8875: 
 8876:     my $total = scalar(@fields);
 8877:     for (my $i=0; $i<$total; $i++) {
 8878:         $rem = $i%($numinrow);
 8879:         if ($rem == 0) {
 8880:             if ($i > 0) {
 8881:                 $output .= '</tr>';
 8882:             }
 8883:             $output .= '<tr>';
 8884:         }
 8885:         my $check = ' ';
 8886:         unless ($role eq 'emailusername') {
 8887:             if (exists($checks{$fields[$i]})) {
 8888:                 $check = $checks{$fields[$i]};
 8889:             } else {
 8890:                 if ($role eq 'st') {
 8891:                     if (ref($settings) ne 'HASH') {
 8892:                         $check = ' checked="checked" '; 
 8893:                     }
 8894:                 }
 8895:             }
 8896:         }
 8897:         $output .= '<td class="LC_left_item">'.
 8898:                    '<span class="LC_nobreak">';
 8899:         if ($role eq 'emailusername') {
 8900:             unless ($checks{$fields[$i]} =~ /^(required|optional)$/) {
 8901:                 $checks{$fields[$i]} = 'omit';
 8902:             }
 8903:             foreach my $option ('required','optional','omit') {
 8904:                 my $checked='';
 8905:                 if ($checks{$fields[$i]} eq $option) {
 8906:                     $checked='checked="checked" ';
 8907:                 }
 8908:                 $output .= '<label>'.
 8909:                            '<input type="radio" name="canmodify_'.$item.'_'.$fields[$i].'" value="'.$option.'" '.$checked.'/>'.
 8910:                            &mt($option).'</label>'.('&nbsp;' x2);
 8911:             }
 8912:             $output .= '<i>'.$fieldtitles{$fields[$i]}.'</i>';
 8913:         } else {
 8914:             $output .= '<label>'.
 8915:                        '<input type="checkbox" name="canmodify_'.$role.'" '.
 8916:                        'value="'.$fields[$i].'"'.$check.'/>'.$fieldtitles{$fields[$i]}.
 8917:                        '</label>';
 8918:         }
 8919:         $output .= '</span></td>';
 8920:     }
 8921:     $rem = $total%$numinrow;
 8922:     my $colsleft;
 8923:     if ($rem) {
 8924:         $colsleft = $numinrow - $rem;
 8925:     }
 8926:     if ($colsleft > 1) {
 8927:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 8928:                    '&nbsp;</td>';
 8929:     } elsif ($colsleft == 1) {
 8930:         $output .= '<td class="LC_left_item">&nbsp;</td>';
 8931:     }
 8932:     $output .= '</tr></table></td></tr>';
 8933:     return $output;
 8934: }
 8935: 
 8936: sub insttypes_row {
 8937:     my ($settings,$types,$usertypes,$dom,$numinrow,$othertitle,$context,$rowtotal,$onclick,
 8938:         $customcss,$rowstyle) = @_;
 8939:     my %lt = &Apache::lonlocal::texthash (
 8940:                       cansearch => 'Users allowed to search',
 8941:                       statustocreate => 'Institutional affiliation(s) able to create own account (login/SSO)',
 8942:                       lockablenames => 'User preference to lock name',
 8943:                       selfassign    => 'Self-reportable affiliations',
 8944:                       overrides     => "Override domain's helpdesk settings based on requester's affiliation",
 8945:              );
 8946:     my $showdom;
 8947:     if ($context eq 'cansearch') {
 8948:         $showdom = ' ('.$dom.')';
 8949:     }
 8950:     my $class = 'LC_left_item';
 8951:     if ($context eq 'statustocreate') {
 8952:         $class = 'LC_right_item';
 8953:     }
 8954:     my $css_class;
 8955:     if ($$rowtotal%2) {
 8956:         $css_class = 'LC_odd_row';
 8957:     }
 8958:     if ($customcss) {
 8959:         $css_class .= ' '.$customcss;
 8960:     }
 8961:     $css_class =~ s/^\s+//;
 8962:     if ($css_class) {
 8963:         $css_class = ' class="'.$css_class.'"';
 8964:     }
 8965:     if ($rowstyle) {
 8966:         $css_class .= ' style="'.$rowstyle.'"';
 8967:     }
 8968:     if ($onclick) {
 8969:         $onclick = 'onclick="'.$onclick.'" ';
 8970:     }
 8971:     my $output = '<tr'.$css_class.'>'.
 8972:                  '<td>'.$lt{$context}.$showdom.
 8973:                  '</td><td class="'.$class.'" colspan="2"><table>';
 8974:     my $rem;
 8975:     if (ref($types) eq 'ARRAY') {
 8976:         for (my $i=0; $i<@{$types}; $i++) {
 8977:             if (defined($usertypes->{$types->[$i]})) {
 8978:                 my $rem = $i%($numinrow);
 8979:                 if ($rem == 0) {
 8980:                     if ($i > 0) {
 8981:                         $output .= '</tr>';
 8982:                     }
 8983:                     $output .= '<tr>';
 8984:                 }
 8985:                 my $check = ' ';
 8986:                 if (ref($settings) eq 'HASH') {
 8987:                     if (ref($settings->{$context}) eq 'ARRAY') {
 8988:                         if (grep(/^\Q$types->[$i]\E$/,@{$settings->{$context}})) {
 8989:                             $check = ' checked="checked" ';
 8990:                         }
 8991:                     } elsif (ref($settings->{$context}) eq 'HASH') {
 8992:                         if (ref($settings->{$context}->{$types->[$i]}) eq 'HASH') {
 8993:                             $check = ' checked="checked" ';
 8994:                         }
 8995:                     } elsif ($context eq 'statustocreate') {
 8996:                         $check = ' checked="checked" ';
 8997:                     }
 8998:                 }
 8999:                 $output .= '<td class="LC_left_item">'.
 9000:                            '<span class="LC_nobreak"><label>'.
 9001:                            '<input type="checkbox" name="'.$context.'" '.
 9002:                            'value="'.$types->[$i].'"'.$check.$onclick.'/>'.
 9003:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 9004:             }
 9005:         }
 9006:         $rem = @{$types}%($numinrow);
 9007:     }
 9008:     my $colsleft = $numinrow - $rem;
 9009:     if ($context eq 'overrides') {
 9010:         if ($colsleft > 1) {
 9011:             $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 9012:         } else {
 9013:             $output .= '<td class="LC_left_item">';
 9014:         }
 9015:         $output .= '&nbsp;';
 9016:     } else {
 9017:         if ($rem == 0) {
 9018:             $output .= '<tr>';
 9019:         }
 9020:         if ($colsleft > 1) {
 9021:             $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 9022:         } else {
 9023:             $output .= '<td class="LC_left_item">';
 9024:         }
 9025:         my $defcheck = ' ';
 9026:         if (ref($settings) eq 'HASH') {  
 9027:             if (ref($settings->{$context}) eq 'ARRAY') {
 9028:                 if (grep(/^default$/,@{$settings->{$context}})) {
 9029:                     $defcheck = ' checked="checked" ';
 9030:                 }
 9031:             } elsif ($context eq 'statustocreate') {
 9032:                 $defcheck = ' checked="checked" ';
 9033:             }
 9034:         }
 9035:         $output .= '<span class="LC_nobreak"><label>'.
 9036:                    '<input type="checkbox" name="'.$context.'" '.
 9037:                    'value="default"'.$defcheck.$onclick.' />'.
 9038:                    $othertitle.'</label></span>';
 9039:     }
 9040:     $output .= '</td></tr></table></td></tr>';
 9041:     return $output;
 9042: }
 9043: 
 9044: sub sorted_searchtitles {
 9045:     my %searchtitles = &Apache::lonlocal::texthash(
 9046:                          'uname' => 'username',
 9047:                          'lastname' => 'last name',
 9048:                          'lastfirst' => 'last name, first name',
 9049:                      );
 9050:     my @titleorder = ('uname','lastname','lastfirst');
 9051:     return (\%searchtitles,\@titleorder);
 9052: }
 9053: 
 9054: sub sorted_searchtypes {
 9055:     my %srchtypes_desc = (
 9056:                            exact    => 'is exact match',
 9057:                            contains => 'contains ..',
 9058:                            begins   => 'begins with ..',
 9059:                          );
 9060:     my @srchtypeorder = ('exact','begins','contains');
 9061:     return (\%srchtypes_desc,\@srchtypeorder);
 9062: }
 9063: 
 9064: sub usertype_update_row {
 9065:     my ($settings,$usertypes,$fieldtitles,$fields,$types,$rownums) = @_;
 9066:     my $datatable;
 9067:     my $numinrow = 4;
 9068:     foreach my $type (@{$types}) {
 9069:         if (defined($usertypes->{$type})) {
 9070:             $$rownums ++;
 9071:             my $css_class = $$rownums%2?' class="LC_odd_row"':'';
 9072:             $datatable .= '<tr'.$css_class.'><td>'.$usertypes->{$type}.
 9073:                           '</td><td class="LC_left_item"><table>';
 9074:             for (my $i=0; $i<@{$fields}; $i++) {
 9075:                 my $rem = $i%($numinrow);
 9076:                 if ($rem == 0) {
 9077:                     if ($i > 0) {
 9078:                         $datatable .= '</tr>';
 9079:                     }
 9080:                     $datatable .= '<tr>';
 9081:                 }
 9082:                 my $check = ' ';
 9083:                 if (ref($settings) eq 'HASH') {
 9084:                     if (ref($settings->{'fields'}) eq 'HASH') {
 9085:                         if (ref($settings->{'fields'}{$type}) eq 'ARRAY') {
 9086:                             if (grep(/^\Q$fields->[$i]\E$/,@{$settings->{'fields'}{$type}})) {
 9087:                                 $check = ' checked="checked" ';
 9088:                             }
 9089:                         }
 9090:                     }
 9091:                 }
 9092: 
 9093:                 if ($i == @{$fields}-1) {
 9094:                     my $colsleft = $numinrow - $rem;
 9095:                     if ($colsleft > 1) {
 9096:                         $datatable .= '<td colspan="'.$colsleft.'">';
 9097:                     } else {
 9098:                         $datatable .= '<td>';
 9099:                     }
 9100:                 } else {
 9101:                     $datatable .= '<td>';
 9102:                 }
 9103:                 $datatable .= '<span class="LC_nobreak"><label>'.
 9104:                               '<input type="checkbox" name="updateable_'.$type.
 9105:                               '_'.$fields->[$i].'" value="1"'.$check.'/>'.
 9106:                               $fieldtitles->{$fields->[$i]}.'</label></span></td>';
 9107:             }
 9108:             $datatable .= '</tr></table></td></tr>';
 9109:         }
 9110:     }
 9111:     return $datatable;
 9112: }
 9113: 
 9114: sub modify_login {
 9115:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
 9116:     my ($resulttext,$errors,$colchgtext,%changes,%colchanges,%newfile,%newurl,
 9117:         %curr_loginvia,%loginhash,@currlangs,@newlangs,$addedfile,%title,@offon,
 9118:         %currsaml,%saml,%samltext,%samlimg,%samlalt,%samlurl,%samltitle,%samlnotsso);
 9119:     %title = ( coursecatalog => 'Display course catalog',
 9120:                adminmail => 'Display administrator E-mail address',
 9121:                helpdesk  => 'Display "Contact Helpdesk" link',
 9122:                newuser => 'Link for visitors to create a user account',
 9123:                loginheader => 'Log-in box header',
 9124:                saml => 'Dual SSO and non-SSO login');
 9125:     @offon = ('off','on');
 9126:     if (ref($domconfig{login}) eq 'HASH') {
 9127:         if (ref($domconfig{login}{loginvia}) eq 'HASH') {
 9128:             foreach my $lonhost (keys(%{$domconfig{login}{loginvia}})) {
 9129:                 $curr_loginvia{$lonhost} = $domconfig{login}{loginvia}{$lonhost};
 9130:             }
 9131:         }
 9132:         if (ref($domconfig{login}{'saml'}) eq 'HASH') {
 9133:             foreach my $lonhost (keys(%{$domconfig{login}{'saml'}})) {
 9134:                 if (ref($domconfig{login}{'saml'}{$lonhost}) eq 'HASH') {
 9135:                     $currsaml{$lonhost} = $domconfig{login}{'saml'}{$lonhost};
 9136:                     $saml{$lonhost} = 1;
 9137:                     $samltext{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'text'};
 9138:                     $samlurl{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'url'};
 9139:                     $samlalt{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'alt'};
 9140:                     $samlimg{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'img'};
 9141:                     $samltitle{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'title'};
 9142:                     $samlnotsso{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'notsso'};
 9143:                 }
 9144:             }
 9145:         }
 9146:     }
 9147:     ($errors,%colchanges) = &modify_colors($r,$dom,$confname,['login'],
 9148:                                            \%domconfig,\%loginhash);
 9149:     my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
 9150:     foreach my $item (@toggles) {
 9151:         $loginhash{login}{$item} = $env{'form.'.$item};
 9152:     }
 9153:     $loginhash{login}{loginheader} = $env{'form.loginheader'};
 9154:     if (ref($colchanges{'login'}) eq 'HASH') {  
 9155:         $colchgtext = &display_colorchgs($dom,\%colchanges,['login'],
 9156:                                          \%loginhash);
 9157:     }
 9158: 
 9159:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 9160:     my %domservers = &Apache::lonnet::get_servers($dom);
 9161:     my @loginvia_attribs = ('serverpath','custompath','exempt');
 9162:     if (keys(%servers) > 1) {
 9163:         foreach my $lonhost (keys(%servers)) {
 9164:             next if ($env{'form.'.$lonhost.'_server'} eq $lonhost);
 9165:             if (ref($curr_loginvia{$lonhost}) eq 'HASH') {
 9166:                 if ($env{'form.'.$lonhost.'_server'} eq $curr_loginvia{$lonhost}{'server'}) {
 9167:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $curr_loginvia{$lonhost}{'server'};
 9168:                 } elsif ($curr_loginvia{$lonhost}{'server'} ne '') {
 9169:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
 9170:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
 9171:                         $changes{'loginvia'}{$lonhost} = 1;
 9172:                     } else {
 9173:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = '';
 9174:                         $changes{'loginvia'}{$lonhost} = 1;
 9175:                     }
 9176:                 } else {
 9177:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
 9178:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
 9179:                         $changes{'loginvia'}{$lonhost} = 1;
 9180:                     }
 9181:                 }
 9182:                 if ($loginhash{login}{loginvia}{$lonhost}{'server'} eq '') {
 9183:                     foreach my $item (@loginvia_attribs) {
 9184:                         $loginhash{login}{loginvia}{$lonhost}{$item} = '';
 9185:                     }
 9186:                 } else {
 9187:                     foreach my $item (@loginvia_attribs) {
 9188:                         my $new = $env{'form.'.$lonhost.'_'.$item};
 9189:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
 9190:                             $env{'form.'.$lonhost.'_custompath'} =~ s/\s+//g;
 9191:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
 9192:                                 $new = '/';
 9193:                             }
 9194:                         }
 9195:                         if (($item eq 'custompath') && 
 9196:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
 9197:                             $new = '';
 9198:                         }
 9199:                         if ($new ne $curr_loginvia{$lonhost}{$item}) {
 9200:                             $changes{'loginvia'}{$lonhost} = 1;
 9201:                         }
 9202:                         if ($item eq 'exempt') {
 9203:                             $new = &check_exempt_addresses($new);
 9204:                         }
 9205:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
 9206:                     }
 9207:                 }
 9208:             } else {
 9209:                 if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
 9210:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
 9211:                     $changes{'loginvia'}{$lonhost} = 1;
 9212:                     foreach my $item (@loginvia_attribs) {
 9213:                         my $new = $env{'form.'.$lonhost.'_'.$item};
 9214:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
 9215:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
 9216:                                 $new = '/';
 9217:                             }
 9218:                         }
 9219:                         if (($item eq 'custompath') && 
 9220:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
 9221:                             $new = '';
 9222:                         }
 9223:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
 9224:                     }
 9225:                 }
 9226:             }
 9227:         }
 9228:     }
 9229: 
 9230:     my $servadm = $r->dir_config('lonAdmEMail');
 9231:     my %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
 9232:     if (ref($domconfig{'login'}) eq 'HASH') {
 9233:         if (ref($domconfig{'login'}{'helpurl'}) eq 'HASH') {
 9234:             foreach my $lang (sort(keys(%{$domconfig{'login'}{'helpurl'}}))) {
 9235:                 if ($lang eq 'nolang') {
 9236:                     push(@currlangs,$lang);
 9237:                 } elsif (defined($langchoices{$lang})) {
 9238:                     push(@currlangs,$lang);
 9239:                 } else {
 9240:                     next;
 9241:                 }
 9242:             }
 9243:         }
 9244:     }
 9245:     my @delurls = &Apache::loncommon::get_env_multiple('form.loginhelpurl_del');
 9246:     if (@currlangs > 0) {
 9247:         foreach my $lang (@currlangs) {
 9248:             if (grep(/^\Q$lang\E$/,@delurls)) {
 9249:                 $changes{'helpurl'}{$lang} = 1;
 9250:             } elsif ($env{'form.loginhelpurl_'.$lang.'.filename'}) {
 9251:                 $changes{'helpurl'}{$lang} = 1;
 9252:                 $newfile{$lang} = $env{'form.loginhelpurl_'.$lang.'.filename'};
 9253:                 push(@newlangs,$lang);
 9254:             } else {
 9255:                 $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
 9256:             }
 9257:         }
 9258:     }
 9259:     unless (grep(/^nolang$/,@currlangs)) {
 9260:         if ($env{'form.loginhelpurl_nolang.filename'}) {
 9261:             $changes{'helpurl'}{'nolang'} = 1;
 9262:             $newfile{'nolang'} = $env{'form.loginhelpurl_nolang.filename'};
 9263:             push(@newlangs,'nolang');
 9264:         }
 9265:     }
 9266:     if ($env{'form.loginhelpurl_add_lang'}) {
 9267:         if ((defined($langchoices{$env{'form.loginhelpurl_add_lang'}})) &&
 9268:             ($env{'form.loginhelpurl_add_file.filename'})) {
 9269:             $newfile{$env{'form.loginhelpurl_add_lang'}} = $env{'form.loginhelpurl_add_file.filename'};
 9270:             $addedfile = $env{'form.loginhelpurl_add_lang'};
 9271:         }
 9272:     }
 9273:     if ((@newlangs > 0) || ($addedfile)) {
 9274:         my $error;
 9275:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
 9276:         if ($configuserok eq 'ok') {
 9277:             if ($switchserver) {
 9278:                 $error = &mt("Upload of custom help file is not permitted to this server: [_1]",$switchserver);
 9279:             } elsif ($author_ok eq 'ok') {
 9280:                 my @allnew = @newlangs;
 9281:                 if ($addedfile ne '') {
 9282:                     push(@allnew,$addedfile);
 9283:                 }
 9284:                 foreach my $lang (@allnew) {
 9285:                     my $formelem = 'loginhelpurl_'.$lang;
 9286:                     if ($lang eq $env{'form.loginhelpurl_add_lang'}) {
 9287:                         $formelem = 'loginhelpurl_add_file';
 9288:                     }
 9289:                     (my $result,$newurl{$lang}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
 9290:                                                                "help/$lang",'','',$newfile{$lang});
 9291:                     if ($result eq 'ok') {
 9292:                         $loginhash{'login'}{'helpurl'}{$lang} = $newurl{$lang};
 9293:                         $changes{'helpurl'}{$lang} = 1;
 9294:                     } else {
 9295:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$newfile{$lang},$result);
 9296:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
 9297:                         if ((grep(/^\Q$lang\E$/,@currlangs)) &&
 9298:                             (!grep(/^\Q$lang\E$/,@delurls))) {
 9299:                             $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
 9300:                         }
 9301:                     }
 9302:                 }
 9303:             } else {
 9304:                 $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);
 9305:             }
 9306:         } else {
 9307:             $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);
 9308:         }
 9309:         if ($error) {
 9310:             &Apache::lonnet::logthis($error);
 9311:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
 9312:         }
 9313:     }
 9314: 
 9315:     my (%currheadtagurls,%currexempt,@newhosts,%newheadtagurls,%possexempt);
 9316:     if (ref($domconfig{'login'}) eq 'HASH') {
 9317:         if (ref($domconfig{'login'}{'headtag'}) eq 'HASH') {
 9318:             foreach my $lonhost (keys(%{$domconfig{'login'}{'headtag'}})) {
 9319:                 if ($domservers{$lonhost}) {
 9320:                     if (ref($domconfig{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
 9321:                         $currheadtagurls{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'url'};
 9322:                         $currexempt{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'exempt'};
 9323:                     }
 9324:                 }
 9325:             }
 9326:         }
 9327:     }
 9328:     my @delheadtagurls = &Apache::loncommon::get_env_multiple('form.loginheadtag_del');
 9329:     foreach my $lonhost (sort(keys(%domservers))) {
 9330:         if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
 9331:             $changes{'headtag'}{$lonhost} = 1;
 9332:         } else {
 9333:             if ($env{'form.loginheadtagexempt_'.$lonhost}) {
 9334:                 $possexempt{$lonhost} = &check_exempt_addresses($env{'form.loginheadtagexempt_'.$lonhost});
 9335:             }
 9336:             if ($env{'form.loginheadtag_'.$lonhost.'.filename'}) {
 9337:                 push(@newhosts,$lonhost);
 9338:             } elsif ($currheadtagurls{$lonhost}) {
 9339:                 $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $currheadtagurls{$lonhost};
 9340:                 if ($currexempt{$lonhost}) {
 9341:                     if ((!exists($possexempt{$lonhost})) || ($possexempt{$lonhost} ne $currexempt{$lonhost})) {
 9342:                         $changes{'headtag'}{$lonhost} = 1;
 9343:                     }
 9344:                 } elsif ($possexempt{$lonhost}) {
 9345:                     $changes{'headtag'}{$lonhost} = 1;
 9346:                 }
 9347:                 if ($possexempt{$lonhost}) {
 9348:                     $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
 9349:                 }
 9350:             }
 9351:         }
 9352:     }
 9353:     if (@newhosts) {
 9354:         my $error;
 9355:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
 9356:         if ($configuserok eq 'ok') {
 9357:             if ($switchserver) {
 9358:                 $error = &mt("Upload of custom markup is not permitted to this server: [_1]",$switchserver);
 9359:             } elsif ($author_ok eq 'ok') {
 9360:                 foreach my $lonhost (@newhosts) {
 9361:                     my $formelem = 'loginheadtag_'.$lonhost;
 9362:                     (my $result,$newheadtagurls{$lonhost}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
 9363:                                                                           "login/headtag/$lonhost",'','',
 9364:                                                                           $env{'form.loginheadtag_'.$lonhost.'.filename'});
 9365:                     if ($result eq 'ok') {
 9366:                         $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $newheadtagurls{$lonhost};
 9367:                         $changes{'headtag'}{$lonhost} = 1;
 9368:                         if ($possexempt{$lonhost}) {
 9369:                             $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
 9370:                         }
 9371:                     } else {
 9372:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",
 9373:                                            $newheadtagurls{$lonhost},$result);
 9374:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
 9375:                         if ((grep(/^\Q$lonhost\E$/,keys(%currheadtagurls))) &&
 9376:                             (!grep(/^\Q$lonhost\E$/,@delheadtagurls))) {
 9377:                             $loginhash{'login'}{'headtag'}{$lonhost} = $currheadtagurls{$lonhost};
 9378:                         }
 9379:                     }
 9380:                 }
 9381:             } else {
 9382:                 $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);
 9383:             }
 9384:         } else {
 9385:             $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);
 9386:         }
 9387:         if ($error) {
 9388:             &Apache::lonnet::logthis($error);
 9389:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
 9390:         }
 9391:     }
 9392:     my @delsamlimg = &Apache::loncommon::get_env_multiple('form.saml_img_del');
 9393:     my @newsamlimgs;
 9394:     foreach my $lonhost (keys(%domservers)) {
 9395:         if ($env{'form.saml_'.$lonhost}) {
 9396:             if ($env{'form.saml_img_'.$lonhost.'.filename'}) {
 9397:                 push(@newsamlimgs,$lonhost);
 9398:             }
 9399:             foreach my $item ('text','alt','url','title','notsso') {
 9400:                 $env{'form.saml_'.$item.'_'.$lonhost} =~ s/^\s+|\s+$//g;
 9401:             }
 9402:             if ($saml{$lonhost}) {
 9403:                 if (grep(/^\Q$lonhost\E$/,@delsamlimg)) {
 9404: #FIXME Need to obsolete published image
 9405:                     delete($currsaml{$lonhost}{'img'});
 9406:                     $changes{'saml'}{$lonhost} = 1;
 9407:                 }
 9408:                 if ($env{'form.saml_alt_'.$lonhost} ne $samlalt{$lonhost}) {
 9409:                     $changes{'saml'}{$lonhost} = 1;
 9410:                 }
 9411:                 if ($env{'form.saml_text_'.$lonhost} ne $samltext{$lonhost}) {
 9412:                     $changes{'saml'}{$lonhost} = 1;
 9413:                 }
 9414:                 if ($env{'form.saml_url_'.$lonhost} ne $samlurl{$lonhost}) {
 9415:                     $changes{'saml'}{$lonhost} = 1;
 9416:                 }
 9417:                 if ($env{'form.saml_title_'.$lonhost} ne $samltitle{$lonhost}) {
 9418:                     $changes{'saml'}{$lonhost} = 1;
 9419:                 }
 9420:                 if ($env{'form.saml_notsso_'.$lonhost} ne $samlnotsso{$lonhost}) {
 9421:                     $changes{'saml'}{$lonhost} = 1;
 9422:                 }
 9423:             } else {
 9424:                 $changes{'saml'}{$lonhost} = 1;
 9425:             }
 9426:             foreach my $item ('text','alt','url','title','notsso') {
 9427:                 $currsaml{$lonhost}{$item} = $env{'form.saml_'.$item.'_'.$lonhost};
 9428:             }
 9429:         } else {
 9430:             if ($saml{$lonhost}) {
 9431:                 $changes{'saml'}{$lonhost} = 1;
 9432:                 delete($currsaml{$lonhost});
 9433:             }
 9434:         }
 9435:     }
 9436:     foreach my $posshost (keys(%currsaml)) {
 9437:         unless (exists($domservers{$posshost})) {
 9438:             delete($currsaml{$posshost});
 9439:         }
 9440:     }
 9441:     %{$loginhash{'login'}{'saml'}} = %currsaml;
 9442:     if (@newsamlimgs) {
 9443:         my $error;
 9444:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
 9445:         if ($configuserok eq 'ok') {
 9446:             if ($switchserver) {
 9447:                 $error = &mt("Upload of SSO Button Image is not permitted to this server: [_1].",$switchserver);
 9448:             } elsif ($author_ok eq 'ok') {
 9449:                 foreach my $lonhost (@newsamlimgs) {
 9450:                     my $formelem = 'saml_img_'.$lonhost;
 9451:                     my ($result,$imgurl) = &publishlogo($r,'upload',$formelem,$dom,$confname,
 9452:                                                         "login/saml/$lonhost",'','',
 9453:                                                         $env{'form.saml_img_'.$lonhost.'.filename'});
 9454:                     if ($result eq 'ok') {
 9455:                         $currsaml{$lonhost}{'img'} = $imgurl;
 9456:                         $loginhash{'login'}{'saml'}{$lonhost}{'img'} = $imgurl;
 9457:                         $changes{'saml'}{$lonhost} = 1;
 9458:                     } else {
 9459:                         my $puberror = &mt("Upload of SSO button image failed for [_1] because an error occurred publishing the file in RES space. Error was: [_2].",
 9460:                                            $lonhost,$result);
 9461:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
 9462:                     }
 9463:                 }
 9464:             } else {
 9465:                 $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);
 9466:             }
 9467:         } else {
 9468:             $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);
 9469:         }
 9470:         if ($error) {
 9471:             &Apache::lonnet::logthis($error);
 9472:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
 9473:         }
 9474:     }
 9475:     &process_captcha('login',\%changes,$loginhash{'login'},$domconfig{'login'});
 9476: 
 9477:     my $defaulthelpfile = '/adm/loginproblems.html';
 9478:     my $defaulttext = &mt('Default in use');
 9479: 
 9480:     my $putresult = &Apache::lonnet::put_dom('configuration',\%loginhash,
 9481:                                              $dom);
 9482:     if ($putresult eq 'ok') {
 9483:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
 9484:         my %defaultchecked = (
 9485:                     'coursecatalog' => 'on',
 9486:                     'helpdesk'      => 'on',
 9487:                     'adminmail'     => 'off',
 9488:                     'newuser'       => 'off',
 9489:         );
 9490:         if (ref($domconfig{'login'}) eq 'HASH') {
 9491:             foreach my $item (@toggles) {
 9492:                 if ($defaultchecked{$item} eq 'on') { 
 9493:                     if (($domconfig{'login'}{$item} eq '0') &&
 9494:                         ($env{'form.'.$item} eq '1')) {
 9495:                         $changes{$item} = 1;
 9496:                     } elsif (($domconfig{'login'}{$item} eq '' ||
 9497:                               $domconfig{'login'}{$item} eq '1') &&
 9498:                              ($env{'form.'.$item} eq '0')) {
 9499:                         $changes{$item} = 1;
 9500:                     }
 9501:                 } elsif ($defaultchecked{$item} eq 'off') {
 9502:                     if (($domconfig{'login'}{$item} eq '1') &&
 9503:                         ($env{'form.'.$item} eq '0')) {
 9504:                         $changes{$item} = 1;
 9505:                     } elsif (($domconfig{'login'}{$item} eq '' ||
 9506:                               $domconfig{'login'}{$item} eq '0') &&
 9507:                              ($env{'form.'.$item} eq '1')) {
 9508:                         $changes{$item} = 1;
 9509:                     }
 9510:                 }
 9511:             }
 9512:         }
 9513:         if (keys(%changes) > 0 || $colchgtext) {
 9514:             &Apache::loncommon::devalidate_domconfig_cache($dom);
 9515:             if (exists($changes{'saml'})) {
 9516:                 my $hostid_in_use;
 9517:                 my @hosts = &Apache::lonnet::current_machine_ids();
 9518:                 if (@hosts > 1) {
 9519:                     foreach my $hostid (@hosts) {
 9520:                         if (&Apache::lonnet::host_domain($hostid) eq $dom) {
 9521:                             $hostid_in_use = $hostid;
 9522:                             last;
 9523:                         }
 9524:                     }
 9525:                 } else {
 9526:                     $hostid_in_use = $r->dir_config('lonHostID');
 9527:                 }
 9528:                 if (($hostid_in_use) &&
 9529:                     (&Apache::lonnet::host_domain($hostid_in_use) eq $dom)) {
 9530:                     &Apache::lonnet::devalidate_cache_new('samllanding',$hostid_in_use);
 9531:                 }
 9532:                 if (ref($lastactref) eq 'HASH') {
 9533:                     if (ref($changes{'saml'}) eq 'HASH') {
 9534:                         my %updates;
 9535:                         map { $updates{$_} = 1; } keys(%{$changes{'saml'}});
 9536:                         $lastactref->{'samllanding'} = \%updates;
 9537:                     }
 9538:                 }
 9539:             }
 9540:             if (ref($lastactref) eq 'HASH') {
 9541:                 $lastactref->{'domainconfig'} = 1;
 9542:             }
 9543:             $resulttext = &mt('Changes made:').'<ul>';
 9544:             foreach my $item (sort(keys(%changes))) {
 9545:                 if ($item eq 'loginvia') {
 9546:                     if (ref($changes{$item}) eq 'HASH') {
 9547:                         $resulttext .= '<li>'.&mt('Log-in page availability:').'<ul>';
 9548:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
 9549:                             if (defined($servers{$loginhash{login}{loginvia}{$lonhost}{'server'}})) {
 9550:                                 if (ref($loginhash{login}{loginvia}{$lonhost}) eq 'HASH') {
 9551:                                     my $protocol = $Apache::lonnet::protocol{$env{'form.'.$lonhost.'_server'}};
 9552:                                     $protocol = 'http' if ($protocol ne 'https');
 9553:                                     my $target = $protocol.'://'.$servers{$env{'form.'.$lonhost.'_server'}};
 9554: 
 9555:                                     if ($loginhash{login}{loginvia}{$lonhost}{'serverpath'} eq 'custom') {
 9556:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'custompath'};
 9557:                                     } else {
 9558:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'serverpath'}; 
 9559:                                     }
 9560:                                     $resulttext .= '<li>'.&mt('Server: [_1] log-in page redirects to [_2].',$servers{$lonhost},'<a href="'.$target.'">'.$target.'</a>');
 9561:                                     if ($loginhash{login}{loginvia}{$lonhost}{'exempt'} ne '') {
 9562:                                         $resulttext .= '&nbsp;'.&mt('No redirection for clients from following IPs:').'&nbsp;'.$loginhash{login}{loginvia}{$lonhost}{'exempt'};
 9563:                                     }
 9564:                                     $resulttext .= '</li>';
 9565:                                 } else {
 9566:                                     $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$lonhost).'</li>';
 9567:                                 }
 9568:                             } else {
 9569:                                 $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$servers{$lonhost}).'</li>';
 9570:                             }
 9571:                         }
 9572:                         $resulttext .= '</ul></li>';
 9573:                     }
 9574:                 } elsif ($item eq 'helpurl') {
 9575:                     if (ref($changes{$item}) eq 'HASH') {
 9576:                         foreach my $lang (sort(keys(%{$changes{$item}}))) {
 9577:                             if (grep(/^\Q$lang\E$/,@delurls)) {
 9578:                                 my ($chg,$link);
 9579:                                 $link = &Apache::loncommon::modal_link($defaulthelpfile,$defaulttext,600,500);
 9580:                                 if ($lang eq 'nolang') {
 9581:                                     $chg = &mt('custom log-in help file removed for no preferred language; [_1]',$link);
 9582:                                 } else {
 9583:                                     $chg = &mt('custom log-in help file removed for specific language: [_1]; [_2]',$langchoices{$lang},$link);
 9584:                                 }
 9585:                                 $resulttext .= '<li>'.$chg.'</li>';
 9586:                             } else {
 9587:                                 my $chg;
 9588:                                 if ($lang eq 'nolang') {
 9589:                                     $chg = &mt('custom log-in help file for no preferred language');
 9590:                                 } else {
 9591:                                     $chg = &mt('custom log-in help file for specific language: [_1]',$langchoices{$lang});
 9592:                                 }
 9593:                                 $resulttext .= '<li>'.&Apache::loncommon::modal_link(
 9594:                                                       $loginhash{'login'}{'helpurl'}{$lang}.
 9595:                                                       '?inhibitmenu=yes',$chg,600,500).
 9596:                                                '</li>';
 9597:                             }
 9598:                         }
 9599:                     }
 9600:                 } elsif ($item eq 'headtag') {
 9601:                     if (ref($changes{$item}) eq 'HASH') {
 9602:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
 9603:                             if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
 9604:                                 $resulttext .= '<li>'.&mt('custom markup file removed for [_1]',$domservers{$lonhost}).'</li>';
 9605:                             } elsif (ref($loginhash{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
 9606:                                 $resulttext .= '<li><a href="'.
 9607:                                                "javascript:void(open('$loginhash{'login'}{'headtag'}{$lonhost}{'url'}?inhibitmenu=yes','Custom_HeadTag',
 9608:                                                'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
 9609:                                                '">'.&mt('custom markup').'</a> '.&mt('(for [_1])',$servers{$lonhost}).' ';
 9610:                                 if ($possexempt{$lonhost}) {
 9611:                                     $resulttext .= &mt('not included for client IP(s): [_1]',$possexempt{$lonhost});
 9612:                                 } else {
 9613:                                     $resulttext .= &mt('included for any client IP');
 9614:                                 }
 9615:                                 $resulttext .= '</li>';
 9616:                             }
 9617:                         }
 9618:                     }
 9619:                 } elsif ($item eq 'saml') {
 9620:                     if (ref($changes{$item}) eq 'HASH') {
 9621:                         my %notlt = (
 9622:                                        text   => 'Text for log-in by SSO',
 9623:                                        img    => 'SSO button image',
 9624:                                        alt    => 'Alt text for button image',
 9625:                                        url    => 'SSO URL',
 9626:                                        title  => 'Tooltip for SSO link',
 9627:                                        notsso => 'Text for non-SSO log-in',
 9628:                                     );
 9629:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
 9630:                             if (ref($currsaml{$lonhost}) eq 'HASH') {
 9631:                                 $resulttext .= '<li>'.&mt("$title{$item} in use for [_1]","<b>$lonhost</b>").
 9632:                                                '<ul>';
 9633:                                 foreach my $key ('text','img','alt','url','title','notsso') {
 9634:                                     if ($currsaml{$lonhost}{$key} eq '') {
 9635:                                         $resulttext .= '<li>'.&mt("$notlt{$key} not in use").'</li>';
 9636:                                     } else {
 9637:                                         my $value = "'$currsaml{$lonhost}{$key}'";
 9638:                                         if ($key eq 'img') {
 9639:                                             $value = '<img src="'.$currsaml{$lonhost}{$key}.'" />';
 9640:                                         }
 9641:                                         $resulttext .= '<li>'.&mt("$notlt{$key} set to: [_1]",
 9642:                                                                   $value).'</li>';
 9643:                                     }
 9644:                                 }
 9645:                                 $resulttext .= '</ul></li>';
 9646:                             } else {
 9647:                                 $resulttext .= '<li>'.&mt("$title{$item} not in use for [_1]",$lonhost).'</li>';
 9648:                             }
 9649:                         }
 9650:                     }
 9651:                 } elsif ($item eq 'captcha') {
 9652:                     if (ref($loginhash{'login'}) eq 'HASH') {
 9653:                         my $chgtxt;
 9654:                         if ($loginhash{'login'}{$item} eq 'notused') {
 9655:                             $chgtxt .= &mt('No CAPTCHA validation in use for helpdesk form.');
 9656:                         } else {
 9657:                             my %captchas = &captcha_phrases();
 9658:                             if ($captchas{$loginhash{'login'}{$item}}) {
 9659:                                 $chgtxt .= &mt("Validation for helpdesk form set to $captchas{$loginhash{'login'}{$item}}.");
 9660:                             } else {
 9661:                                 $chgtxt .= &mt('Validation for helpdesk form set to unknown type.');
 9662:                             }
 9663:                         }
 9664:                         $resulttext .= '<li>'.$chgtxt.'</li>';
 9665:                     }
 9666:                 } elsif ($item eq 'recaptchakeys') {
 9667:                     if (ref($loginhash{'login'}) eq 'HASH') {
 9668:                         my ($privkey,$pubkey);
 9669:                         if (ref($loginhash{'login'}{$item}) eq 'HASH') {
 9670:                             $pubkey = $loginhash{'login'}{$item}{'public'};
 9671:                             $privkey = $loginhash{'login'}{$item}{'private'};
 9672:                         }
 9673:                         my $chgtxt .= &mt('ReCAPTCHA keys changes').'<ul>';
 9674:                         if (!$pubkey) {
 9675:                             $chgtxt .= '<li>'.&mt('Public key deleted').'</li>';
 9676:                         } else {
 9677:                             $chgtxt .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
 9678:                         }
 9679:                         if (!$privkey) {
 9680:                             $chgtxt .= '<li>'.&mt('Private key deleted').'</li>';
 9681:                         } else {
 9682:                             $chgtxt .= '<li>'.&mt('Private key set to [_1]',$privkey).'</li>';
 9683:                         }
 9684:                         $chgtxt .= '</ul>';
 9685:                         $resulttext .= '<li>'.$chgtxt.'</li>';
 9686:                     }
 9687:                 } elsif ($item eq 'recaptchaversion') {
 9688:                     if (ref($loginhash{'login'}) eq 'HASH') {
 9689:                         if ($loginhash{'login'}{'captcha'} eq 'recaptcha') {
 9690:                             $resulttext .= '<li>'.&mt('ReCAPTCHA for helpdesk form set to version [_1]',$loginhash{'login'}{'recaptchaversion'}).
 9691:                                            '</li>';
 9692:                         }
 9693:                     }
 9694:                 } else {
 9695:                     $resulttext .= '<li>'.&mt("$title{$item} set to $offon[$env{'form.'.$item}]").'</li>';
 9696:                 }
 9697:             }
 9698:             $resulttext .= $colchgtext.'</ul>';
 9699:         } else {
 9700:             $resulttext = &mt('No changes made to log-in page settings');
 9701:         }
 9702:     } else {
 9703:         $resulttext = '<span class="LC_error">'.
 9704: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
 9705:     }
 9706:     if ($errors) {
 9707:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
 9708:                        $errors.'</ul>';
 9709:     }
 9710:     return $resulttext;
 9711: }
 9712: 
 9713: sub check_exempt_addresses {
 9714:     my ($iplist) = @_;
 9715:     $iplist =~ s/^\s+//;
 9716:     $iplist =~ s/\s+$//;
 9717:     my @poss_ips = split(/\s*[,:]\s*/,$iplist);
 9718:     my (@okips,$new);
 9719:     foreach my $ip (@poss_ips) {
 9720:         if ($ip =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) {
 9721:             if (($1 <= 255) && ($2 <= 255) && ($3 <= 255) && ($4 <= 255)) {
 9722:                 push(@okips,$ip);
 9723:             }
 9724:         }
 9725:     }
 9726:     if (@okips > 0) {
 9727:         $new = join(',',@okips);
 9728:     } else {
 9729:         $new = '';
 9730:     }
 9731:     return $new;
 9732: }
 9733: 
 9734: sub color_font_choices {
 9735:     my %choices =
 9736:         &Apache::lonlocal::texthash (
 9737:             img => "Header",
 9738:             bgs => "Background colors",
 9739:             links => "Link colors",
 9740:             images => "Images",
 9741:             font => "Font color",
 9742:             fontmenu => "Font menu",
 9743:             pgbg => "Page",
 9744:             tabbg => "Header",
 9745:             sidebg => "Border",
 9746:             link => "Link",
 9747:             alink => "Active link",
 9748:             vlink => "Visited link",
 9749:         );
 9750:     return %choices;
 9751: }
 9752: 
 9753: sub modify_ipaccess {
 9754:     my ($dom,$lastactref,%domconfig) = @_;
 9755:     my (@allpos,%changes,%confhash,$errors,$resulttext);
 9756:     my (@items,%deletions,%itemids,@warnings);
 9757:     my ($typeorder,$types) = &commblocktype_text();
 9758:     if ($env{'form.ipaccess_add'}) {
 9759:         my $name = $env{'form.ipaccess_name_add'};
 9760:         my ($newid,$error) = &get_ipaccess_id($dom,$name);
 9761:         if ($newid) {
 9762:             $itemids{'add'} = $newid;
 9763:             push(@items,'add');
 9764:             $changes{$newid} = 1;
 9765:         } else {
 9766:             $error = &mt('Failed to acquire unique ID for new IP access control item');
 9767:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
 9768:         }
 9769:     }
 9770:     if (ref($domconfig{'ipaccess'}) eq 'HASH') {
 9771:         my @todelete = &Apache::loncommon::get_env_multiple('form.ipaccess_del');
 9772:         if (@todelete) {
 9773:             map { $deletions{$_} = 1; } @todelete;
 9774:         }
 9775:         my $maxnum = $env{'form.ipaccess_maxnum'};
 9776:         for (my $i=0; $i<$maxnum; $i++) {
 9777:             my $itemid = $env{'form.ipaccess_id_'.$i};
 9778:             $itemid =~ s/\D+//g;
 9779:             if (ref($domconfig{'ipaccess'}{$itemid}) eq 'HASH') {
 9780:                 if ($deletions{$itemid}) {
 9781:                     $changes{$itemid} = $domconfig{'ipaccess'}{$itemid}{'name'};
 9782:                 } else {
 9783:                     push(@items,$i);
 9784:                     $itemids{$i} = $itemid;
 9785:                 }
 9786:             }
 9787:         }
 9788:     }
 9789:     foreach my $idx (@items) {
 9790:         my $itemid = $itemids{$idx};
 9791:         next unless ($itemid);
 9792:         my %current;
 9793:         unless ($idx eq 'add') {
 9794:             if (ref($domconfig{'ipaccess'}{$itemid}) eq 'HASH') {
 9795:                 %current = %{$domconfig{'ipaccess'}{$itemid}};
 9796:             }
 9797:         }
 9798:         my $position = $env{'form.ipaccess_pos_'.$itemid};
 9799:         $position =~ s/\D+//g;
 9800:         if ($position ne '') {
 9801:             $allpos[$position] = $itemid;
 9802:         }
 9803:         my $name = $env{'form.ipaccess_name_'.$idx};
 9804:         $name =~ s/^\s+|\s+$//g;
 9805:         $confhash{$itemid}{'name'} = $name;
 9806:         my $possrange = $env{'form.ipaccess_range_'.$idx};
 9807:         $possrange =~ s/^\s+|\s+$//g;
 9808:         unless ($possrange eq '') {
 9809:             $possrange =~ s/[\r\n]+/\s/g;
 9810:             $possrange =~ s/\s*-\s*/-/g;
 9811:             $possrange =~ s/\s+/,/g;
 9812:             $possrange =~ s/,+/,/g;
 9813:             if ($possrange ne '') {
 9814:                 my (@ok,$count);
 9815:                 $count = 0;
 9816:                 foreach my $poss (split(/\,/,$possrange)) {
 9817:                     $count ++;
 9818:                     $poss = &validate_ip_pattern($poss);
 9819:                     if ($poss ne '') {
 9820:                         push(@ok,$poss);
 9821:                     }
 9822:                 }
 9823:                 my $diff = $count - scalar(@ok);
 9824:                 if ($diff) {
 9825:                     $errors .= '<li><span class="LC_error">'.
 9826:                                &mt('[quant,_1,IP] invalid and excluded from saved value for IP range(s) for [_2]',
 9827:                                    $diff,$name).
 9828:                                '</span></li>';
 9829:                 }
 9830:                 if (@ok) {
 9831:                     my @cidr_list;
 9832:                     foreach my $item (@ok) {
 9833:                         @cidr_list = &Net::CIDR::cidradd($item,@cidr_list);
 9834:                     }
 9835:                     $confhash{$itemid}{'ip'} = join(',',@cidr_list);
 9836:                 }
 9837:             }
 9838:         }
 9839:         foreach my $field ('name','ip') {
 9840:             unless (($idx eq 'add') || ($changes{$itemid})) {
 9841:                 if ($current{$field} ne $confhash{$itemid}{$field}) {
 9842:                     $changes{$itemid} = 1;
 9843:                     last;
 9844:                 }
 9845:             }
 9846:         }
 9847:         $confhash{$itemid}{'commblocks'} = {};
 9848: 
 9849:         my %commblocks;
 9850:         map { $commblocks{$_} = 1; } &Apache::loncommon::get_env_multiple('form.ipaccess_block_'.$idx);
 9851:         foreach my $type (@{$typeorder}) {
 9852:             if ($commblocks{$type}) {
 9853:                 $confhash{$itemid}{'commblocks'}{$type} = 'on';
 9854:             }
 9855:             unless (($idx eq 'add') || ($changes{$itemid})) {
 9856:                 if (ref($current{'commblocks'}) eq 'HASH') {
 9857:                     if ($confhash{$itemid}{'commblocks'}{$type} ne $current{'commblocks'}{$type}) {
 9858:                         $changes{$itemid} = 1;
 9859:                     }
 9860:                 } elsif ($confhash{$itemid}{'commblocks'}{$type}) {
 9861:                     $changes{$itemid} = 1;
 9862:                 }
 9863:             }
 9864:         }
 9865:         $confhash{$itemid}{'courses'} = {};
 9866:         my %crsdeletions;
 9867:         my @delcrs = &Apache::loncommon::get_env_multiple('form.ipaccess_course_delete_'.$idx);
 9868:         if (@delcrs) {
 9869:             map { $crsdeletions{$_} = 1; } @delcrs;
 9870:         }
 9871:         if (ref($current{'courses'}) eq 'HASH') {
 9872:             foreach my $cid (sort(keys(%{$current{'courses'}}))) {
 9873:                 if ($crsdeletions{$cid}) {
 9874:                     $changes{$itemid} = 1;
 9875:                 } else {
 9876:                     $confhash{$itemid}{'courses'}{$cid} = 1;
 9877:                 }
 9878:             }
 9879:         }
 9880:         $env{'form.ipaccess_cnum_'.$idx} =~ s/^\s+|\s+$//g;
 9881:         $env{'form.ipaccess_cdom_'.$idx} =~ s/^\s+|\s+$//g;
 9882:         if (($env{'form.ipaccess_cnum_'.$idx} =~ /^$match_courseid$/) &&
 9883:             ($env{'form.ipaccess_cdom_'.$idx} =~ /^$match_domain$/)) {
 9884:             if (&Apache::lonnet::homeserver($env{'form.ipaccess_cnum_'.$idx},
 9885:                                             $env{'form.ipaccess_cdom_'.$idx}) eq 'no_host') {
 9886:                 $errors .= '<li><span class="LC_error">'.
 9887:                            &mt('Invalid courseID [_1] omitted from list of allowed courses',
 9888:                                $env{'form.ipaccess_cdom_'.$idx}.'_'.$env{'form.ipaccess_cnum_'.$idx}).
 9889:                            '</span></li>';
 9890:             } else {
 9891:                 $confhash{$itemid}{'courses'}{$env{'form.ipaccess_cdom_'.$idx}.'_'.$env{'form.ipaccess_cnum_'.$idx}} = 1;
 9892:                 $changes{$itemid} = 1;
 9893:             }
 9894:         }
 9895:     }
 9896:     if (@allpos > 0) {
 9897:         my $idx = 0;
 9898:         foreach my $itemid (@allpos) {
 9899:             if ($itemid ne '') {
 9900:                 $confhash{$itemid}{'order'} = $idx;
 9901:                 unless ($changes{$itemid}) {
 9902:                     if (ref($domconfig{'ipaccess'}) eq 'HASH') {
 9903:                         if (ref($domconfig{'ipaccess'}{$itemid}) eq 'HASH') {
 9904:                             if ($domconfig{'ipaccess'}{$itemid}{'order'} ne $idx) {
 9905:                                 $changes{$itemid} = 1;
 9906:                             }
 9907:                         }
 9908:                     }
 9909:                 }
 9910:                 $idx ++;
 9911:             }
 9912:         }
 9913:     }
 9914:     if (keys(%changes)) {
 9915:         my %defaultshash = (
 9916:                               ipaccess => \%confhash,
 9917:                            );
 9918:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
 9919:                                                  $dom);
 9920:         if ($putresult eq 'ok') {
 9921:             my $cachetime = 1800;
 9922:             &Apache::lonnet::do_cache_new('ipaccess',$dom,\%confhash,$cachetime);
 9923:             if (ref($lastactref) eq 'HASH') {
 9924:                 $lastactref->{'ipaccess'} = 1;
 9925:             }
 9926:             $resulttext = &mt('Changes made:').'<ul>';
 9927:             my %bynum;
 9928:             foreach my $itemid (sort(keys(%changes))) {
 9929:                 if (ref($confhash{$itemid}) eq 'HASH') {
 9930:                     my $position = $confhash{$itemid}{'order'};
 9931:                     if ($position =~ /^\d+$/) {
 9932:                         $bynum{$position} = $itemid;
 9933:                     }
 9934:                 }
 9935:             }
 9936:             if (keys(%deletions)) {
 9937:                 foreach my $itemid (sort { $a <=> $b } keys(%deletions)) {
 9938:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
 9939:                 }
 9940:             }
 9941:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
 9942:                 my $itemid = $bynum{$pos};
 9943:                 if (ref($confhash{$itemid}) eq 'HASH') {
 9944:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'name'}.'</b><ul>';
 9945:                     my $position = $pos + 1;
 9946:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
 9947:                     if ($confhash{$itemid}{'ip'} eq '') {
 9948:                         $resulttext .= '<li>'.&mt('No IP Range(s) set').'</li>';
 9949:                     } else {
 9950:                         $resulttext .= '<li>'.&mt('IP Range(s): [_1]',$confhash{$itemid}{'ip'}).'</li>';
 9951:                     }
 9952:                     if (keys(%{$confhash{$itemid}{'commblocks'}})) {
 9953:                         $resulttext .= '<li>'.&mt('Functionality Blocked: [_1]',
 9954:                                                   join(', ', map { $types->{$_}; } sort(keys(%{$confhash{$itemid}{'commblocks'}})))).
 9955:                                        '</li>';
 9956:                     } else {
 9957:                         $resulttext .= '<li>'.&mt('No functionality blocked').'</li>';
 9958:                     }
 9959:                     if (keys(%{$confhash{$itemid}{'courses'}})) {
 9960:                         my @courses;
 9961:                         foreach my $cid (sort(keys(%{$confhash{$itemid}{'courses'}}))) {
 9962:                             my %courseinfo = &Apache::lonnet::coursedescription($cid,{'one_time' => 1});
 9963:                             push(@courses,$courseinfo{'description'}.' ('.$cid.')');
 9964:                         }
 9965:                         $resulttext .= '<li>'.&mt('Courses/Communities allowed').':<ul><li>'.
 9966:                                              join('</li><li>',@courses).'</li></ul>';
 9967:                     } else {
 9968:                         $resulttext .= '<li>'.&mt('No courses allowed').'</li>';
 9969:                     }
 9970:                     $resulttext .= '</ul></li>';
 9971:                 }
 9972:             }
 9973:             $resulttext .= '</ul>';
 9974:         } else {
 9975:             $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
 9976:         }
 9977:     } else {
 9978:         $resulttext = &mt('No changes made');
 9979:     }
 9980:     if ($errors) {
 9981:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
 9982:                        $errors.'</ul></p>';
 9983:     }
 9984:     return $resulttext;
 9985: }
 9986: 
 9987: sub get_ipaccess_id {
 9988:     my ($domain,$location) = @_;
 9989:     # get lock on ipaccess db
 9990:     my $lockhash = {
 9991:                       lock => $env{'user.name'}.
 9992:                               ':'.$env{'user.domain'},
 9993:                    };
 9994:     my $tries = 0;
 9995:     my $gotlock = &Apache::lonnet::newput_dom('ipaccess',$lockhash,$domain);
 9996:     my ($id,$error);
 9997: 
 9998:     while (($gotlock ne 'ok') && ($tries<10)) {
 9999:         $tries ++;
10000:         sleep (0.1);
10001:         $gotlock = &Apache::lonnet::newput_dom('ipaccess',$lockhash,$domain);
10002:     }
10003:     if ($gotlock eq 'ok') {
10004:         my %currids = &Apache::lonnet::dump_dom('ipaccess',$domain);
10005:         if ($currids{'lock'}) {
10006:             delete($currids{'lock'});
10007:             if (keys(%currids)) {
10008:                 my @curr = sort { $a <=> $b } keys(%currids);
10009:                 if ($curr[-1] =~ /^\d+$/) {
10010:                     $id = 1 + $curr[-1];
10011:                 }
10012:             } else {
10013:                 $id = 1;
10014:             }
10015:             if ($id) {
10016:                 unless (&Apache::lonnet::newput_dom('ipaccess',{ $id => $location },$domain) eq 'ok') {
10017:                     $error = 'nostore';
10018:                 }
10019:             } else {
10020:                 $error = 'nonumber';
10021:             }
10022:         }
10023:         my $dellockoutcome = &Apache::lonnet::del_dom('ipaccess',['lock'],$domain);
10024:     } else {
10025:         $error = 'nolock';
10026:     }
10027:     return ($id,$error);
10028: }
10029: 
10030: sub modify_rolecolors {
10031:     my ($r,$dom,$confname,$roles,$lastactref,%domconfig) = @_;
10032:     my ($resulttext,%rolehash);
10033:     $rolehash{'rolecolors'} = {};
10034:     if (ref($domconfig{'rolecolors'}) ne 'HASH') {
10035:         if ($domconfig{'rolecolors'} eq '') {
10036:             $domconfig{'rolecolors'} = {};
10037:         }
10038:     }
10039:     my ($errors,%changes) = &modify_colors($r,$dom,$confname,$roles,
10040:                          $domconfig{'rolecolors'},$rolehash{'rolecolors'});
10041:     my $putresult = &Apache::lonnet::put_dom('configuration',\%rolehash,
10042:                                              $dom);
10043:     if ($putresult eq 'ok') {
10044:         if (keys(%changes) > 0) {
10045:             &Apache::loncommon::devalidate_domconfig_cache($dom);
10046:             if (ref($lastactref) eq 'HASH') {
10047:                 $lastactref->{'domainconfig'} = 1;
10048:             }
10049:             $resulttext = &display_colorchgs($dom,\%changes,$roles,
10050:                                              $rolehash{'rolecolors'});
10051:         } else {
10052:             $resulttext = &mt('No changes made to default color schemes');
10053:         }
10054:     } else {
10055:         $resulttext = '<span class="LC_error">'.
10056: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
10057:     }
10058:     if ($errors) {
10059:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
10060:                        $errors.'</ul>';
10061:     }
10062:     return $resulttext;
10063: }
10064: 
10065: sub modify_colors {
10066:     my ($r,$dom,$confname,$roles,$domconfig,$confhash) = @_;
10067:     my (%changes,%choices);
10068:     my @bgs;
10069:     my @links = ('link','alink','vlink');
10070:     my @logintext;
10071:     my @images;
10072:     my $servadm = $r->dir_config('lonAdmEMail');
10073:     my $errors;
10074:     my %defaults;
10075:     foreach my $role (@{$roles}) {
10076:         if ($role eq 'login') {
10077:             %choices = &login_choices();
10078:             @logintext = ('textcol','bgcol');
10079:         } else {
10080:             %choices = &color_font_choices();
10081:         }
10082:         if ($role eq 'login') {
10083:             @images = ('img','logo','domlogo','login');
10084:             @bgs = ('pgbg','mainbg','sidebg');
10085:         } else {
10086:             @images = ('img');
10087:             @bgs = ('pgbg','tabbg','sidebg');
10088:         }
10089:         my %defaults = &role_defaults($role,\@bgs,\@links,\@images,\@logintext);
10090:         unless ($env{'form.'.$role.'_font'} eq $defaults{'font'}) {
10091:             $confhash->{$role}{'font'} = $env{'form.'.$role.'_font'};
10092:         }
10093:         if ($role eq 'login') {
10094:             foreach my $item (@logintext) {
10095:                 $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
10096:                 if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
10097:                     $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
10098:                 }
10099:                 unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'logintext'}{$item})) {
10100:                     $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
10101:                 }
10102:             }
10103:         } else {
10104:             $env{'form.'.$role.'_fontmenu'} = lc($env{'form.'.$role.'_fontmenu'});
10105:             if ($env{'form.'.$role.'_fontmenu'} =~ /^\w+/) {
10106:                 $env{'form.'.$role.'_fontmenu'} = '#'.$env{'form.'.$role.'_fontmenu'};
10107:             }
10108:             unless($env{'form.'.$role.'_fontmenu'} eq lc($defaults{'fontmenu'})) {
10109:                 $confhash->{$role}{'fontmenu'} = $env{'form.'.$role.'_fontmenu'};
10110:             }
10111:         }
10112:         foreach my $item (@bgs) {
10113:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
10114:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
10115:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
10116:             }
10117:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'bgs'}{$item})) {
10118:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
10119:             }
10120:         }
10121:         foreach my $item (@links) {
10122:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
10123:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
10124:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
10125:             }
10126:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'links'}{$item})) {
10127:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
10128:             }
10129:         }
10130:         my ($configuserok,$author_ok,$switchserver) = 
10131:             &config_check($dom,$confname,$servadm);
10132:         my ($width,$height) = &thumb_dimensions();
10133:         if (ref($domconfig->{$role}) ne 'HASH') {
10134:             $domconfig->{$role} = {};
10135:         }
10136:         foreach my $img (@images) {
10137:             if ($role eq 'login') { 
10138:                 if (($img eq 'img') || ($img eq 'logo')) {  
10139:                     if (defined($env{'form.login_showlogo_'.$img})) {
10140:                         $confhash->{$role}{'showlogo'}{$img} = 1;
10141:                     } else { 
10142:                         $confhash->{$role}{'showlogo'}{$img} = 0;
10143:                     }
10144:                 }
10145:                 if ($env{'form.login_alt_'.$img} ne '') {
10146:                     $confhash->{$role}{'alttext'}{$img} = $env{'form.login_alt_'.$img};
10147:                 }
10148:             }
10149: 	    if ( ! $env{'form.'.$role.'_'.$img.'.filename'} 
10150: 		 && !defined($domconfig->{$role}{$img})
10151: 		 && !$env{'form.'.$role.'_del_'.$img}
10152: 		 && $env{'form.'.$role.'_import_'.$img}) {
10153: 		# import the old configured image from the .tab setting
10154: 		# if they haven't provided a new one 
10155: 		$domconfig->{$role}{$img} = 
10156: 		    $env{'form.'.$role.'_import_'.$img};
10157: 	    }
10158:             if ($env{'form.'.$role.'_'.$img.'.filename'} ne '') {
10159:                 my $error;
10160:                 if ($configuserok eq 'ok') {
10161:                     if ($switchserver) {
10162:                         $error = &mt("Upload of [_1] image for $role page(s) is not permitted to this server: [_2]",$choices{$img},$switchserver);
10163:                     } else {
10164:                         if ($author_ok eq 'ok') {
10165:                             my ($result,$logourl) = 
10166:                                 &publishlogo($r,'upload',$role.'_'.$img,
10167:                                            $dom,$confname,$img,$width,$height);
10168:                             if ($result eq 'ok') {
10169:                                 $confhash->{$role}{$img} = $logourl;
10170:                                 $changes{$role}{'images'}{$img} = 1;
10171:                             } else {
10172:                                 $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);
10173:                             }
10174:                         } else {
10175:                             $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);
10176:                         }
10177:                     }
10178:                 } else {
10179:                     $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);
10180:                 }
10181:                 if ($error) {
10182:                     &Apache::lonnet::logthis($error);
10183:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
10184:                 }
10185:             } elsif ($domconfig->{$role}{$img} ne '') {
10186:                 if ($domconfig->{$role}{$img} !~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
10187:                     my $error;
10188:                     if ($configuserok eq 'ok') {
10189: # is confname an author?
10190:                         if ($switchserver eq '') {
10191:                             if ($author_ok eq 'ok') {
10192:                                 my ($result,$logourl) = 
10193:                                &publishlogo($r,'copy',$domconfig->{$role}{$img},
10194:                                             $dom,$confname,$img,$width,$height);
10195:                                 if ($result eq 'ok') {
10196:                                     $confhash->{$role}{$img} = $logourl;
10197: 				    $changes{$role}{'images'}{$img} = 1;
10198:                                 }
10199:                             }
10200:                         }
10201:                     }
10202:                 }
10203:             }
10204:         }
10205:         if (ref($domconfig) eq 'HASH') {
10206:             if (ref($domconfig->{$role}) eq 'HASH') {
10207:                 foreach my $img (@images) {
10208:                     if ($domconfig->{$role}{$img} ne '') {
10209:                         if ($env{'form.'.$role.'_del_'.$img}) {
10210:                             $confhash->{$role}{$img} = '';
10211:                             $changes{$role}{'images'}{$img} = 1;
10212:                         } else {
10213:                             if ($confhash->{$role}{$img} eq '') {
10214:                                 $confhash->{$role}{$img} = $domconfig->{$role}{$img};
10215:                             }
10216:                         }
10217:                     } else {
10218:                         if ($env{'form.'.$role.'_del_'.$img}) {
10219:                             $confhash->{$role}{$img} = '';
10220:                             $changes{$role}{'images'}{$img} = 1;
10221:                         } 
10222:                     }
10223:                     if ($role eq 'login') {
10224:                         if (($img eq 'logo') || ($img eq 'img')) {
10225:                             if (ref($domconfig->{'login'}{'showlogo'}) eq 'HASH') {
10226:                                 if ($confhash->{$role}{'showlogo'}{$img} ne 
10227:                                     $domconfig->{$role}{'showlogo'}{$img}) {
10228:                                     $changes{$role}{'showlogo'}{$img} = 1; 
10229:                                 }
10230:                             } else {
10231:                                 if ($confhash->{$role}{'showlogo'}{$img} == 0) {
10232:                                     $changes{$role}{'showlogo'}{$img} = 1;
10233:                                 }
10234:                             }
10235:                         }
10236:                         if ($img ne 'login') {
10237:                             if (ref($domconfig->{$role}{'alttext'}) eq 'HASH') {
10238:                                 if ($confhash->{$role}{'alttext'}{$img} ne
10239:                                     $domconfig->{$role}{'alttext'}{$img}) {
10240:                                     $changes{$role}{'alttext'}{$img} = 1;
10241:                                 }
10242:                             } else {
10243:                                 if ($confhash->{$role}{'alttext'}{$img} ne '') {
10244:                                     $changes{$role}{'alttext'}{$img} = 1;
10245:                                 }
10246:                             }
10247:                         }
10248:                     }
10249:                 }
10250:                 if ($domconfig->{$role}{'font'} ne '') {
10251:                     if ($confhash->{$role}{'font'} ne $domconfig->{$role}{'font'}) {
10252:                         $changes{$role}{'font'} = 1;
10253:                     }
10254:                 } else {
10255:                     if ($confhash->{$role}{'font'}) {
10256:                         $changes{$role}{'font'} = 1;
10257:                     }
10258:                 }
10259:                 if ($role ne 'login') {
10260:                     if ($domconfig->{$role}{'fontmenu'} ne '') {
10261:                         if ($confhash->{$role}{'fontmenu'} ne $domconfig->{$role}{'fontmenu'}) {
10262:                             $changes{$role}{'fontmenu'} = 1;
10263:                         }
10264:                     } else {
10265:                         if ($confhash->{$role}{'fontmenu'}) {
10266:                             $changes{$role}{'fontmenu'} = 1;
10267:                         }
10268:                     }
10269:                 }
10270:                 foreach my $item (@bgs) {
10271:                     if ($domconfig->{$role}{$item} ne '') {
10272:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
10273:                             $changes{$role}{'bgs'}{$item} = 1;
10274:                         } 
10275:                     } else {
10276:                         if ($confhash->{$role}{$item}) {
10277:                             $changes{$role}{'bgs'}{$item} = 1;
10278:                         }
10279:                     }
10280:                 }
10281:                 foreach my $item (@links) {
10282:                     if ($domconfig->{$role}{$item} ne '') {
10283:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
10284:                             $changes{$role}{'links'}{$item} = 1;
10285:                         }
10286:                     } else {
10287:                         if ($confhash->{$role}{$item}) {
10288:                             $changes{$role}{'links'}{$item} = 1;
10289:                         }
10290:                     }
10291:                 }
10292:                 foreach my $item (@logintext) {
10293:                     if ($domconfig->{$role}{$item} ne '') {
10294:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
10295:                             $changes{$role}{'logintext'}{$item} = 1;
10296:                         }
10297:                     } else {
10298:                         if ($confhash->{$role}{$item}) {
10299:                             $changes{$role}{'logintext'}{$item} = 1;
10300:                         }
10301:                     }
10302:                 }
10303:             } else {
10304:                 &default_change_checker($role,\@images,\@links,\@bgs,
10305:                                         \@logintext,$confhash,\%changes); 
10306:             }
10307:         } else {
10308:             &default_change_checker($role,\@images,\@links,\@bgs,
10309:                                     \@logintext,$confhash,\%changes); 
10310:         }
10311:     }
10312:     return ($errors,%changes);
10313: }
10314: 
10315: sub config_check {
10316:     my ($dom,$confname,$servadm) = @_;
10317:     my ($configuserok,$author_ok,$switchserver,%currroles);
10318:     my $uhome = &Apache::lonnet::homeserver($confname,$dom,1);
10319:     ($configuserok,%currroles) = &check_configuser($uhome,$dom,
10320:                                                    $confname,$servadm);
10321:     if ($configuserok eq 'ok') {
10322:         $switchserver = &check_switchserver($dom,$confname);
10323:         if ($switchserver eq '') {
10324:             $author_ok = &check_authorstatus($dom,$confname,%currroles);
10325:         }
10326:     }
10327:     return ($configuserok,$author_ok,$switchserver);
10328: }
10329: 
10330: sub default_change_checker {
10331:     my ($role,$images,$links,$bgs,$logintext,$confhash,$changes) = @_;
10332:     foreach my $item (@{$links}) {
10333:         if ($confhash->{$role}{$item}) {
10334:             $changes->{$role}{'links'}{$item} = 1;
10335:         }
10336:     }
10337:     foreach my $item (@{$bgs}) {
10338:         if ($confhash->{$role}{$item}) {
10339:             $changes->{$role}{'bgs'}{$item} = 1;
10340:         }
10341:     }
10342:     foreach my $item (@{$logintext}) {
10343:         if ($confhash->{$role}{$item}) {
10344:             $changes->{$role}{'logintext'}{$item} = 1;
10345:         }
10346:     }
10347:     foreach my $img (@{$images}) {
10348:         if ($env{'form.'.$role.'_del_'.$img}) {
10349:             $confhash->{$role}{$img} = '';
10350:             $changes->{$role}{'images'}{$img} = 1;
10351:         }
10352:         if ($role eq 'login') {
10353:             if ($confhash->{$role}{'showlogo'}{$img} == 0) {
10354:                 $changes->{$role}{'showlogo'}{$img} = 1;
10355:             }
10356:             if (ref($confhash->{$role}{'alttext'}) eq 'HASH') {
10357:                 if ($confhash->{$role}{'alttext'}{$img} ne '') {
10358:                     $changes->{$role}{'alttext'}{$img} = 1;
10359:                 }
10360:             }
10361:         }
10362:     }
10363:     if ($confhash->{$role}{'font'}) {
10364:         $changes->{$role}{'font'} = 1;
10365:     }
10366: }
10367: 
10368: sub display_colorchgs {
10369:     my ($dom,$changes,$roles,$confhash) = @_;
10370:     my (%choices,$resulttext);
10371:     if (!grep(/^login$/,@{$roles})) {
10372:         $resulttext = &mt('Changes made:').'<br />';
10373:     }
10374:     foreach my $role (@{$roles}) {
10375:         if ($role eq 'login') {
10376:             %choices = &login_choices();
10377:         } else {
10378:             %choices = &color_font_choices();
10379:         }
10380:         if (ref($changes->{$role}) eq 'HASH') {
10381:             if ($role ne 'login') {
10382:                 $resulttext .= '<h4>'.&mt($role).'</h4>';
10383:             }
10384:             foreach my $key (sort(keys(%{$changes->{$role}}))) {
10385:                 if ($role ne 'login') {
10386:                     $resulttext .= '<ul>';
10387:                 }
10388:                 if (ref($changes->{$role}{$key}) eq 'HASH') {
10389:                     if ($role ne 'login') {
10390:                         $resulttext .= '<li>'.&mt($choices{$key}).':<ul>';
10391:                     }
10392:                     foreach my $item (sort(keys(%{$changes->{$role}{$key}}))) {
10393:                         if (($role eq 'login') && ($key eq 'showlogo')) {
10394:                             if ($confhash->{$role}{$key}{$item}) {
10395:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to be displayed").'</li>';
10396:                             } else {
10397:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to not be displayed").'</li>';
10398:                             }
10399:                         } elsif (($role eq 'login') && ($key eq 'alttext')) {
10400:                             if ($confhash->{$role}{$key}{$item} ne '') {
10401:                                 $resulttext .= '<li>'.&mt("$choices{$key} for $choices{$item} set to [_1].",
10402:                                                $confhash->{$role}{$key}{$item}).'</li>';
10403:                             } else {
10404:                                 $resulttext .= '<li>'.&mt("$choices{$key} for $choices{$item} deleted.").'</li>';
10405:                             }
10406:                         } elsif ($confhash->{$role}{$item} eq '') {
10407:                             $resulttext .= '<li>'.&mt("$choices{$item} set to default").'</li>';
10408:                         } else {
10409:                             my $newitem = $confhash->{$role}{$item};
10410:                             if ($key eq 'images') {
10411:                                 $newitem = '<img src="'.$confhash->{$role}{$item}.'" alt="'.$choices{$item}.'" valign="bottom" />';
10412:                             }
10413:                             $resulttext .= '<li>'.&mt("$choices{$item} set to [_1]",$newitem).'</li>';
10414:                         }
10415:                     }
10416:                     if ($role ne 'login') {
10417:                         $resulttext .= '</ul></li>';
10418:                     }
10419:                 } else {
10420:                     if ($confhash->{$role}{$key} eq '') {
10421:                         $resulttext .= '<li>'.&mt("$choices{$key} set to default").'</li>';
10422:                     } else {
10423:                         $resulttext .= '<li>'.&mt("$choices{$key} set to [_1]",$confhash->{$role}{$key}).'</li>';
10424:                     }
10425:                 }
10426:                 if ($role ne 'login') {
10427:                     $resulttext .= '</ul>';
10428:                 }
10429:             }
10430:         }
10431:     }
10432:     return $resulttext;
10433: }
10434: 
10435: sub thumb_dimensions {
10436:     return ('200','50');
10437: }
10438: 
10439: sub check_dimensions {
10440:     my ($inputfile) = @_;
10441:     my ($fullwidth,$fullheight);
10442:     if ($inputfile =~ m|^[/\w.\-]+$|) {
10443:         if (open(PIPE,"identify $inputfile 2>&1 |")) {
10444:             my $imageinfo = <PIPE>;
10445:             if (!close(PIPE)) {
10446:                 &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
10447:             }
10448:             chomp($imageinfo);
10449:             my ($fullsize) = 
10450:                 ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
10451:             if ($fullsize) {
10452:                 ($fullwidth,$fullheight) = split(/x/,$fullsize);
10453:             }
10454:         }
10455:     }
10456:     return ($fullwidth,$fullheight);
10457: }
10458: 
10459: sub check_configuser {
10460:     my ($uhome,$dom,$confname,$servadm) = @_;
10461:     my ($configuserok,%currroles);
10462:     if ($uhome eq 'no_host') {
10463:         srand( time() ^ ($$ + ($$ << 15))  ); # Seed rand.
10464:         my $configpass = &LONCAPA::Enrollment::create_password($dom);
10465:         $configuserok = 
10466:             &Apache::lonnet::modifyuser($dom,$confname,'','internal',
10467:                              $configpass,'','','','','',undef,$servadm);
10468:     } else {
10469:         $configuserok = 'ok';
10470:         %currroles = 
10471:             &Apache::lonnet::get_my_roles($confname,$dom,'userroles');
10472:     }
10473:     return ($configuserok,%currroles);
10474: }
10475: 
10476: sub check_authorstatus {
10477:     my ($dom,$confname,%currroles) = @_;
10478:     my $author_ok;
10479:     if (!$currroles{':'.$dom.':au'}) {
10480:         my $start = time;
10481:         my $end = 0;
10482:         $author_ok = 
10483:             &Apache::lonnet::assignrole($dom,$confname,'/'.$dom.'/',
10484:                                         'au',$end,$start,'','','domconfig');
10485:     } else {
10486:         $author_ok = 'ok';
10487:     }
10488:     return $author_ok;
10489: }
10490: 
10491: sub publishlogo {
10492:     my ($r,$action,$formname,$dom,$confname,$subdir,$thumbwidth,$thumbheight,$savefileas) = @_;
10493:     my ($output,$fname,$logourl);
10494:     if ($action eq 'upload') {
10495:         $fname=$env{'form.'.$formname.'.filename'};
10496:         chop($env{'form.'.$formname});
10497:     } else {
10498:         ($fname) = ($formname =~ /([^\/]+)$/);
10499:     }
10500:     if ($savefileas ne '') {
10501:         $fname = $savefileas;
10502:     }
10503:     $fname=&Apache::lonnet::clean_filename($fname);
10504: # See if there is anything left
10505:     unless ($fname) { return ('error: no uploaded file'); }
10506:     $fname="$subdir/$fname";
10507:     my $docroot=$r->dir_config('lonDocRoot');
10508:     my $filepath="$docroot/priv";
10509:     my $relpath = "$dom/$confname";
10510:     my ($fnamepath,$file,$fetchthumb);
10511:     $file=$fname;
10512:     if ($fname=~m|/|) {
10513:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
10514:     }
10515:     my @parts=split(/\//,"$filepath/$relpath/$fnamepath");
10516:     my $count;
10517:     for ($count=5;$count<=$#parts;$count++) {
10518:         $filepath.="/$parts[$count]";
10519:         if ((-e $filepath)!=1) {
10520:             mkdir($filepath,02770);
10521:         }
10522:     }
10523:     # Check for bad extension and disallow upload
10524:     if ($file=~/\.(\w+)$/ &&
10525:         (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
10526:         $output = 
10527:             &mt('Invalid file extension ([_1]) - reserved for internal use.',$1); 
10528:     } elsif ($file=~/\.(\w+)$/ &&
10529:         !defined(&Apache::loncommon::fileembstyle($1))) {
10530:         $output = &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
10531:     } elsif ($file=~/\.(\d+)\.(\w+)$/) {
10532:         $output = &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
10533:     } elsif (-d "$filepath/$file") {
10534:         $output = &mt('Filename is a directory name - rename the file and re-upload');
10535:     } else {
10536:         my $source = $filepath.'/'.$file;
10537:         my $logfile;
10538:         if (!open($logfile,">>",$source.'.log')) {
10539:             return (&mt('No write permission to Authoring Space'));
10540:         }
10541:         print $logfile
10542: "\n================= Publish ".localtime()." ================\n".
10543: $env{'user.name'}.':'.$env{'user.domain'}."\n";
10544: # Save the file
10545:         if (!open(FH,">",$source)) {
10546:             &Apache::lonnet::logthis('Failed to create '.$source);
10547:             return (&mt('Failed to create file'));
10548:         }
10549:         if ($action eq 'upload') {
10550:             if (!print FH ($env{'form.'.$formname})) {
10551:                 &Apache::lonnet::logthis('Failed to write to '.$source);
10552:                 return (&mt('Failed to write file'));
10553:             }
10554:         } else {
10555:             my $original = &Apache::lonnet::filelocation('',$formname);
10556:             if(!copy($original,$source)) {
10557:                 &Apache::lonnet::logthis('Failed to copy '.$original.' to '.$source);
10558:                 return (&mt('Failed to write file'));
10559:             }
10560:         }
10561:         close(FH);
10562:         chmod(0660, $source); # Permissions to rw-rw---.
10563: 
10564:         my $targetdir=$docroot.'/res/'.$dom.'/'.$confname .'/'.$fnamepath;
10565:         my $copyfile=$targetdir.'/'.$file;
10566: 
10567:         my @parts=split(/\//,$targetdir);
10568:         my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
10569:         for (my $count=5;$count<=$#parts;$count++) {
10570:             $path.="/$parts[$count]";
10571:             if (!-e $path) {
10572:                 print $logfile "\nCreating directory ".$path;
10573:                 mkdir($path,02770);
10574:             }
10575:         }
10576:         my $versionresult;
10577:         if (-e $copyfile) {
10578:             $versionresult = &logo_versioning($targetdir,$file,$logfile);
10579:         } else {
10580:             $versionresult = 'ok';
10581:         }
10582:         if ($versionresult eq 'ok') {
10583:             if (copy($source,$copyfile)) {
10584:                 print $logfile "\nCopied original source to ".$copyfile."\n";
10585:                 $output = 'ok';
10586:                 $logourl = '/res/'.$dom.'/'.$confname.'/'.$fname;
10587:                 push(@{$modified_urls},[$copyfile,$source]);
10588:                 my $metaoutput = 
10589:                     &write_metadata($dom,$confname,$formname,$targetdir,$file,$logfile);
10590:                 unless ($registered_cleanup) {
10591:                     my $handlers = $r->get_handlers('PerlCleanupHandler');
10592:                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
10593:                     $registered_cleanup=1;
10594:                 }
10595:             } else {
10596:                 print $logfile "\nUnable to write ".$copyfile.':'.$!."\n";
10597:                 $output = &mt('Failed to copy file to RES space').", $!";
10598:             }
10599:             if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
10600:                 my $inputfile = $filepath.'/'.$file;
10601:                 my $outfile = $filepath.'/'.'tn-'.$file;
10602:                 my ($fullwidth,$fullheight) = &check_dimensions($inputfile);
10603:                 if ($fullwidth ne '' && $fullheight ne '') { 
10604:                     if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
10605:                         my $thumbsize = $thumbwidth.'x'.$thumbheight;
10606:                         my @args = ('convert','-sample',$thumbsize,$inputfile,$outfile);
10607:                         system({$args[0]} @args);
10608:                         chmod(0660, $filepath.'/tn-'.$file);
10609:                         if (-e $outfile) {
10610:                             my $copyfile=$targetdir.'/tn-'.$file;
10611:                             if (copy($outfile,$copyfile)) {
10612:                                 print $logfile "\nCopied source to ".$copyfile."\n";
10613:                                 my $thumb_metaoutput = 
10614:                                     &write_metadata($dom,$confname,$formname,
10615:                                                     $targetdir,'tn-'.$file,$logfile);
10616:                                 push(@{$modified_urls},[$copyfile,$outfile]);
10617:                                 unless ($registered_cleanup) {
10618:                                     my $handlers = $r->get_handlers('PerlCleanupHandler');
10619:                                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
10620:                                     $registered_cleanup=1;
10621:                                 }
10622:                             } else {
10623:                                 print $logfile "\nUnable to write ".$copyfile.
10624:                                                ':'.$!."\n";
10625:                             }
10626:                         }
10627:                     }
10628:                 }
10629:             }
10630:         } else {
10631:             $output = $versionresult;
10632:         }
10633:     }
10634:     return ($output,$logourl);
10635: }
10636: 
10637: sub logo_versioning {
10638:     my ($targetdir,$file,$logfile) = @_;
10639:     my $target = $targetdir.'/'.$file;
10640:     my ($maxversion,$fn,$extn,$output);
10641:     $maxversion = 0;
10642:     if ($file =~ /^(.+)\.(\w+)$/) {
10643:         $fn=$1;
10644:         $extn=$2;
10645:     }
10646:     opendir(DIR,$targetdir);
10647:     while (my $filename=readdir(DIR)) {
10648:         if ($filename=~/\Q$fn\E\.(\d+)\.\Q$extn\E$/) {
10649:             $maxversion=($1>$maxversion)?$1:$maxversion;
10650:         }
10651:     }
10652:     $maxversion++;
10653:     print $logfile "\nCreating old version ".$maxversion."\n";
10654:     my $copyfile=$targetdir.'/'.$fn.'.'.$maxversion.'.'.$extn;
10655:     if (copy($target,$copyfile)) {
10656:         print $logfile "Copied old target to ".$copyfile."\n";
10657:         $copyfile=$copyfile.'.meta';
10658:         if (copy($target.'.meta',$copyfile)) {
10659:             print $logfile "Copied old target metadata to ".$copyfile."\n";
10660:             $output = 'ok';
10661:         } else {
10662:             print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
10663:             $output = &mt('Failed to copy old meta').", $!, ";
10664:         }
10665:     } else {
10666:         print $logfile "Unable to write ".$copyfile.':'.$!."\n";
10667:         $output = &mt('Failed to copy old target').", $!, ";
10668:     }
10669:     return $output;
10670: }
10671: 
10672: sub write_metadata {
10673:     my ($dom,$confname,$formname,$targetdir,$file,$logfile) = @_;
10674:     my (%metadatafields,%metadatakeys,$output);
10675:     $metadatafields{'title'}=$formname;
10676:     $metadatafields{'creationdate'}=time;
10677:     $metadatafields{'lastrevisiondate'}=time;
10678:     $metadatafields{'copyright'}='public';
10679:     $metadatafields{'modifyinguser'}=$env{'user.name'}.':'.
10680:                                          $env{'user.domain'};
10681:     $metadatafields{'authorspace'}=$confname.':'.$dom;
10682:     $metadatafields{'domain'}=$dom;
10683:     {
10684:         print $logfile "\nWrite metadata file for ".$targetdir.'/'.$file;
10685:         my $mfh;
10686:         if (open($mfh,">",$targetdir.'/'.$file.'.meta')) {
10687:             foreach (sort(keys(%metadatafields))) {
10688:                 unless ($_=~/\./) {
10689:                     my $unikey=$_;
10690:                     $unikey=~/^([A-Za-z]+)/;
10691:                     my $tag=$1;
10692:                     $tag=~tr/A-Z/a-z/;
10693:                     print $mfh "\n\<$tag";
10694:                     foreach (split(/\,/,$metadatakeys{$unikey})) {
10695:                         my $value=$metadatafields{$unikey.'.'.$_};
10696:                         $value=~s/\"/\'\'/g;
10697:                         print $mfh ' '.$_.'="'.$value.'"';
10698:                     }
10699:                     print $mfh '>'.
10700:                         &HTML::Entities::encode($metadatafields{$unikey},'<>&"')
10701:                             .'</'.$tag.'>';
10702:                 }
10703:             }
10704:             $output = 'ok';
10705:             print $logfile "\nWrote metadata";
10706:             close($mfh);
10707:         } else {
10708:             print $logfile "\nFailed to open metadata file";
10709:             $output = &mt('Could not write metadata');
10710:         }
10711:     }
10712:     return $output;
10713: }
10714: 
10715: sub notifysubscribed {
10716:     foreach my $targetsource (@{$modified_urls}){
10717:         next unless (ref($targetsource) eq 'ARRAY');
10718:         my ($target,$source)=@{$targetsource};
10719:         if ($source ne '') {
10720:             if (open(my $logfh,">>",$source.'.log')) {
10721:                 print $logfh "\nCleanup phase: Notifications\n";
10722:                 my @subscribed=&subscribed_hosts($target);
10723:                 foreach my $subhost (@subscribed) {
10724:                     print $logfh "\nNotifying host ".$subhost.':';
10725:                     my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
10726:                     print $logfh $reply;
10727:                 }
10728:                 my @subscribedmeta=&subscribed_hosts("$target.meta");
10729:                 foreach my $subhost (@subscribedmeta) {
10730:                     print $logfh "\nNotifying host for metadata only ".$subhost.':';
10731:                     my $reply=&Apache::lonnet::critical('update:'.$target.'.meta',
10732:                                                         $subhost);
10733:                     print $logfh $reply;
10734:                 }
10735:                 print $logfh "\n============ Done ============\n";
10736:                 close($logfh);
10737:             }
10738:         }
10739:     }
10740:     return OK;
10741: }
10742: 
10743: sub subscribed_hosts {
10744:     my ($target) = @_;
10745:     my @subscribed;
10746:     if (open(my $fh,"<","$target.subscription")) {
10747:         while (my $subline=<$fh>) {
10748:             if ($subline =~ /^($match_lonid):/) {
10749:                 my $host = $1;
10750:                 if ($host ne $Apache::lonnet::perlvar{'lonHostID'}) {
10751:                     unless (grep(/^\Q$host\E$/,@subscribed)) {
10752:                         push(@subscribed,$host);
10753:                     }
10754:                 }
10755:             }
10756:         }
10757:     }
10758:     return @subscribed;
10759: }
10760: 
10761: sub check_switchserver {
10762:     my ($dom,$confname) = @_;
10763:     my ($allowed,$switchserver);
10764:     my $home = &Apache::lonnet::homeserver($confname,$dom);
10765:     if ($home eq 'no_host') {
10766:         $home = &Apache::lonnet::domain($dom,'primary');
10767:     }
10768:     my @ids=&Apache::lonnet::current_machine_ids();
10769:     foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
10770:     if (!$allowed) {
10771: 	$switchserver='<a href="/adm/switchserver?otherserver='.$home.'&amp;role=dc./'.$dom.'/&amp;destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
10772:     }
10773:     return $switchserver;
10774: }
10775: 
10776: sub modify_quotas {
10777:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
10778:     my ($context,@usertools,@options,%validations,%titles,%confhash,%toolshash,
10779:         %limithash,$toolregexp,%conditions,$resulttext,%changes,$confname,$configuserok,
10780:         $author_ok,$switchserver,$errors,$validationitemsref,$validationnamesref,
10781:         $validationfieldsref);
10782:     if ($action eq 'quotas') {
10783:         $context = 'tools'; 
10784:     } else {
10785:         $context = $action;
10786:     }
10787:     if ($context eq 'requestcourses') {
10788:         @usertools = ('official','unofficial','community','textbook');
10789:         @options =('norequest','approval','validate','autolimit');
10790:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
10791:         %titles = &courserequest_titles();
10792:         $toolregexp = join('|',@usertools);
10793:         %conditions = &courserequest_conditions();
10794:         $confname = $dom.'-domainconfig';
10795:         my $servadm = $r->dir_config('lonAdmEMail');
10796:         ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
10797:         ($validationitemsref,$validationnamesref,$validationfieldsref) = 
10798:             &Apache::loncoursequeueadmin::requestcourses_validation_types();
10799:     } elsif ($context eq 'requestauthor') {
10800:         @usertools = ('author');
10801:         %titles = &authorrequest_titles();
10802:     } else {
10803:         @usertools = ('aboutme','blog','webdav','portfolio');
10804:         %titles = &tool_titles();
10805:     }
10806:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
10807:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
10808:     foreach my $key (keys(%env)) {
10809:         if ($context eq 'requestcourses') {
10810:             if ($key =~ /^form\.crsreq_($toolregexp)_(.+)$/) {
10811:                 my $item = $1;
10812:                 my $type = $2;
10813:                 if ($type =~ /^limit_(.+)/) {
10814:                     $limithash{$item}{$1} = $env{$key};
10815:                 } else {
10816:                     $confhash{$item}{$type} = $env{$key};
10817:                 }
10818:             }
10819:         } elsif ($context eq 'requestauthor') {
10820:             if ($key =~ /^\Qform.authorreq_\E(.+)$/) {
10821:                 $confhash{$1} = $env{$key};
10822:             }
10823:         } else {
10824:             if ($key =~ /^form\.quota_(.+)$/) {
10825:                 $confhash{'defaultquota'}{$1} = $env{$key};
10826:             } elsif ($key =~ /^form\.authorquota_(.+)$/) {
10827:                 $confhash{'authorquota'}{$1} = $env{$key};
10828:             } elsif ($key =~ /^form\.\Q$context\E_(.+)$/) {
10829:                 @{$toolshash{$1}} = &Apache::loncommon::get_env_multiple($key);
10830:             }
10831:         }
10832:     }
10833:     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
10834:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.'.$context.'notifyapproval');
10835:         @approvalnotify = sort(@approvalnotify);
10836:         $confhash{'notify'}{'approval'} = join(',',@approvalnotify);
10837:         my @crstypes = ('official','unofficial','community','textbook');
10838:         my @hasuniquecode = &Apache::loncommon::get_env_multiple('form.uniquecode');
10839:         foreach my $type (@hasuniquecode) {
10840:             if (grep(/^\Q$type\E$/,@crstypes)) {
10841:                 $confhash{'uniquecode'}{$type} = 1;
10842:             }
10843:         }
10844:         my (%newbook,%allpos);
10845:         if ($context eq 'requestcourses') {
10846:             foreach my $type ('textbooks','templates') {
10847:                 @{$allpos{$type}} = (); 
10848:                 my $invalid;
10849:                 if ($type eq 'textbooks') {
10850:                     $invalid = &mt('Invalid LON-CAPA course for textbook');
10851:                 } else {
10852:                     $invalid = &mt('Invalid LON-CAPA course for template');
10853:                 }
10854:                 if ($env{'form.'.$type.'_addbook'}) {
10855:                     if (($env{'form.'.$type.'_addbook_cnum'} =~ /^$match_courseid$/) &&
10856:                         ($env{'form.'.$type.'_addbook_cdom'} =~ /^$match_domain$/)) {
10857:                         if (&Apache::lonnet::homeserver($env{'form.'.$type.'_addbook_cnum'},
10858:                                                         $env{'form.'.$type.'_addbook_cdom'}) eq 'no_host') {
10859:                             $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
10860:                         } else {
10861:                             $newbook{$type} = $env{'form.'.$type.'_addbook_cdom'}.'_'.$env{'form.'.$type.'_addbook_cnum'};
10862:                             my $position = $env{'form.'.$type.'_addbook_pos'};
10863:                             $position =~ s/\D+//g;
10864:                             if ($position ne '') {
10865:                                 $allpos{$type}[$position] = $newbook{$type};
10866:                             }
10867:                         }
10868:                     } else {
10869:                         $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
10870:                     }
10871:                 }
10872:             } 
10873:         }
10874:         if (ref($domconfig{$action}) eq 'HASH') {
10875:             if (ref($domconfig{$action}{'notify'}) eq 'HASH') {
10876:                 if ($domconfig{$action}{'notify'}{'approval'} ne $confhash{'notify'}{'approval'}) {
10877:                     $changes{'notify'}{'approval'} = 1;
10878:                 }
10879:             } else {
10880:                 if ($confhash{'notify'}{'approval'}) {
10881:                     $changes{'notify'}{'approval'} = 1;
10882:                 }
10883:             }
10884:             if (ref($domconfig{$action}{'uniquecode'}) eq 'HASH') {
10885:                 if (ref($confhash{'uniquecode'}) eq 'HASH') {
10886:                     foreach my $crstype (keys(%{$domconfig{$action}{'uniquecode'}})) {
10887:                         unless ($confhash{'uniquecode'}{$crstype}) {
10888:                             $changes{'uniquecode'} = 1;
10889:                         }
10890:                     }
10891:                     unless ($changes{'uniquecode'}) {
10892:                         foreach my $crstype (keys(%{$confhash{'uniquecode'}})) {
10893:                             unless ($domconfig{$action}{'uniquecode'}{$crstype}) {
10894:                                 $changes{'uniquecode'} = 1;
10895:                             }
10896:                         }
10897:                     }
10898:                } else {
10899:                    $changes{'uniquecode'} = 1;
10900:                }
10901:             } elsif (ref($confhash{'uniquecode'}) eq 'HASH') {
10902:                 $changes{'uniquecode'} = 1;
10903:             }
10904:             if ($context eq 'requestcourses') {
10905:                 foreach my $type ('textbooks','templates') {
10906:                     if (ref($domconfig{$action}{$type}) eq 'HASH') {
10907:                         my %deletions;
10908:                         my @todelete = &Apache::loncommon::get_env_multiple('form.'.$type.'_del');
10909:                         if (@todelete) {
10910:                             map { $deletions{$_} = 1; } @todelete;
10911:                         }
10912:                         my %imgdeletions;
10913:                         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.'.$type.'_image_del');
10914:                         if (@todeleteimages) {
10915:                             map { $imgdeletions{$_} = 1; } @todeleteimages;
10916:                         }
10917:                         my $maxnum = $env{'form.'.$type.'_maxnum'};
10918:                         for (my $i=0; $i<=$maxnum; $i++) {
10919:                             my $itemid = $env{'form.'.$type.'_id_'.$i};
10920:                             my ($key) = ($itemid =~ /^\Q$type\E_(\w+)$/); 
10921:                             if (ref($domconfig{$action}{$type}{$key}) eq 'HASH') {
10922:                                 if ($deletions{$key}) {
10923:                                     if ($domconfig{$action}{$type}{$key}{'image'}) {
10924:                                         #FIXME need to obsolete item in RES space
10925:                                     }
10926:                                     next;
10927:                                 } else {
10928:                                     my $newpos = $env{'form.'.$itemid};
10929:                                     $newpos =~ s/\D+//g;
10930:                                     foreach my $item ('subject','title','publisher','author') {
10931:                                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
10932:                                                  ($type eq 'templates'));
10933:                                         $confhash{$type}{$key}{$item} = $env{'form.'.$type.'_'.$item.'_'.$i};
10934:                                         if ($domconfig{$action}{$type}{$key}{$item} ne $confhash{$type}{$key}{$item}) {
10935:                                             $changes{$type}{$key} = 1;
10936:                                         }
10937:                                     }
10938:                                     $allpos{$type}[$newpos] = $key;
10939:                                 }
10940:                                 if ($imgdeletions{$key}) {
10941:                                     $changes{$type}{$key} = 1;
10942:                                     #FIXME need to obsolete item in RES space
10943:                                 } elsif ($env{'form.'.$type.'_image_'.$i.'.filename'}) {
10944:                                     my ($cdom,$cnum) = split(/_/,$key);
10945:                                     if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
10946:                                         $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
10947:                                     } else {
10948:                                         my ($imgurl,$error) = &process_textbook_image($r,$dom,$confname,$type.'_image_'.$i,
10949:                                                                                       $cdom,$cnum,$type,$configuserok,
10950:                                                                                       $switchserver,$author_ok);
10951:                                         if ($imgurl) {
10952:                                             $confhash{$type}{$key}{'image'} = $imgurl;
10953:                                             $changes{$type}{$key} = 1; 
10954:                                         }
10955:                                         if ($error) {
10956:                                             &Apache::lonnet::logthis($error);
10957:                                             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
10958:                                         }
10959:                                     } 
10960:                                 } elsif ($domconfig{$action}{$type}{$key}{'image'}) {
10961:                                     $confhash{$type}{$key}{'image'} = 
10962:                                         $domconfig{$action}{$type}{$key}{'image'};
10963:                                 }
10964:                             }
10965:                         }
10966:                     }
10967:                 }
10968:             }
10969:         } else {
10970:             if ($confhash{'notify'}{'approval'}) {
10971:                 $changes{'notify'}{'approval'} = 1;
10972:             }
10973:             if (ref($confhash{'uniquecode'} eq 'HASH')) {
10974:                 $changes{'uniquecode'} = 1;
10975:             }
10976:         }
10977:         if ($context eq 'requestcourses') {
10978:             foreach my $type ('textbooks','templates') {
10979:                 if ($newbook{$type}) {
10980:                     $changes{$type}{$newbook{$type}} = 1;
10981:                     foreach my $item ('subject','title','publisher','author') {
10982:                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
10983:                                  ($type eq 'template'));
10984:                         $env{'form.'.$type.'_addbook_'.$item} =~ s/(`)/'/g;
10985:                         if ($env{'form.'.$type.'_addbook_'.$item}) {
10986:                             $confhash{$type}{$newbook{$type}}{$item} = $env{'form.'.$type.'_addbook_'.$item};
10987:                         }
10988:                     }
10989:                     if ($type eq 'textbooks') {
10990:                         if ($env{'form.'.$type.'_addbook_image.filename'} ne '') {
10991:                             my ($cdom,$cnum) = split(/_/,$newbook{$type});
10992:                             if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
10993:                                 $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
10994:                             } else {
10995:                                 my ($imageurl,$error) =
10996:                                     &process_textbook_image($r,$dom,$confname,$type.'_addbook_image',$cdom,$cnum,$type,
10997:                                                             $configuserok,$switchserver,$author_ok);
10998:                                 if ($imageurl) {
10999:                                     $confhash{$type}{$newbook{$type}}{'image'} = $imageurl;
11000:                                 }
11001:                                 if ($error) {
11002:                                     &Apache::lonnet::logthis($error);
11003:                                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
11004:                                 }
11005:                             }
11006:                         }
11007:                     }
11008:                 }
11009:                 if (@{$allpos{$type}} > 0) {
11010:                     my $idx = 0;
11011:                     foreach my $item (@{$allpos{$type}}) {
11012:                         if ($item ne '') {
11013:                             $confhash{$type}{$item}{'order'} = $idx;
11014:                             if (ref($domconfig{$action}) eq 'HASH') {
11015:                                 if (ref($domconfig{$action}{$type}) eq 'HASH') {
11016:                                     if (ref($domconfig{$action}{$type}{$item}) eq 'HASH') {
11017:                                         if ($domconfig{$action}{$type}{$item}{'order'} ne $idx) {
11018:                                             $changes{$type}{$item} = 1;
11019:                                         }
11020:                                     }
11021:                                 }
11022:                             }
11023:                             $idx ++;
11024:                         }
11025:                     }
11026:                 }
11027:             }
11028:             if (ref($validationitemsref) eq 'ARRAY') {
11029:                 foreach my $item (@{$validationitemsref}) {
11030:                     if ($item eq 'fields') {
11031:                         my @changed;
11032:                         @{$confhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.requestcourses_validation_'.$item);
11033:                         if (@{$confhash{'validation'}{$item}} > 0) {
11034:                             @{$confhash{'validation'}{$item}} = sort(@{$confhash{'validation'}{$item}});
11035:                         }
11036:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
11037:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
11038:                                 if (ref($domconfig{'requestcourses'}{'validation'}{$item}) eq 'ARRAY') {
11039:                                     @changed = &Apache::loncommon::compare_arrays($confhash{'validation'}{$item},
11040:                                                                                   $domconfig{'requestcourses'}{'validation'}{$item});
11041:                                 } else {
11042:                                     @changed = @{$confhash{'validation'}{$item}};
11043:                                 }
11044:                             } else {
11045:                                 @changed = @{$confhash{'validation'}{$item}};
11046:                             }
11047:                         } else {
11048:                             @changed = @{$confhash{'validation'}{$item}};
11049:                         }
11050:                         if (@changed) {
11051:                             if ($confhash{'validation'}{$item}) {
11052:                                 $changes{'validation'}{$item} = join(', ',@{$confhash{'validation'}{$item}});
11053:                             } else {
11054:                                 $changes{'validation'}{$item} = &mt('None');
11055:                             }
11056:                         }
11057:                     } else {
11058:                         $confhash{'validation'}{$item} = $env{'form.requestcourses_validation_'.$item};
11059:                         if ($item eq 'markup') {
11060:                             if ($env{'form.requestcourses_validation_'.$item}) {
11061:                                 $env{'form.requestcourses_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
11062:                             }
11063:                         }
11064:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
11065:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
11066:                                 if ($domconfig{'requestcourses'}{'validation'}{$item} ne $confhash{'validation'}{$item}) {
11067:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
11068:                                 }
11069:                             } else {
11070:                                 if ($confhash{'validation'}{$item} ne '') {
11071:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
11072:                                 }
11073:                             }
11074:                         } else {
11075:                             if ($confhash{'validation'}{$item} ne '') {
11076:                                 $changes{'validation'}{$item} = $confhash{'validation'}{$item};
11077:                             }
11078:                         }
11079:                     }
11080:                 }
11081:             }
11082:             if ($env{'form.validationdc'}) {
11083:                 my $newval = $env{'form.validationdc'};
11084:                 my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
11085:                 if (exists($domcoords{$newval})) {
11086:                     $confhash{'validation'}{'dc'} = $newval;
11087:                 }
11088:             }
11089:             if (ref($confhash{'validation'}) eq 'HASH') {
11090:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
11091:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
11092:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
11093:                             unless ($confhash{'validation'}{'dc'} eq $domconfig{'requestcourses'}{'validation'}{'dc'}) {
11094:                                 if ($confhash{'validation'}{'dc'} eq '') {
11095:                                     $changes{'validation'}{'dc'} = &mt('None');
11096:                                 } else {
11097:                                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
11098:                                 }
11099:                             }
11100:                         } elsif ($confhash{'validation'}{'dc'} ne '') {
11101:                             $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
11102:                         }
11103:                     } elsif ($confhash{'validation'}{'dc'} ne '') {
11104:                         $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
11105:                     }
11106:                 } elsif ($confhash{'validation'}{'dc'} ne '') {
11107:                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
11108:                 }
11109:             } else {
11110:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
11111:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
11112:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
11113:                             $changes{'validation'}{'dc'} = &mt('None');
11114:                         }
11115:                     }
11116:                 }
11117:             }
11118:         }
11119:     } else {
11120:         $confhash{'defaultquota'}{'default'} = $env{'form.defaultquota'};
11121:         $confhash{'authorquota'}{'default'} = $env{'form.authorquota'};
11122:     }
11123:     foreach my $item (@usertools) {
11124:         foreach my $type (@{$types},'default','_LC_adv') {
11125:             my $unset; 
11126:             if ($context eq 'requestcourses') {
11127:                 $unset = '0';
11128:                 if ($type eq '_LC_adv') {
11129:                     $unset = '';
11130:                 }
11131:                 if ($confhash{$item}{$type} eq 'autolimit') {
11132:                     $confhash{$item}{$type} .= '=';
11133:                     unless ($limithash{$item}{$type} =~ /\D/) {
11134:                         $confhash{$item}{$type} .= $limithash{$item}{$type};
11135:                     }
11136:                 }
11137:             } elsif ($context eq 'requestauthor') {
11138:                 $unset = '0';
11139:                 if ($type eq '_LC_adv') {
11140:                     $unset = '';
11141:                 }
11142:             } else {
11143:                 if (grep(/^\Q$type\E$/,@{$toolshash{$item}})) {
11144:                     $confhash{$item}{$type} = 1;
11145:                 } else {
11146:                     $confhash{$item}{$type} = 0;
11147:                 }
11148:             }
11149:             if (ref($domconfig{$action}) eq 'HASH') {
11150:                 if ($action eq 'requestauthor') {
11151:                     if ($domconfig{$action}{$type} ne $confhash{$type}) {
11152:                         $changes{$type} = 1;
11153:                     }
11154:                 } elsif (ref($domconfig{$action}{$item}) eq 'HASH') {
11155:                     if ($domconfig{$action}{$item}{$type} ne $confhash{$item}{$type}) {
11156:                         $changes{$item}{$type} = 1;
11157:                     }
11158:                 } else {
11159:                     if ($context eq 'requestcourses') {
11160:                         if ($confhash{$item}{$type} ne $unset) {
11161:                             $changes{$item}{$type} = 1;
11162:                         }
11163:                     } else {
11164:                         if (!$confhash{$item}{$type}) {
11165:                             $changes{$item}{$type} = 1;
11166:                         }
11167:                     }
11168:                 }
11169:             } else {
11170:                 if ($context eq 'requestcourses') {
11171:                     if ($confhash{$item}{$type} ne $unset) {
11172:                         $changes{$item}{$type} = 1;
11173:                     }
11174:                 } elsif ($context eq 'requestauthor') {
11175:                     if ($confhash{$type} ne $unset) {
11176:                         $changes{$type} = 1;
11177:                     }
11178:                 } else {
11179:                     if (!$confhash{$item}{$type}) {
11180:                         $changes{$item}{$type} = 1;
11181:                     }
11182:                 }
11183:             }
11184:         }
11185:     }
11186:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
11187:         if (ref($domconfig{'quotas'}) eq 'HASH') {
11188:             if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
11189:                 foreach my $key (keys(%{$domconfig{'quotas'}{'defaultquota'}})) {
11190:                     if (exists($confhash{'defaultquota'}{$key})) {
11191:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{'defaultquota'}{$key}) {
11192:                             $changes{'defaultquota'}{$key} = 1;
11193:                         }
11194:                     } else {
11195:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{'defaultquota'}{$key};
11196:                     }
11197:                 }
11198:             } else {
11199:                 foreach my $key (keys(%{$domconfig{'quotas'}})) {
11200:                     if (exists($confhash{'defaultquota'}{$key})) {
11201:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{$key}) {
11202:                             $changes{'defaultquota'}{$key} = 1;
11203:                         }
11204:                     } else {
11205:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{$key};
11206:                     }
11207:                 }
11208:             }
11209:             if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
11210:                 foreach my $key (keys(%{$domconfig{'quotas'}{'authorquota'}})) {
11211:                     if (exists($confhash{'authorquota'}{$key})) {
11212:                         if ($confhash{'authorquota'}{$key} ne $domconfig{'quotas'}{'authorquota'}{$key}) {
11213:                             $changes{'authorquota'}{$key} = 1;
11214:                         }
11215:                     } else {
11216:                         $confhash{'authorquota'}{$key} = $domconfig{'quotas'}{'authorquota'}{$key};
11217:                     }
11218:                 }
11219:             }
11220:         }
11221:         if (ref($confhash{'defaultquota'}) eq 'HASH') {
11222:             foreach my $key (keys(%{$confhash{'defaultquota'}})) {
11223:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
11224:                     if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
11225:                         if (!exists($domconfig{'quotas'}{'defaultquota'}{$key})) {
11226:                             $changes{'defaultquota'}{$key} = 1;
11227:                         }
11228:                     } else {
11229:                         if (!exists($domconfig{'quotas'}{$key})) {
11230:                             $changes{'defaultquota'}{$key} = 1;
11231:                         }
11232:                     }
11233:                 } else {
11234:                     $changes{'defaultquota'}{$key} = 1;
11235:                 }
11236:             }
11237:         }
11238:         if (ref($confhash{'authorquota'}) eq 'HASH') {
11239:             foreach my $key (keys(%{$confhash{'authorquota'}})) {
11240:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
11241:                     if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
11242:                         if (!exists($domconfig{'quotas'}{'authorquota'}{$key})) {
11243:                             $changes{'authorquota'}{$key} = 1;
11244:                         }
11245:                     } else {
11246:                         $changes{'authorquota'}{$key} = 1;
11247:                     }
11248:                 } else {
11249:                     $changes{'authorquota'}{$key} = 1;
11250:                 }
11251:             }
11252:         }
11253:     }
11254: 
11255:     if ($context eq 'requestauthor') {
11256:         $domdefaults{'requestauthor'} = \%confhash;
11257:     } else {
11258:         foreach my $key (keys(%confhash)) {
11259:             unless (($context eq 'requestcourses') && (($key eq 'textbooks') || ($key eq 'templates'))) {
11260:                 $domdefaults{$key} = $confhash{$key};
11261:             }
11262:         }
11263:     }
11264: 
11265:     my %quotahash = (
11266:                       $action => { %confhash }
11267:                     );
11268:     my $putresult = &Apache::lonnet::put_dom('configuration',\%quotahash,
11269:                                              $dom);
11270:     if ($putresult eq 'ok') {
11271:         if (keys(%changes) > 0) {
11272:             my $cachetime = 24*60*60;
11273:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
11274:             if (ref($lastactref) eq 'HASH') {
11275:                 $lastactref->{'domdefaults'} = 1;
11276:             }
11277:             $resulttext = &mt('Changes made:').'<ul>';
11278:             unless (($context eq 'requestcourses') ||
11279:                     ($context eq 'requestauthor')) {
11280:                 if (ref($changes{'defaultquota'}) eq 'HASH') {
11281:                     $resulttext .= '<li>'.&mt('Portfolio default quotas').'<ul>';
11282:                     foreach my $type (@{$types},'default') {
11283:                         if (defined($changes{'defaultquota'}{$type})) {
11284:                             my $typetitle = $usertypes->{$type};
11285:                             if ($type eq 'default') {
11286:                                 $typetitle = $othertitle;
11287:                             }
11288:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'defaultquota'}{$type}).'</li>';
11289:                         }
11290:                     }
11291:                     $resulttext .= '</ul></li>';
11292:                 }
11293:                 if (ref($changes{'authorquota'}) eq 'HASH') {
11294:                     $resulttext .= '<li>'.&mt('Authoring Space default quotas').'<ul>';
11295:                     foreach my $type (@{$types},'default') {
11296:                         if (defined($changes{'authorquota'}{$type})) {
11297:                             my $typetitle = $usertypes->{$type};
11298:                             if ($type eq 'default') {
11299:                                 $typetitle = $othertitle;
11300:                             }
11301:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'authorquota'}{$type}).'</li>';
11302:                         }
11303:                     }
11304:                     $resulttext .= '</ul></li>';
11305:                 }
11306:             }
11307:             my %newenv;
11308:             foreach my $item (@usertools) {
11309:                 my (%haschgs,%inconf);
11310:                 if ($context eq 'requestauthor') {
11311:                     %haschgs = %changes;
11312:                     %inconf = %confhash;
11313:                 } else {
11314:                     if (ref($changes{$item}) eq 'HASH') {
11315:                         %haschgs = %{$changes{$item}};
11316:                     }
11317:                     if (ref($confhash{$item}) eq 'HASH') {
11318:                         %inconf = %{$confhash{$item}};
11319:                     }
11320:                 }
11321:                 if (keys(%haschgs) > 0) {
11322:                     my $newacc = 
11323:                         &Apache::lonnet::usertools_access($env{'user.name'},
11324:                                                           $env{'user.domain'},
11325:                                                           $item,'reload',$context);
11326:                     if (($context eq 'requestcourses') ||
11327:                         ($context eq 'requestauthor')) {
11328:                         if ($env{'environment.canrequest.'.$item} ne $newacc) {
11329:                             $newenv{'environment.canrequest.'.$item} = $newacc;
11330:                         }
11331:                     } else {
11332:                         if ($env{'environment.availabletools.'.$item} ne $newacc) { 
11333:                             $newenv{'environment.availabletools.'.$item} = $newacc;
11334:                         }
11335:                     }
11336:                     unless ($context eq 'requestauthor') {
11337:                         $resulttext .= '<li>'.$titles{$item}.'<ul>';
11338:                     }
11339:                     foreach my $type (@{$types},'default','_LC_adv') {
11340:                         if ($haschgs{$type}) {
11341:                             my $typetitle = $usertypes->{$type};
11342:                             if ($type eq 'default') {
11343:                                 $typetitle = $othertitle;
11344:                             } elsif ($type eq '_LC_adv') {
11345:                                 $typetitle = 'LON-CAPA Advanced Users'; 
11346:                             }
11347:                             if ($inconf{$type}) {
11348:                                 if ($context eq 'requestcourses') {
11349:                                     my $cond;
11350:                                     if ($inconf{$type} =~ /^autolimit=(\d*)$/) {
11351:                                         if ($1 eq '') {
11352:                                             $cond = &mt('(Automatic processing of any request).');
11353:                                         } else {
11354:                                             $cond = &mt('(Automatic processing of requests up to limit of [quant,_1,request] per user).',$1);
11355:                                         }
11356:                                     } else { 
11357:                                         $cond = $conditions{$inconf{$type}};
11358:                                     }
11359:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1].',$typetitle).' '.$cond.'</li>';
11360:                                 } elsif ($context eq 'requestauthor') {
11361:                                     $resulttext .= '<li>'.&mt('Set to "[_1]" for "[_2]".',
11362:                                                              $titles{$inconf{$type}},$typetitle);
11363: 
11364:                                 } else {
11365:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1]',$typetitle).'</li>';
11366:                                 }
11367:                             } else {
11368:                                 if ($type eq '_LC_adv') {
11369:                                     if ($inconf{$type} eq '0') {
11370:                                         $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
11371:                                     } else { 
11372:                                         $resulttext .= '<li>'.&mt('No override set for [_1]',$typetitle).'</li>';
11373:                                     }
11374:                                 } else {
11375:                                     $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
11376:                                 }
11377:                             }
11378:                         }
11379:                     }
11380:                     unless ($context eq 'requestauthor') {
11381:                         $resulttext .= '</ul></li>';
11382:                     }
11383:                 }
11384:             }
11385:             if (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
11386:                 if (ref($changes{'notify'}) eq 'HASH') {
11387:                     if ($changes{'notify'}{'approval'}) {
11388:                         if (ref($confhash{'notify'}) eq 'HASH') {
11389:                             if ($confhash{'notify'}{'approval'}) {
11390:                                 $resulttext .= '<li>'.&mt('Notification of requests requiring approval will be sent to: ').$confhash{'notify'}{'approval'}.'</li>';
11391:                             } else {
11392:                                 $resulttext .= '<li>'.&mt('No Domain Coordinators will receive notification of requests requiring approval.').'</li>';
11393:                             }
11394:                         }
11395:                     }
11396:                 }
11397:             }
11398:             if ($action eq 'requestcourses') {
11399:                 my @offon = ('off','on');
11400:                 if ($changes{'uniquecode'}) {
11401:                     if (ref($confhash{'uniquecode'}) eq 'HASH') {
11402:                         my $codestr = join(' ',map{ &mt($_); } sort(keys(%{$confhash{'uniquecode'}})));
11403:                         $resulttext .= '<li>'.
11404:                                        &mt('Generation of six character code as course identifier for distribution to students set to on for: [_1].','<b>'.$codestr.'</b>').
11405:                                        '</li>';
11406:                     } else {
11407:                         $resulttext .= '<li>'.&mt('Generation of six character code as course identifier for distribution to students set to off.').
11408:                                        '</li>';
11409:                     }
11410:                 }
11411:                 foreach my $type ('textbooks','templates') {
11412:                     if (ref($changes{$type}) eq 'HASH') {
11413:                         $resulttext .= '<li>'.&mt("Available $type updated").'<ul>';
11414:                         foreach my $key (sort(keys(%{$changes{$type}}))) {
11415:                             my %coursehash = &Apache::lonnet::coursedescription($key);
11416:                             my $coursetitle = $coursehash{'description'};
11417:                             my $position = $confhash{$type}{$key}{'order'} + 1;
11418:                             $resulttext .= '<li>';
11419:                             foreach my $item ('subject','title','publisher','author') {
11420:                                 next if ((($item eq 'author') || ($item eq 'publisher')) &&
11421:                                          ($type eq 'templates'));
11422:                                 my $name = $item.':';
11423:                                 $name =~ s/^(\w)/\U$1/;
11424:                                 $resulttext .= &mt($name).' '.$confhash{$type}{$key}{$item}.'<br />';
11425:                             }
11426:                             $resulttext .= ' '.&mt('Order: [_1]',$position).'<br />';
11427:                             if ($type eq 'textbooks') {
11428:                                 if ($confhash{$type}{$key}{'image'}) {
11429:                                     $resulttext .= ' '.&mt('Image: [_1]',
11430:                                                    '<img src="'.$confhash{$type}{$key}{'image'}.'"'.
11431:                                                    ' alt="Textbook cover" />').'<br />';
11432:                                 }
11433:                             }
11434:                             $resulttext .= ' '.&mt('LON-CAPA Course: [_1]',$coursetitle).'</li>';
11435:                         }
11436:                         $resulttext .= '</ul></li>';
11437:                     }
11438:                 }
11439:                 if (ref($changes{'validation'}) eq 'HASH') {
11440:                     if ((ref($validationitemsref) eq 'ARRAY') && (ref($validationnamesref) eq 'HASH')) {
11441:                         $resulttext .= '<li>'.&mt('Validation of courses/communities updated').'<ul>';
11442:                         foreach my $item (@{$validationitemsref}) {
11443:                             if (exists($changes{'validation'}{$item})) {
11444:                                 if ($item eq 'markup') {
11445:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
11446:                                                               '<br /><pre>'.$changes{'validation'}{$item}.'</pre>').'</li>';
11447:                                 } else {
11448:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
11449:                                                               '<b>'.$changes{'validation'}{$item}.'</b>').'</li>';
11450:                                 }
11451:                             }
11452:                         }
11453:                         if (exists($changes{'validation'}{'dc'})) {
11454:                             $resulttext .= '<li>'.&mt('Validated course requests identified as processed by: [_1]',
11455:                                                      '<b>'.$changes{'validation'}{'dc'}.'</b>').'</li>';
11456:                         }
11457:                     }
11458:                 }
11459:             }
11460:             $resulttext .= '</ul>';
11461:             if (keys(%newenv)) {
11462:                 &Apache::lonnet::appenv(\%newenv);
11463:             }
11464:         } else {
11465:             if ($context eq 'requestcourses') {
11466:                 $resulttext = &mt('No changes made to rights to request creation of courses.');
11467:             } elsif ($context eq 'requestauthor') {
11468:                 $resulttext = &mt('No changes made to rights to request author space.');
11469:             } else {
11470:                 $resulttext = &mt('No changes made to availability of personal information pages, blogs, portfolios or default quotas');
11471:             }
11472:         }
11473:     } else {
11474:         $resulttext = '<span class="LC_error">'.
11475: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
11476:     }
11477:     if ($errors) {
11478:         $resulttext .= '<p>'.&mt('The following errors occurred when modifying Textbook settings.').
11479:                        '<ul>'.$errors.'</ul></p>';
11480:     }
11481:     return $resulttext;
11482: }
11483: 
11484: sub process_textbook_image {
11485:     my ($r,$dom,$confname,$caller,$cdom,$cnum,$type,$configuserok,$switchserver,$author_ok) = @_;
11486:     my $filename = $env{'form.'.$caller.'.filename'};
11487:     my ($error,$url);
11488:     my ($width,$height) = (50,50);
11489:     if ($configuserok eq 'ok') {
11490:         if ($switchserver) {
11491:             $error = &mt('Upload of textbook image is not permitted to this server: [_1]',
11492:                          $switchserver);
11493:         } elsif ($author_ok eq 'ok') {
11494:             my ($result,$imageurl) =
11495:                 &publishlogo($r,'upload',$caller,$dom,$confname,
11496:                              "$type/$cdom/$cnum/cover",$width,$height);
11497:             if ($result eq 'ok') {
11498:                 $url = $imageurl;
11499:             } else {
11500:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
11501:             }
11502:         } else {
11503:             $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);
11504:         }
11505:     } else {
11506:         $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);
11507:     }
11508:     return ($url,$error);
11509: }
11510: 
11511: sub modify_autoenroll {
11512:     my ($dom,$lastactref,%domconfig) = @_;
11513:     my ($resulttext,%changes);
11514:     my %currautoenroll;
11515:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
11516:         foreach my $key (keys(%{$domconfig{'autoenroll'}})) {
11517:             $currautoenroll{$key} = $domconfig{'autoenroll'}{$key};
11518:         }
11519:     }
11520:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
11521:     my %title = ( run => 'Auto-enrollment active',
11522:                   sender => 'Sender for notification messages',
11523:                   coowners => 'Automatic assignment of co-ownership to instructors of record (institutional data)',
11524:                   autofailsafe => 'Failsafe for no drops if institutional data missing for a section');
11525:     my @offon = ('off','on');
11526:     my $sender_uname = $env{'form.sender_uname'};
11527:     my $sender_domain = $env{'form.sender_domain'};
11528:     if ($sender_domain eq '') {
11529:         $sender_uname = '';
11530:     } elsif ($sender_uname eq '') {
11531:         $sender_domain = '';
11532:     }
11533:     my $coowners = $env{'form.autoassign_coowners'};
11534:     my $autofailsafe = $env{'form.autoenroll_autofailsafe'};
11535:     $autofailsafe =~ s{^\s+|\s+$}{}g;
11536:     if ($autofailsafe =~ /\D/) {
11537:         undef($autofailsafe);
11538:     }
11539:     my $failsafe = $env{'form.autoenroll_failsafe'};
11540:     unless (($failsafe eq 'zero') || ($failsafe eq 'any')) {
11541:         $failsafe = 'off';
11542:         undef($autofailsafe);
11543:     }
11544:     my %autoenrollhash =  (
11545:                        autoenroll => { 'run' => $env{'form.autoenroll_run'},
11546:                                        'sender_uname' => $sender_uname,
11547:                                        'sender_domain' => $sender_domain,
11548:                                        'co-owners' => $coowners,
11549:                                        'autofailsafe' => $autofailsafe,
11550:                                        'failsafe' => $failsafe,
11551:                                 }
11552:                      );
11553:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autoenrollhash,
11554:                                              $dom);
11555:     if ($putresult eq 'ok') {
11556:         if (exists($currautoenroll{'run'})) {
11557:              if ($currautoenroll{'run'} ne $env{'form.autoenroll_run'}) {
11558:                  $changes{'run'} = 1;
11559:              }
11560:         } elsif ($autorun) {
11561:             if ($env{'form.autoenroll_run'} ne '1') {
11562:                  $changes{'run'} = 1;
11563:             }
11564:         }
11565:         if ($currautoenroll{'sender_uname'} ne $sender_uname) {
11566:             $changes{'sender'} = 1;
11567:         }
11568:         if ($currautoenroll{'sender_domain'} ne $sender_domain) {
11569:             $changes{'sender'} = 1;
11570:         }
11571:         if ($currautoenroll{'co-owners'} ne '') {
11572:             if ($currautoenroll{'co-owners'} ne $coowners) {
11573:                 $changes{'coowners'} = 1;
11574:             }
11575:         } elsif ($coowners) {
11576:             $changes{'coowners'} = 1;
11577:         }
11578:         if ($currautoenroll{'autofailsafe'} ne $autofailsafe) {
11579:             $changes{'autofailsafe'} = 1;
11580:         }
11581:         if ($currautoenroll{'failsafe'} ne $failsafe) {
11582:             $changes{'failsafe'} = 1;
11583:         }
11584:         if (keys(%changes) > 0) {
11585:             $resulttext = &mt('Changes made:').'<ul>';
11586:             if ($changes{'run'}) {
11587:                 $resulttext .= '<li>'.&mt("$title{'run'} set to $offon[$env{'form.autoenroll_run'}]").'</li>';
11588:             }
11589:             if ($changes{'sender'}) {
11590:                 if ($sender_uname eq '' || $sender_domain eq '') {
11591:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to default (course owner).").'</li>';
11592:                 } else {
11593:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to [_1]",$sender_uname.':'.$sender_domain).'</li>';
11594:                 }
11595:             }
11596:             if ($changes{'coowners'}) {
11597:                 $resulttext .= '<li>'.&mt("$title{'coowners'} set to $offon[$env{'form.autoassign_coowners'}]").'</li>';
11598:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
11599:                 if (ref($lastactref) eq 'HASH') {
11600:                     $lastactref->{'domainconfig'} = 1;
11601:                 }
11602:             }
11603:             if ($changes{'autofailsafe'}) {
11604:                 if ($autofailsafe ne '') {
11605:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section set to: [_1]',$autofailsafe).'</li>';
11606:                 } else {
11607:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section not in use').'</li>';
11608:                 }
11609:             }
11610:             if ($changes{'failsafe'}) {
11611:                 if ($failsafe eq 'off') {
11612:                     unless ($changes{'autofailsafe'}) {
11613:                         $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section not in use').'</li>';
11614:                     }
11615:                 } elsif ($failsafe eq 'zero') {
11616:                     $resulttext .= '<li>'.&mt('Failsafe applies if retrieved section enrollment is zero').'</li>';
11617:                 } else {
11618:                     $resulttext .= '<li>'.&mt('Failsafe applies if retrieved section enrollment is zero or greater').'</li>';
11619:                 }
11620:             }
11621:             if (($changes{'autofailsafe'}) || ($changes{'failsafe'})) {
11622:                 &Apache::lonnet::get_domain_defaults($dom,1);
11623:                 if (ref($lastactref) eq 'HASH') {
11624:                     $lastactref->{'domdefaults'} = 1;
11625:                 }
11626:             }
11627:             $resulttext .= '</ul>';
11628:         } else {
11629:             $resulttext = &mt('No changes made to auto-enrollment settings');
11630:         }
11631:     } else {
11632:         $resulttext = '<span class="LC_error">'.
11633: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
11634:     }
11635:     return $resulttext;
11636: }
11637: 
11638: sub modify_autoupdate {
11639:     my ($dom,%domconfig) = @_;
11640:     my ($resulttext,%currautoupdate,%fields,%changes);
11641:     if (ref($domconfig{'autoupdate'}) eq 'HASH') {
11642:         foreach my $key (keys(%{$domconfig{'autoupdate'}})) {
11643:             $currautoupdate{$key} = $domconfig{'autoupdate'}{$key};
11644:         }
11645:     }
11646:     my @offon = ('off','on');
11647:     my %title = &Apache::lonlocal::texthash (
11648:                     run        => 'Auto-update:',
11649:                     classlists => 'Updates to user information in classlists?',
11650:                     unexpired  => 'Skip updates for users without active or future roles?',
11651:                     lastactive => 'Skip updates for inactive users?',
11652:                 );
11653:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
11654:     my %fieldtitles = &Apache::lonlocal::texthash (
11655:                         id => 'Student/Employee ID',
11656:                         permanentemail => 'E-mail address',
11657:                         lastname => 'Last Name',
11658:                         firstname => 'First Name',
11659:                         middlename => 'Middle Name',
11660:                         generation => 'Generation',
11661:                       );
11662:     $othertitle = &mt('All users');
11663:     if (keys(%{$usertypes}) >  0) {
11664:         $othertitle = &mt('Other users');
11665:     }
11666:     foreach my $key (keys(%env)) {
11667:         if ($key =~ /^form\.updateable_(.+)_([^_]+)$/) {
11668:             my ($usertype,$item) = ($1,$2);
11669:             if (grep(/^\Q$item\E$/,keys(%fieldtitles))) {
11670:                 if ($usertype eq 'default') {   
11671:                     push(@{$fields{$1}},$2);
11672:                 } elsif (ref($types) eq 'ARRAY') {
11673:                     if (grep(/^\Q$usertype\E$/,@{$types})) {
11674:                         push(@{$fields{$1}},$2);
11675:                     }
11676:                 }
11677:             }
11678:         }
11679:     }
11680:     my @lockablenames = &Apache::loncommon::get_env_multiple('form.lockablenames');
11681:     @lockablenames = sort(@lockablenames);
11682:     if (ref($currautoupdate{'lockablenames'}) eq 'ARRAY') {
11683:         my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
11684:         if (@changed) {
11685:             $changes{'lockablenames'} = 1;
11686:         }
11687:     } else {
11688:         if (@lockablenames) {
11689:             $changes{'lockablenames'} = 1;
11690:         }
11691:     }
11692:     my %updatehash = (
11693:                       autoupdate => { run => $env{'form.autoupdate_run'},
11694:                                       classlists => $env{'form.classlists'},
11695:                                       unexpired  => $env{'form.unexpired'},
11696:                                       fields => {%fields},
11697:                                       lockablenames => \@lockablenames,
11698:                                     }
11699:                      );
11700:     my $lastactivedays;
11701:     if ($env{'form.lastactive'}) {
11702:         $lastactivedays = $env{'form.lastactivedays'};
11703:         $lastactivedays =~ s/^\s+|\s+$//g;
11704:         unless ($lastactivedays =~ /^\d+$/) {
11705:             undef($lastactivedays);
11706:             $env{'form.lastactive'} = 0;
11707:         }
11708:     }
11709:     $updatehash{'autoupdate'}{'lastactive'} = $lastactivedays;
11710:     foreach my $key (keys(%currautoupdate)) {
11711:         if (($key eq 'run') || ($key eq 'classlists') || ($key eq 'unexpired') || ($key eq 'lastactive')) {
11712:             if (exists($updatehash{autoupdate}{$key})) {
11713:                 if ($currautoupdate{$key} ne $updatehash{autoupdate}{$key}) {
11714:                     $changes{$key} = 1;
11715:                 }
11716:             }
11717:         } elsif ($key eq 'fields') {
11718:             if (ref($currautoupdate{$key}) eq 'HASH') {
11719:                 foreach my $item (@{$types},'default') {
11720:                     if (ref($currautoupdate{$key}{$item}) eq 'ARRAY') {
11721:                         my $change = 0;
11722:                         foreach my $type (@{$currautoupdate{$key}{$item}}) {
11723:                             if (!exists($fields{$item})) {
11724:                                 $change = 1;
11725:                                 last;
11726:                             } elsif (ref($fields{$item}) eq 'ARRAY') {
11727:                                 if (!grep(/^\Q$type\E$/,@{$fields{$item}})) {
11728:                                     $change = 1;
11729:                                     last;
11730:                                 }
11731:                             }
11732:                         }
11733:                         if ($change) {
11734:                             push(@{$changes{$key}},$item);
11735:                         }
11736:                     } 
11737:                 }
11738:             }
11739:         } elsif ($key eq 'lockablenames') {
11740:             if (ref($currautoupdate{$key}) eq 'ARRAY') {
11741:                 my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
11742:                 if (@changed) {
11743:                     $changes{'lockablenames'} = 1;
11744:                 }
11745:             } else {
11746:                 if (@lockablenames) {
11747:                     $changes{'lockablenames'} = 1;
11748:                 }
11749:             }
11750:         }
11751:     }
11752:     unless (grep(/^\Qlockablenames\E$/,keys(%currautoupdate))) {
11753:         if (@lockablenames) {
11754:             $changes{'lockablenames'} = 1;
11755:         }
11756:     }
11757:     unless (grep(/^unexpired$/,keys(%currautoupdate))) {
11758:         if ($updatehash{'autoupdate'}{'unexpired'}) {
11759:             $changes{'unexpired'} = 1;
11760:         }
11761:     }
11762:     unless (grep(/^lastactive$/,keys(%currautoupdate))) {
11763:         if ($updatehash{'autoupdate'}{'lastactive'} ne '') {
11764:             $changes{'lastactive'} = 1;
11765:         }
11766:     }
11767:     foreach my $item (@{$types},'default') {
11768:         if (defined($fields{$item})) {
11769:             if (ref($currautoupdate{'fields'}) eq 'HASH') {
11770:                 if (ref($currautoupdate{'fields'}{$item}) eq 'ARRAY') {
11771:                     my $change = 0;
11772:                     if (ref($fields{$item}) eq 'ARRAY') {
11773:                         foreach my $type (@{$fields{$item}}) {
11774:                             if (!grep(/^\Q$type\E$/,@{$currautoupdate{'fields'}{$item}})) {
11775:                                 $change = 1;
11776:                                 last;
11777:                             }
11778:                         }
11779:                     }
11780:                     if ($change) {
11781:                         push(@{$changes{'fields'}},$item);
11782:                     }
11783:                 } else {
11784:                     push(@{$changes{'fields'}},$item);
11785:                 }
11786:             } else {
11787:                 push(@{$changes{'fields'}},$item);
11788:             }
11789:         }
11790:     }
11791:     my $putresult = &Apache::lonnet::put_dom('configuration',\%updatehash,
11792:                                              $dom);
11793:     if ($putresult eq 'ok') {
11794:         if (keys(%changes) > 0) {
11795:             $resulttext = &mt('Changes made:').'<ul>';
11796:             foreach my $key (sort(keys(%changes))) {
11797:                 if ($key eq 'lockablenames') {
11798:                     $resulttext .= '<li>';
11799:                     if (@lockablenames) {
11800:                         $usertypes->{'default'} = $othertitle;
11801:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update), available for the following affiliations:").' '.
11802:                                    join(', ', map { $usertypes->{$_}; } @lockablenames).'</li>';
11803:                     } else {
11804:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update) is unavailable.");
11805:                     }
11806:                     $resulttext .= '</li>';
11807:                 } elsif (ref($changes{$key}) eq 'ARRAY') {
11808:                     foreach my $item (@{$changes{$key}}) {
11809:                         my @newvalues;
11810:                         foreach my $type (@{$fields{$item}}) {
11811:                             push(@newvalues,$fieldtitles{$type});
11812:                         }
11813:                         my $newvaluestr;
11814:                         if (@newvalues > 0) {
11815:                             $newvaluestr = join(', ',@newvalues);
11816:                         } else {
11817:                             $newvaluestr = &mt('none');
11818:                         }
11819:                         if ($item eq 'default') {
11820:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$othertitle,$newvaluestr).'</li>';
11821:                         } else {
11822:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$usertypes->{$item},$newvaluestr).'</li>';
11823:                         }
11824:                     }
11825:                 } else {
11826:                     my $newvalue;
11827:                     if ($key eq 'run') {
11828:                         $newvalue = $offon[$env{'form.autoupdate_run'}];
11829:                     } elsif ($key eq 'lastactive') {
11830:                         $newvalue = $offon[$env{'form.lastactive'}];
11831:                         unless ($lastactivedays eq '') {
11832:                             $newvalue .= '; '.&mt('inactive = no activity in last [quant,_1,day]',$lastactivedays);
11833:                         }
11834:                     } else {
11835:                         $newvalue = $offon[$env{'form.'.$key}];
11836:                     }
11837:                     $resulttext .= '<li>'.&mt("[_1] set to $newvalue",$title{$key}).'</li>';
11838:                 }
11839:             }
11840:             $resulttext .= '</ul>';
11841:         } else {
11842:             $resulttext = &mt('No changes made to autoupdates');
11843:         }
11844:     } else {
11845:         $resulttext = '<span class="LC_error">'.
11846: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
11847:     }
11848:     return $resulttext;
11849: }
11850: 
11851: sub modify_autocreate {
11852:     my ($dom,%domconfig) = @_;
11853:     my ($resulttext,%changes,%currautocreate,%newvals,%autocreatehash);
11854:     if (ref($domconfig{'autocreate'}) eq 'HASH') {
11855:         foreach my $key (keys(%{$domconfig{'autocreate'}})) {
11856:             $currautocreate{$key} = $domconfig{'autocreate'}{$key};
11857:         }
11858:     }
11859:     my %title= ( xml => 'Auto-creation of courses in XML course description files',
11860:                  req => 'Auto-creation of validated requests for official courses',
11861:                  xmldc => 'Identity of course creator of courses from XML files',
11862:                );
11863:     my @types = ('xml','req');
11864:     foreach my $item (@types) {
11865:         $newvals{$item} = $env{'form.autocreate_'.$item};
11866:         $newvals{$item} =~ s/\D//g;
11867:         $newvals{$item} = 0 if ($newvals{$item} eq '');
11868:     }
11869:     $newvals{'xmldc'} = $env{'form.autocreate_xmldc'};
11870:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
11871:     unless (exists($domcoords{$newvals{'xmldc'}})) {
11872:         $newvals{'xmldc'} = '';
11873:     } 
11874:     %autocreatehash =  (
11875:                         autocreate => { xml => $newvals{'xml'},
11876:                                         req => $newvals{'req'},
11877:                                       }
11878:                        );
11879:     if ($newvals{'xmldc'} ne '') {
11880:         $autocreatehash{'autocreate'}{'xmldc'} = $newvals{'xmldc'};
11881:     }
11882:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autocreatehash,
11883:                                              $dom);
11884:     if ($putresult eq 'ok') {
11885:         my @items = @types;
11886:         if ($newvals{'xml'}) {
11887:             push(@items,'xmldc');
11888:         }
11889:         foreach my $item (@items) {
11890:             if (exists($currautocreate{$item})) {
11891:                 if ($currautocreate{$item} ne $newvals{$item}) {
11892:                     $changes{$item} = 1;
11893:                 }
11894:             } elsif ($newvals{$item}) {
11895:                 $changes{$item} = 1;
11896:             }
11897:         }
11898:         if (keys(%changes) > 0) {
11899:             my @offon = ('off','on'); 
11900:             $resulttext = &mt('Changes made:').'<ul>';
11901:             foreach my $item (@types) {
11902:                 if ($changes{$item}) {
11903:                     my $newtxt = $offon[$newvals{$item}];
11904:                     $resulttext .= '<li>'.
11905:                                    &mt("$title{$item} set to [_1]$newtxt [_2]",
11906:                                        '<b>','</b>').
11907:                                    '</li>';
11908:                 }
11909:             }
11910:             if ($changes{'xmldc'}) {
11911:                 my ($dcname,$dcdom) = split(':',$newvals{'xmldc'});
11912:                 my $newtxt = &Apache::loncommon::plainname($dcname,$dcdom);
11913:                 $resulttext .= '<li>'.&mt("$title{'xmldc'} set to [_1]",'<b>'.$newtxt.'</b>').'</li>'; 
11914:             }
11915:             $resulttext .= '</ul>';
11916:         } else {
11917:             $resulttext = &mt('No changes made to auto-creation settings');
11918:         }
11919:     } else {
11920:         $resulttext = '<span class="LC_error">'.
11921:             &mt('An error occurred: [_1]',$putresult).'</span>';
11922:     }
11923:     return $resulttext;
11924: }
11925: 
11926: sub modify_directorysrch {
11927:     my ($dom,$lastactref,%domconfig) = @_;
11928:     my ($resulttext,%changes);
11929:     my %currdirsrch;
11930:     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
11931:         foreach my $key (keys(%{$domconfig{'directorysrch'}})) {
11932:             $currdirsrch{$key} = $domconfig{'directorysrch'}{$key};
11933:         }
11934:     }
11935:     my %title = ( available => 'Institutional directory search available',
11936:                   localonly => 'Other domains can search institution',
11937:                   lcavailable => 'LON-CAPA directory search available',
11938:                   lclocalonly => 'Other domains can search LON-CAPA domain',
11939:                   searchby => 'Search types',
11940:                   searchtypes => 'Search latitude');
11941:     my @offon = ('off','on');
11942:     my @otherdoms = ('Yes','No');
11943: 
11944:     my @searchtypes = &Apache::loncommon::get_env_multiple('form.searchtypes');  
11945:     my @cansearch = &Apache::loncommon::get_env_multiple('form.cansearch');
11946:     my @searchby = &Apache::loncommon::get_env_multiple('form.searchby');
11947: 
11948:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
11949:     if (keys(%{$usertypes}) == 0) {
11950:         @cansearch = ('default');
11951:     } else {
11952:         if (ref($currdirsrch{'cansearch'}) eq 'ARRAY') {
11953:             foreach my $type (@{$currdirsrch{'cansearch'}}) {
11954:                 if (!grep(/^\Q$type\E$/,@cansearch)) {
11955:                     push(@{$changes{'cansearch'}},$type);
11956:                 }
11957:             }
11958:             foreach my $type (@cansearch) {
11959:                 if (!grep(/^\Q$type\E$/,@{$currdirsrch{'cansearch'}})) {
11960:                     push(@{$changes{'cansearch'}},$type);
11961:                 }
11962:             }
11963:         } else {
11964:             push(@{$changes{'cansearch'}},@cansearch);
11965:         }
11966:     }
11967: 
11968:     if (ref($currdirsrch{'searchby'}) eq 'ARRAY') {
11969:         foreach my $by (@{$currdirsrch{'searchby'}}) {
11970:             if (!grep(/^\Q$by\E$/,@searchby)) {
11971:                 push(@{$changes{'searchby'}},$by);
11972:             }
11973:         }
11974:         foreach my $by (@searchby) {
11975:             if (!grep(/^\Q$by\E$/,@{$currdirsrch{'searchby'}})) {
11976:                 push(@{$changes{'searchby'}},$by);
11977:             }
11978:         }
11979:     } else {
11980:         push(@{$changes{'searchby'}},@searchby);
11981:     }
11982: 
11983:     if (ref($currdirsrch{'searchtypes'}) eq 'ARRAY') {
11984:         foreach my $type (@{$currdirsrch{'searchtypes'}}) {
11985:             if (!grep(/^\Q$type\E$/,@searchtypes)) {
11986:                 push(@{$changes{'searchtypes'}},$type);
11987:             }
11988:         }
11989:         foreach my $type (@searchtypes) {
11990:             if (!grep(/^\Q$type\E$/,@{$currdirsrch{'searchtypes'}})) {
11991:                 push(@{$changes{'searchtypes'}},$type);
11992:             }
11993:         }
11994:     } else {
11995:         if (exists($currdirsrch{'searchtypes'})) {
11996:             foreach my $type (@searchtypes) {  
11997:                 if ($type ne $currdirsrch{'searchtypes'}) { 
11998:                     push(@{$changes{'searchtypes'}},$type);
11999:                 }
12000:             }
12001:             if (!grep(/^\Q$currdirsrch{'searchtypes'}\E/,@searchtypes)) {
12002:                 push(@{$changes{'searchtypes'}},$currdirsrch{'searchtypes'});
12003:             }   
12004:         } else {
12005:             push(@{$changes{'searchtypes'}},@searchtypes); 
12006:         }
12007:     }
12008: 
12009:     my %dirsrch_hash =  (
12010:             directorysrch => { available => $env{'form.dirsrch_available'},
12011:                                cansearch => \@cansearch,
12012:                                localonly => $env{'form.dirsrch_instlocalonly'},
12013:                                lclocalonly => $env{'form.dirsrch_domlocalonly'},
12014:                                lcavailable => $env{'form.dirsrch_domavailable'},
12015:                                searchby => \@searchby,
12016:                                searchtypes => \@searchtypes,
12017:                              }
12018:             );
12019:     my $putresult = &Apache::lonnet::put_dom('configuration',\%dirsrch_hash,
12020:                                              $dom);
12021:     if ($putresult eq 'ok') {
12022:         if (exists($currdirsrch{'available'})) {
12023:              if ($currdirsrch{'available'} ne $env{'form.dirsrch_available'}) {
12024:                  $changes{'available'} = 1;
12025:              }
12026:         } else {
12027:             if ($env{'form.dirsrch_available'} eq '1') {
12028:                 $changes{'available'} = 1;
12029:             }
12030:         }
12031:         if (exists($currdirsrch{'lcavailable'})) {
12032:             if ($currdirsrch{'lcavailable'} ne $env{'form.dirsrch_domavailable'}) {
12033:                 $changes{'lcavailable'} = 1;
12034:             }
12035:         } else {
12036:             if ($env{'form.dirsrch_lcavailable'} eq '1') {
12037:                 $changes{'lcavailable'} = 1;
12038:             }
12039:         }
12040:         if (exists($currdirsrch{'localonly'})) {
12041:             if ($currdirsrch{'localonly'} ne $env{'form.dirsrch_instlocalonly'}) {
12042:                 $changes{'localonly'} = 1;
12043:             }
12044:         } else {
12045:             if ($env{'form.dirsrch_instlocalonly'} eq '1') {
12046:                 $changes{'localonly'} = 1;
12047:             }
12048:         }
12049:         if (exists($currdirsrch{'lclocalonly'})) {
12050:             if ($currdirsrch{'lclocalonly'} ne $env{'form.dirsrch_domlocalonly'}) {
12051:                 $changes{'lclocalonly'} = 1;
12052:             }
12053:         } else {
12054:             if ($env{'form.dirsrch_domlocalonly'} eq '1') {
12055:                 $changes{'lclocalonly'} = 1;
12056:             }
12057:         }
12058:         if (keys(%changes) > 0) {
12059:             $resulttext = &mt('Changes made:').'<ul>';
12060:             if ($changes{'available'}) {
12061:                 $resulttext .= '<li>'.&mt("$title{'available'} set to: $offon[$env{'form.dirsrch_available'}]").'</li>';
12062:             }
12063:             if ($changes{'lcavailable'}) {
12064:                 $resulttext .= '<li>'.&mt("$title{'lcavailable'} set to: $offon[$env{'form.dirsrch_domavailable'}]").'</li>';
12065:             }
12066:             if ($changes{'localonly'}) {
12067:                 $resulttext .= '<li>'.&mt("$title{'localonly'} set to: $otherdoms[$env{'form.dirsrch_instlocalonly'}]").'</li>';
12068:             }
12069:             if ($changes{'lclocalonly'}) {
12070:                 $resulttext .= '<li>'.&mt("$title{'lclocalonly'} set to: $otherdoms[$env{'form.dirsrch_domlocalonly'}]").'</li>';
12071:             }
12072:             if (ref($changes{'cansearch'}) eq 'ARRAY') {
12073:                 my $chgtext;
12074:                 if (ref($usertypes) eq 'HASH') {
12075:                     if (keys(%{$usertypes}) > 0) {
12076:                         foreach my $type (@{$types}) {
12077:                             if (grep(/^\Q$type\E$/,@cansearch)) {
12078:                                 $chgtext .= $usertypes->{$type}.'; ';
12079:                             }
12080:                         }
12081:                         if (grep(/^default$/,@cansearch)) {
12082:                             $chgtext .= $othertitle;
12083:                         } else {
12084:                             $chgtext =~ s/\; $//;
12085:                         }
12086:                         $resulttext .=
12087:                             '<li>'.
12088:                             &mt("Users from domain '[_1]' permitted to search the institutional directory set to: [_2]",
12089:                                 '<span class="LC_cusr_emph">'.$dom.'</span>',$chgtext).
12090:                             '</li>';
12091:                     }
12092:                 }
12093:             }
12094:             if (ref($changes{'searchby'}) eq 'ARRAY') {
12095:                 my ($searchtitles,$titleorder) = &sorted_searchtitles();
12096:                 my $chgtext;
12097:                 foreach my $type (@{$titleorder}) {
12098:                     if (grep(/^\Q$type\E$/,@searchby)) {
12099:                         if (defined($searchtitles->{$type})) {
12100:                             $chgtext .= $searchtitles->{$type}.'; ';
12101:                         }
12102:                     }
12103:                 }
12104:                 $chgtext =~ s/\; $//;
12105:                 $resulttext .= '<li>'.&mt("$title{'searchby'} set to: [_1]",$chgtext).'</li>';
12106:             }
12107:             if (ref($changes{'searchtypes'}) eq 'ARRAY') {
12108:                 my ($srchtypes_desc,$srchtypeorder) = &sorted_searchtypes(); 
12109:                 my $chgtext;
12110:                 foreach my $type (@{$srchtypeorder}) {
12111:                     if (grep(/^\Q$type\E$/,@searchtypes)) {
12112:                         if (defined($srchtypes_desc->{$type})) {
12113:                             $chgtext .= $srchtypes_desc->{$type}.'; ';
12114:                         }
12115:                     }
12116:                 }
12117:                 $chgtext =~ s/\; $//;
12118:                 $resulttext .= '<li>'.&mt($title{'searchtypes'}.' set to: "[_1]"',$chgtext).'</li>';
12119:             }
12120:             $resulttext .= '</ul>';
12121:             &Apache::lonnet::do_cache_new('directorysrch',$dom,$dirsrch_hash{'directorysrch'},3600);
12122:             if (ref($lastactref) eq 'HASH') {
12123:                 $lastactref->{'directorysrch'} = 1;
12124:             }
12125:         } else {
12126:             $resulttext = &mt('No changes made to directory search settings');
12127:         }
12128:     } else {
12129:         $resulttext = '<span class="LC_error">'.
12130:                       &mt('An error occurred: [_1]',$putresult).'</span>';
12131:     }
12132:     return $resulttext;
12133: }
12134: 
12135: sub modify_contacts {
12136:     my ($dom,$lastactref,%domconfig) = @_;
12137:     my ($resulttext,%currsetting,%newsetting,%changes,%contacts_hash);
12138:     if (ref($domconfig{'contacts'}) eq 'HASH') {
12139:         foreach my $key (keys(%{$domconfig{'contacts'}})) {
12140:             $currsetting{$key} = $domconfig{'contacts'}{$key};
12141:         }
12142:     }
12143:     my (%others,%to,%bcc,%includestr,%includeloc);
12144:     my @contacts = ('supportemail','adminemail');
12145:     my @mailings = ('errormail','packagesmail','helpdeskmail','otherdomsmail',
12146:                     'lonstatusmail','requestsmail','updatesmail','idconflictsmail','hostipmail');
12147:     my @toggles = ('reporterrors','reportupdates','reportstatus');
12148:     my @lonstatus = ('threshold','sysmail','weights','excluded');
12149:     my ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
12150:     foreach my $type (@mailings) {
12151:         @{$newsetting{$type}} = 
12152:             &Apache::loncommon::get_env_multiple('form.'.$type);
12153:         foreach my $item (@contacts) {
12154:             if (grep(/^\Q$item\E$/,@{$newsetting{$type}})) {
12155:                 $contacts_hash{contacts}{$type}{$item} = 1;
12156:             } else {
12157:                 $contacts_hash{contacts}{$type}{$item} = 0;
12158:             }
12159:         }
12160:         $others{$type} = $env{'form.'.$type.'_others'};
12161:         $contacts_hash{contacts}{$type}{'others'} = $others{$type};
12162:         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
12163:             $bcc{$type} = $env{'form.'.$type.'_bcc'};
12164:             $contacts_hash{contacts}{$type}{'bcc'} = $bcc{$type};
12165:             if (($env{'form.'.$type.'_includestr'} ne '') && ($env{'form.'.$type.'_includeloc'} =~ /^s|b$/)) {
12166:                 $includestr{$type} = $env{'form.'.$type.'_includestr'};
12167:                 $includeloc{$type} = $env{'form.'.$type.'_includeloc'};
12168:                 $contacts_hash{contacts}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
12169:             }
12170:         }
12171:     }
12172:     foreach my $item (@contacts) {
12173:         $to{$item} = $env{'form.'.$item};
12174:         $contacts_hash{'contacts'}{$item} = $to{$item};
12175:     }
12176:     foreach my $item (@toggles) {
12177:         if ($env{'form.'.$item} =~ /^(0|1)$/) {
12178:             $contacts_hash{'contacts'}{$item} = $env{'form.'.$item};
12179:         }
12180:     }
12181:     my ($lonstatus_defs,$lonstatus_names) = &Apache::loncommon::lon_status_items();
12182:     foreach my $item (@lonstatus) {
12183:         if ($item eq 'excluded') {
12184:             my (%serverhomes,@excluded);
12185:             map { $serverhomes{$_} = 1; } values(%Apache::lonnet::serverhomeIDs);
12186:             my @possexcluded = &Apache::loncommon::get_env_multiple('form.errorexcluded');
12187:             if (@possexcluded) {
12188:                 foreach my $id (sort(@possexcluded)) {
12189:                     if ($serverhomes{$id}) {
12190:                         push(@excluded,$id);
12191:                     }
12192:                 }
12193:             }
12194:             if (@excluded) {
12195:                 $contacts_hash{'contacts'}{'lonstatus'}{$item} = \@excluded;
12196:             }
12197:         } elsif ($item eq 'weights') {
12198:             foreach my $type ('E','W','N','U') {
12199:                 $env{'form.error'.$item.'_'.$type} =~ s/^\s+|\s+$//g;
12200:                 if ($env{'form.error'.$item.'_'.$type} =~ /^\d+$/) {
12201:                     unless ($env{'form.error'.$item.'_'.$type} == $lonstatus_defs->{$type}) {
12202:                         $contacts_hash{'contacts'}{'lonstatus'}{$item}{$type} =
12203:                             $env{'form.error'.$item.'_'.$type};
12204:                     }
12205:                 }
12206:             }
12207:         } elsif (($item eq 'threshold') || ($item eq 'sysmail')) {
12208:             $env{'form.error'.$item} =~ s/^\s+|\s+$//g;
12209:             if ($env{'form.error'.$item} =~ /^\d+$/) {
12210:                 unless ($env{'form.error'.$item} == $lonstatus_defs->{$item}) {
12211:                     $contacts_hash{'contacts'}{'lonstatus'}{$item} = $env{'form.error'.$item};
12212:                 }
12213:             }
12214:         }
12215:     }
12216:     if ((ref($fields) eq 'ARRAY') && (ref($possoptions) eq 'HASH')) {
12217:         foreach my $field (@{$fields}) {
12218:             if (ref($possoptions->{$field}) eq 'ARRAY') {
12219:                 my $value = $env{'form.helpform_'.$field};
12220:                 $value =~ s/^\s+|\s+$//g;
12221:                 if (grep(/^\Q$value\E$/,@{$possoptions->{$field}})) {
12222:                     $contacts_hash{'contacts'}{'helpform'}{$field} = $value;
12223:                     if ($field eq 'screenshot') {
12224:                         $env{'form.helpform_maxsize'} =~ s/^\s+|\s+$//g;
12225:                         if ($env{'form.helpform_maxsize'} =~ /^\d+\.?\d*$/) {
12226:                             $contacts_hash{'contacts'}{'helpform'}{'maxsize'} = $env{'form.helpform_maxsize'};
12227:                         }
12228:                     }
12229:                 }
12230:             }
12231:         }
12232:     }
12233:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
12234:     my (@statuses,%usertypeshash,@overrides);
12235:     if ((ref($types) eq 'ARRAY') && (@{$types} > 0)) {
12236:         @statuses = @{$types};
12237:         if (ref($usertypes) eq 'HASH') {
12238:             %usertypeshash = %{$usertypes};
12239:         }
12240:     }
12241:     if (@statuses) {
12242:         my @possoverrides = &Apache::loncommon::get_env_multiple('form.overrides');
12243:         foreach my $type (@possoverrides) {
12244:             if (($type ne '') && (grep(/^\Q$type\E$/,@statuses))) {
12245:                 push(@overrides,$type);
12246:             }
12247:         }
12248:         if (@overrides) {
12249:             foreach my $type (@overrides) {
12250:                 my @standard = &Apache::loncommon::get_env_multiple('form.override_'.$type);
12251:                 foreach my $item (@contacts) {
12252:                     if (grep(/^\Q$item\E$/,@standard)) {
12253:                         $contacts_hash{'contacts'}{'overrides'}{$type}{$item} = 1;
12254:                         $newsetting{'override_'.$type}{$item} = 1;
12255:                     } else {
12256:                         $contacts_hash{'contacts'}{'overrides'}{$type}{$item} = 0;
12257:                         $newsetting{'override_'.$type}{$item} = 0;
12258:                     }
12259:                 }
12260:                 $contacts_hash{'contacts'}{'overrides'}{$type}{'others'} = $env{'form.override_'.$type.'_others'};
12261:                 $contacts_hash{'contacts'}{'overrides'}{$type}{'bcc'} = $env{'form.override_'.$type.'_bcc'};
12262:                 $newsetting{'override_'.$type}{'others'} = $env{'form.override_'.$type.'_others'};
12263:                 $newsetting{'override_'.$type}{'bcc'} = $env{'form.override_'.$type.'_bcc'};
12264:                 if (($env{'form.override_'.$type.'_includestr'} ne '') && ($env{'form.override_'.$type.'_includeloc'} =~ /^s|b$/)) {
12265:                     $includestr{$type} = $env{'form.override_'.$type.'_includestr'};
12266:                     $includeloc{$type} = $env{'form.override_'.$type.'_includeloc'};
12267:                     $contacts_hash{'contacts'}{'overrides'}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
12268:                     $newsetting{'override_'.$type}{'include'} = $contacts_hash{'contacts'}{'overrides'}{$type}{'include'};
12269:                 }
12270:             }    
12271:         }
12272:     }
12273:     if (keys(%currsetting) > 0) {
12274:         foreach my $item (@contacts) {
12275:             if ($to{$item} ne $currsetting{$item}) {
12276:                 $changes{$item} = 1;
12277:             }
12278:         }
12279:         foreach my $type (@mailings) {
12280:             foreach my $item (@contacts) {
12281:                 if (ref($currsetting{$type}) eq 'HASH') {
12282:                     if ($currsetting{$type}{$item} ne $contacts_hash{contacts}{$type}{$item}) {
12283:                         push(@{$changes{$type}},$item);
12284:                     }
12285:                 } else {
12286:                     push(@{$changes{$type}},@{$newsetting{$type}});
12287:                 }
12288:             }
12289:             if ($others{$type} ne $currsetting{$type}{'others'}) {
12290:                 push(@{$changes{$type}},'others');
12291:             }
12292:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
12293:                 if ($bcc{$type} ne $currsetting{$type}{'bcc'}) {
12294:                     push(@{$changes{$type}},'bcc'); 
12295:                 }
12296:                 my ($currloc,$currstr) = split(/:/,$currsetting{$type}{'include'},2);
12297:                 if (($includeloc{$type} ne $currloc) || (&escape($includestr{$type}) ne $currstr)) {
12298:                     push(@{$changes{$type}},'include');
12299:                 }
12300:             }
12301:         }
12302:         if (ref($fields) eq 'ARRAY') {
12303:             if (ref($currsetting{'helpform'}) eq 'HASH') {
12304:                 foreach my $field (@{$fields}) {
12305:                     if ($currsetting{'helpform'}{$field} ne $contacts_hash{'contacts'}{'helpform'}{$field}) {
12306:                         push(@{$changes{'helpform'}},$field);
12307:                     }
12308:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
12309:                         if ($currsetting{'helpform'}{'maxsize'} ne $contacts_hash{'contacts'}{'helpform'}{'maxsize'}) {
12310:                             push(@{$changes{'helpform'}},'maxsize');
12311:                         }
12312:                     }
12313:                 }
12314:             } else {
12315:                 foreach my $field (@{$fields}) {
12316:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
12317:                         push(@{$changes{'helpform'}},$field);
12318:                     }
12319:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
12320:                         if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
12321:                             push(@{$changes{'helpform'}},'maxsize');
12322:                         }
12323:                     }
12324:                 }
12325:             }
12326:         }
12327:         if (@statuses) {
12328:             if (ref($currsetting{'overrides'}) eq 'HASH') {
12329:                 foreach my $key (keys(%{$currsetting{'overrides'}})) {
12330:                     if (ref($currsetting{'overrides'}{$key}) eq 'HASH') {
12331:                         if (ref($newsetting{'override_'.$key}) eq 'HASH') {
12332:                             foreach my $item (@contacts,'bcc','others','include') {
12333:                                 if ($currsetting{'overrides'}{$key}{$item} ne $newsetting{'override_'.$key}{$item}) {
12334:                                     push(@{$changes{'overrides'}},$key);
12335:                                     last;
12336:                                 }
12337:                             }
12338:                         } else {
12339:                             push(@{$changes{'overrides'}},$key);
12340:                         }
12341:                     }
12342:                 }
12343:                 foreach my $key (@overrides) {
12344:                     unless (exists($currsetting{'overrides'}{$key})) {
12345:                         push(@{$changes{'overrides'}},$key);
12346:                     }
12347:                 }
12348:             } else {
12349:                 foreach my $key (@overrides) {
12350:                     push(@{$changes{'overrides'}},$key);
12351:                 }
12352:             }
12353:         }
12354:         if (ref($currsetting{'lonstatus'}) eq 'HASH') {
12355:             foreach my $key ('excluded','weights','threshold','sysmail') {
12356:                 if ($key eq 'excluded') {
12357:                     if ((ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') &&
12358:                         (ref($contacts_hash{contacts}{lonstatus}{excluded}) eq 'ARRAY')) {
12359:                         if ((ref($currsetting{'lonstatus'}{$key}) eq 'ARRAY') &&
12360:                             (@{$currsetting{'lonstatus'}{$key}})) {
12361:                             my @diffs =
12362:                                 &Apache::loncommon::compare_arrays($contacts_hash{contacts}{lonstatus}{excluded},
12363:                                                                    $currsetting{'lonstatus'}{$key});
12364:                             if (@diffs) {
12365:                                 push(@{$changes{'lonstatus'}},$key);
12366:                             }
12367:                         } elsif (@{$contacts_hash{contacts}{lonstatus}{excluded}}) {
12368:                             push(@{$changes{'lonstatus'}},$key);
12369:                         }
12370:                     } elsif ((ref($currsetting{'lonstatus'}{$key}) eq 'ARRAY') &&
12371:                              (@{$currsetting{'lonstatus'}{$key}})) {
12372:                         push(@{$changes{'lonstatus'}},$key);
12373:                     }
12374:                 } elsif ($key eq 'weights') {
12375:                     if ((ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') &&
12376:                         (ref($contacts_hash{contacts}{lonstatus}{$key}) eq 'HASH')) {
12377:                         if (ref($currsetting{'lonstatus'}{$key}) eq 'HASH') {
12378:                             foreach my $type ('E','W','N','U') {
12379:                                 unless ($contacts_hash{contacts}{lonstatus}{$key}{$type} eq
12380:                                         $currsetting{'lonstatus'}{$key}{$type}) {
12381:                                     push(@{$changes{'lonstatus'}},$key);
12382:                                     last;
12383:                                 }
12384:                             }
12385:                         } else {
12386:                             foreach my $type ('E','W','N','U') {
12387:                                 if ($contacts_hash{contacts}{lonstatus}{$key}{$type} ne '') {
12388:                                     push(@{$changes{'lonstatus'}},$key);
12389:                                     last;
12390:                                 }
12391:                             }
12392:                         }
12393:                     } elsif (ref($currsetting{'lonstatus'}{$key}) eq 'HASH') {
12394:                         foreach my $type ('E','W','N','U') {
12395:                             if ($currsetting{'lonstatus'}{$key}{$type} ne '') {
12396:                                 push(@{$changes{'lonstatus'}},$key);
12397:                                 last;
12398:                             }
12399:                         }
12400:                     }
12401:                 } elsif (($key eq 'threshold') || ($key eq 'sysmail')) {
12402:                     if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
12403:                         if ($currsetting{'lonstatus'}{$key} =~ /^\d+$/) {
12404:                             if ($currsetting{'lonstatus'}{$key} != $contacts_hash{contacts}{lonstatus}{$key}) {
12405:                                 push(@{$changes{'lonstatus'}},$key);
12406:                             }
12407:                         } elsif ($contacts_hash{contacts}{lonstatus}{$key} =~ /^\d+$/) {
12408:                             push(@{$changes{'lonstatus'}},$key);
12409:                         }
12410:                     } elsif ($currsetting{'lonstatus'}{$key} =~ /^\d+$/) {
12411:                         push(@{$changes{'lonstatus'}},$key);
12412:                     }
12413:                 }
12414:             }
12415:         } else {
12416:             if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
12417:                 foreach my $key ('excluded','weights','threshold','sysmail') {
12418:                     if (exists($contacts_hash{contacts}{lonstatus}{$key})) {
12419:                         push(@{$changes{'lonstatus'}},$key);
12420:                     }
12421:                 }
12422:             }
12423:         }
12424:     } else {
12425:         my %default;
12426:         $default{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
12427:         $default{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
12428:         $default{'errormail'} = 'adminemail';
12429:         $default{'packagesmail'} = 'adminemail';
12430:         $default{'helpdeskmail'} = 'supportemail';
12431:         $default{'otherdomsmail'} = 'supportemail';
12432:         $default{'lonstatusmail'} = 'adminemail';
12433:         $default{'requestsmail'} = 'adminemail';
12434:         $default{'updatesmail'} = 'adminemail';
12435:         $default{'hostipmail'} = 'adminemail';
12436:         foreach my $item (@contacts) {
12437:            if ($to{$item} ne $default{$item}) {
12438:                $changes{$item} = 1;
12439:            }
12440:         }
12441:         foreach my $type (@mailings) {
12442:             if ((@{$newsetting{$type}} != 1) || ($newsetting{$type}[0] ne $default{$type})) {
12443:                 push(@{$changes{$type}},@{$newsetting{$type}});
12444:             }
12445:             if ($others{$type} ne '') {
12446:                 push(@{$changes{$type}},'others');
12447:             }
12448:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
12449:                 if ($bcc{$type} ne '') {
12450:                     push(@{$changes{$type}},'bcc');
12451:                 }
12452:                 if (($includeloc{$type} =~ /^b|s$/) && ($includestr{$type} ne '')) {
12453:                     push(@{$changes{$type}},'include');
12454:                 }
12455:             }
12456:         }
12457:         if (ref($fields) eq 'ARRAY') {
12458:             foreach my $field (@{$fields}) {
12459:                 if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
12460:                     push(@{$changes{'helpform'}},$field);
12461:                 }
12462:                 if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
12463:                     if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
12464:                         push(@{$changes{'helpform'}},'maxsize');
12465:                     }
12466:                 }
12467:             }
12468:         }
12469:         if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
12470:             foreach my $key ('excluded','weights','threshold','sysmail') {
12471:                 if (exists($contacts_hash{contacts}{lonstatus}{$key})) {
12472:                     push(@{$changes{'lonstatus'}},$key);
12473:                 }
12474:             }
12475:         }
12476:     }
12477:     foreach my $item (@toggles) {
12478:         if (($env{'form.'.$item} == 1) && ($currsetting{$item} == 0)) {
12479:             $changes{$item} = 1;
12480:         } elsif ((!$env{'form.'.$item}) &&
12481:                  (($currsetting{$item} eq '') || ($currsetting{$item} == 1))) {
12482:             $changes{$item} = 1;
12483:         }
12484:     }
12485:     my $putresult = &Apache::lonnet::put_dom('configuration',\%contacts_hash,
12486:                                              $dom);
12487:     if ($putresult eq 'ok') {
12488:         if (keys(%changes) > 0) {
12489:             &Apache::loncommon::devalidate_domconfig_cache($dom);
12490:             if (ref($lastactref) eq 'HASH') {
12491:                 $lastactref->{'domainconfig'} = 1;
12492:             }
12493:             my ($titles,$short_titles)  = &contact_titles();
12494:             $resulttext = &mt('Changes made:').'<ul>';
12495:             foreach my $item (@contacts) {
12496:                 if ($changes{$item}) {
12497:                     $resulttext .= '<li>'.$titles->{$item}.
12498:                                     &mt(' set to: ').
12499:                                     '<span class="LC_cusr_emph">'.
12500:                                     $to{$item}.'</span></li>';
12501:                 }
12502:             }
12503:             foreach my $type (@mailings) {
12504:                 if (ref($changes{$type}) eq 'ARRAY') {
12505:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
12506:                         $resulttext .= '<li>'.$titles->{$type}.' -- '.&mt('sent to').': ';
12507:                     } else {
12508:                         $resulttext .= '<li>'.$titles->{$type}.': ';
12509:                     }
12510:                     my @text;
12511:                     foreach my $item (@{$newsetting{$type}}) {
12512:                         push(@text,$short_titles->{$item});
12513:                     }
12514:                     if ($others{$type} ne '') {
12515:                         push(@text,$others{$type});
12516:                     }
12517:                     if (@text) {
12518:                         $resulttext .= '<span class="LC_cusr_emph">'.
12519:                                        join(', ',@text).'</span>';
12520:                     }
12521:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
12522:                         if ($bcc{$type} ne '') {
12523:                             my $bcctext;
12524:                             if (@text) {
12525:                                 $bcctext = '&nbsp;'.&mt('with Bcc to');
12526:                             } else {
12527:                                 $bcctext = '(Bcc)';
12528:                             }
12529:                             $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$bcc{$type}.'</span>';
12530:                         } elsif (!@text) {
12531:                             $resulttext .= &mt('No one');
12532:                         }
12533:                         if ($includestr{$type} ne '') {
12534:                             if ($includeloc{$type} eq 'b') {
12535:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail body:').' '.$includestr{$type};
12536:                             } elsif ($includeloc{$type} eq 's') {
12537:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail subject:').' '.$includestr{$type};
12538:                             }
12539:                         }
12540:                     } elsif (!@text) {
12541:                         $resulttext .= &mt('No recipients');
12542:                     }
12543:                     $resulttext .= '</li>';
12544:                 }
12545:             }
12546:             if (ref($changes{'overrides'}) eq 'ARRAY') {
12547:                 my @deletions;
12548:                 foreach my $type (@{$changes{'overrides'}}) {
12549:                     if ($usertypeshash{$type}) {
12550:                         if (grep(/^\Q$type\E/,@overrides)) {
12551:                             $resulttext .= '<li>'.&mt("Overrides based on requester's affiliation set for [_1]",
12552:                                                       $usertypeshash{$type}).'<ul><li>';
12553:                             if (ref($newsetting{'override_'.$type}) eq 'HASH') {
12554:                                 my @text;
12555:                                 foreach my $item (@contacts) {
12556:                                     if ($newsetting{'override_'.$type}{$item}) {
12557:                                         push(@text,$short_titles->{$item});
12558:                                     }
12559:                                 }
12560:                                 if ($newsetting{'override_'.$type}{'others'} ne '') {
12561:                                     push(@text,$newsetting{'override_'.$type}{'others'});
12562:                                 }
12563: 
12564:                                 if (@text) {
12565:                                     $resulttext .= &mt('Helpdesk e-mail sent to: [_1]',
12566:                                                        '<span class="LC_cusr_emph">'.join(', ',@text).'</span>');
12567:                                 }
12568:                                 if ($newsetting{'override_'.$type}{'bcc'} ne '') {
12569:                                     my $bcctext;
12570:                                     if (@text) {
12571:                                         $bcctext = '&nbsp;'.&mt('with Bcc to');
12572:                                     } else {
12573:                                         $bcctext = '(Bcc)';
12574:                                     }
12575:                                     $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$newsetting{'override_'.$type}{'bcc'}.'</span>';
12576:                                 } elsif (!@text) {
12577:                                      $resulttext .= &mt('Helpdesk e-mail sent to no one');
12578:                                 }
12579:                                 $resulttext .= '</li>';
12580:                                 if ($newsetting{'override_'.$type}{'include'} ne '') {
12581:                                     my ($loc,$str) = split(/:/,$newsetting{'override_'.$type}{'include'});
12582:                                     if ($loc eq 'b') {
12583:                                         $resulttext .= '<li>'.&mt('Text automatically added to e-mail body:').' '.&unescape($str).'</li>';
12584:                                     } elsif ($loc eq 's') {
12585:                                         $resulttext .= '<li>'.&mt('Text automatically added to e-mail subject:').' '.&unescape($str).'</li>';
12586:                                     }
12587:                                 }
12588:                             }
12589:                             $resulttext .= '</li></ul></li>';
12590:                         } else {
12591:                             push(@deletions,$usertypeshash{$type});
12592:                         }
12593:                     }
12594:                 }
12595:                 if (@deletions) {
12596:                     $resulttext .= '<li>'.&mt("Overrides based on requester's affiliation discontinued for: [_1]",
12597:                                               join(', ',@deletions)).'</li>';
12598:                 }
12599:             }
12600:             my @offon = ('off','on');
12601:             my $corelink = &core_link_msu();
12602:             if ($changes{'reporterrors'}) {
12603:                 $resulttext .= '<li>'.
12604:                                &mt('E-mail error reports to [_1] set to "'.
12605:                                    $offon[$env{'form.reporterrors'}].'".',
12606:                                    $corelink).
12607:                                '</li>';
12608:             }
12609:             if ($changes{'reportupdates'}) {
12610:                 $resulttext .= '<li>'.
12611:                                 &mt('E-mail record of completed LON-CAPA updates to [_1] set to "'.
12612:                                     $offon[$env{'form.reportupdates'}].'".',
12613:                                     $corelink).
12614:                                 '</li>';
12615:             }
12616:             if ($changes{'reportstatus'}) {
12617:                 $resulttext .= '<li>'.
12618:                                 &mt('E-mail status if errors above threshold to [_1] set to "'.
12619:                                     $offon[$env{'form.reportstatus'}].'".',
12620:                                     $corelink).
12621:                                 '</li>';
12622:             }
12623:             if (ref($changes{'lonstatus'}) eq 'ARRAY') {
12624:                 $resulttext .= '<li>'.
12625:                                &mt('Nightly status check e-mail settings').':<ul>';
12626:                 my (%defval,%use_def,%shown);
12627:                 $defval{'threshold'} = $lonstatus_defs->{'threshold'};
12628:                 $defval{'sysmail'} = $lonstatus_defs->{'sysmail'};
12629:                 $defval{'weights'} =
12630:                     join(', ',map { $lonstatus_names->{$_}.'='.$lonstatus_defs->{$_}; } ('E','W','N','U'));
12631:                 $defval{'excluded'} = &mt('None');
12632:                 if (ref($contacts_hash{'contacts'}{'lonstatus'}) eq 'HASH') {
12633:                     foreach my $item ('threshold','sysmail','weights','excluded') {
12634:                         if (exists($contacts_hash{'contacts'}{'lonstatus'}{$item})) {
12635:                             if (($item eq 'threshold') || ($item eq 'sysmail')) {
12636:                                 $shown{$item} = $contacts_hash{'contacts'}{'lonstatus'}{$item};
12637:                             } elsif ($item eq 'weights') {
12638:                                 if (ref($contacts_hash{'contacts'}{'lonstatus'}{$item}) eq 'HASH') {
12639:                                     foreach my $type ('E','W','N','U') {
12640:                                         $shown{$item} .= $lonstatus_names->{$type}.'=';
12641:                                         if (exists($contacts_hash{'contacts'}{'lonstatus'}{$item}{$type})) {
12642:                                             $shown{$item} .= $contacts_hash{'contacts'}{'lonstatus'}{$item}{$type};
12643:                                         } else {
12644:                                             $shown{$item} .= $lonstatus_defs->{$type};
12645:                                         }
12646:                                         $shown{$item} .= ', ';
12647:                                     }
12648:                                     $shown{$item} =~ s/, $//;
12649:                                 } else {
12650:                                     $shown{$item} = $defval{$item};
12651:                                 }
12652:                             } elsif ($item eq 'excluded') {
12653:                                 if (ref($contacts_hash{'contacts'}{'lonstatus'}{$item}) eq 'ARRAY') {
12654:                                     $shown{$item} = join(', ',@{$contacts_hash{'contacts'}{'lonstatus'}{$item}});
12655:                                 } else {
12656:                                     $shown{$item} = $defval{$item};
12657:                                 }
12658:                             }
12659:                         } else {
12660:                             $shown{$item} = $defval{$item};
12661:                         }
12662:                     }
12663:                 } else {
12664:                     foreach my $item ('threshold','weights','excluded','sysmail') {
12665:                         $shown{$item} = $defval{$item};
12666:                     }
12667:                 }
12668:                 foreach my $item ('threshold','weights','excluded','sysmail') {
12669:                     $resulttext .= '<li>'.&mt($titles->{'error'.$item}.' -- [_1]',
12670:                                           $shown{$item}).'</li>';
12671:                 }
12672:                 $resulttext .= '</ul></li>';
12673:             }
12674:             if ((ref($changes{'helpform'}) eq 'ARRAY') && (ref($fields) eq 'ARRAY')) {
12675:                 my (@optional,@required,@unused,$maxsizechg);
12676:                 foreach my $field (@{$changes{'helpform'}}) {
12677:                     if ($field eq 'maxsize') {
12678:                         $maxsizechg = 1;
12679:                         next;
12680:                     }
12681:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'yes') {
12682:                         push(@optional,$field);
12683:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'no') {
12684:                         push(@unused,$field);
12685:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'req') {
12686:                         push(@required,$field);
12687:                     }
12688:                 }
12689:                 if (@optional) {
12690:                     $resulttext .= '<li>'.
12691:                                    &mt('Help form fields changed to "Optional": [_1].',
12692:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @optional)).'</span>'.
12693:                                    '</li>';
12694:                 }
12695:                 if (@required) {
12696:                     $resulttext .= '<li>'.
12697:                                    &mt('Help form fields changed to "Required": [_1].',
12698:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @required)).'</span>'.
12699:                                    '</li>';
12700:                 }
12701:                 if (@unused) {
12702:                     $resulttext .= '<li>'.
12703:                                    &mt('Help form fields changed to "Not shown": [_1].',
12704:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @unused)).'</span>'.
12705:                                    '</li>';
12706:                 }
12707:                 if ($maxsizechg) {
12708:                     $resulttext .= '<li>'.
12709:                                    &mt('Max size for file uploaded to help form by logged-in user set to [_1] MB.',
12710:                                        $contacts_hash{'contacts'}{'helpform'}{'maxsize'}).
12711:                                    '</li>';
12712:                 }
12713:             }
12714:             $resulttext .= '</ul>';
12715:         } else {
12716:             $resulttext = &mt('No changes made to contacts and form settings');
12717:         }
12718:     } else {
12719:         $resulttext = '<span class="LC_error">'.
12720:             &mt('An error occurred: [_1].',$putresult).'</span>';
12721:     }
12722:     return $resulttext;
12723: }
12724: 
12725: sub modify_passwords {
12726:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
12727:     my ($resulttext,%current,%changes,%newvalues,@oktypes,$errors,
12728:         $updatedefaults,$updateconf);
12729:     my $customfn = 'resetpw.html';
12730:     if (ref($domconfig{'passwords'}) eq 'HASH') {
12731:         %current = %{$domconfig{'passwords'}};
12732:     }
12733:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
12734:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
12735:     if (ref($types) eq 'ARRAY') {
12736:         @oktypes = @{$types};
12737:     }
12738:     push(@oktypes,'default');
12739: 
12740:     my %titles = &Apache::lonlocal::texthash (
12741:         intauth_cost   => 'Encryption cost for bcrypt (positive integer)',
12742:         intauth_check  => 'Check bcrypt cost if authenticated',
12743:         intauth_switch => 'Existing crypt-based switched to bcrypt on authentication',
12744:         permanent      => 'Permanent e-mail address',
12745:         critical       => 'Critical notification address',
12746:         notify         => 'Notification address',
12747:         min            => 'Minimum password length',
12748:         max            => 'Maximum password length',
12749:         chars          => 'Required characters',
12750:         numsaved       => 'Number of previous passwords to save',
12751:         reset          => 'Resetting Forgotten Password',
12752:         intauth        => 'Encryption of Stored Passwords (Internal Auth)',
12753:         rules          => 'Rules for LON-CAPA Passwords',
12754:         crsownerchg    => 'Course Owner Changing Student Passwords',
12755:         username       => 'Username',
12756:         email          => 'E-mail address',
12757:     );
12758: 
12759: #
12760: # Retrieve current domain configuration for internal authentication from $domconfig{'defaults'}.
12761: #
12762:     my (%curr_defaults,%save_defaults);
12763:     if (ref($domconfig{'defaults'}) eq 'HASH') {
12764:         foreach my $key (keys(%{$domconfig{'defaults'}})) {
12765:             if ($key =~ /^intauth_(cost|check|switch)$/) {
12766:                 $curr_defaults{$key} = $domconfig{'defaults'}{$key};
12767:             } else {
12768:                 $save_defaults{$key} = $domconfig{'defaults'}{$key};
12769:             }
12770:         }
12771:     }
12772:     my %staticdefaults = (
12773:         'resetlink'      => 2,
12774:         'resetcase'      => \@oktypes,
12775:         'resetprelink'   => 'both',
12776:         'resetemail'     => ['critical','notify','permanent'],
12777:         'intauth_cost'   => 10,
12778:         'intauth_check'  => 0,
12779:         'intauth_switch' => 0,
12780:     );
12781:     $staticdefaults{'min'} = $Apache::lonnet::passwdmin;
12782:     foreach my $type (@oktypes) {
12783:         $staticdefaults{'resetpostlink'}{$type} = ['email','username'];
12784:     }
12785:     my $linklife = $env{'form.passwords_link'};
12786:     $linklife =~ s/^\s+|\s+$//g;
12787:     if (($linklife =~ /^\d+(|\.\d*)$/) && ($linklife > 0)) {
12788:         $newvalues{'resetlink'} = $linklife;
12789:         if ($current{'resetlink'}) {
12790:             if ($current{'resetlink'} ne $linklife) {
12791:                 $changes{'reset'} = 1;
12792:             }
12793:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
12794:             if ($staticdefaults{'resetlink'} ne $linklife) {
12795:                 $changes{'reset'} = 1;
12796:             }
12797:         }
12798:     } elsif ($current{'resetlink'}) {
12799:         $changes{'reset'} = 1;
12800:     }
12801:     my @casesens;
12802:     my @posscase = &Apache::loncommon::get_env_multiple('form.passwords_case_sensitive');
12803:     foreach my $case (sort(@posscase)) {
12804:         if (grep(/^\Q$case\E$/,@oktypes)) {
12805:             push(@casesens,$case);
12806:         }
12807:     }
12808:     $newvalues{'resetcase'} = \@casesens;
12809:     if (ref($current{'resetcase'}) eq 'ARRAY') {
12810:         my @diffs = &Apache::loncommon::compare_arrays($current{'resetcase'},\@casesens);
12811:         if (@diffs > 0) {
12812:             $changes{'reset'} = 1;
12813:         }
12814:     } elsif (!ref($domconfig{passwords}) eq 'HASH') {
12815:         my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetcase'},\@casesens);
12816:         if (@diffs > 0) {
12817:             $changes{'reset'} = 1;
12818:         }
12819:     }
12820:     if ($env{'form.passwords_prelink'} =~ /^(both|either)$/) {
12821:         $newvalues{'resetprelink'} = $env{'form.passwords_prelink'};
12822:         if (exists($current{'resetprelink'})) {
12823:             if ($current{'resetprelink'} ne $newvalues{'resetprelink'}) {
12824:                 $changes{'reset'} = 1;
12825:             }
12826:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
12827:             if ($staticdefaults{'resetprelink'} ne $newvalues{'resetprelink'}) {
12828:                 $changes{'reset'} = 1;
12829:             }
12830:         }
12831:     } elsif ($current{'resetprelink'}) {
12832:         $changes{'reset'} = 1;
12833:     }
12834:     foreach my $type (@oktypes) {
12835:         my @possplink = &Apache::loncommon::get_env_multiple('form.passwords_postlink_'.$type);
12836:         my @postlink;
12837:         foreach my $item (sort(@possplink)) {
12838:             if ($item =~ /^(email|username)$/) {
12839:                 push(@postlink,$item);
12840:             }
12841:         }
12842:         $newvalues{'resetpostlink'}{$type} = \@postlink;
12843:         unless ($changes{'reset'}) {
12844:             if (ref($current{'resetpostlink'}) eq 'HASH') {
12845:                 if (ref($current{'resetpostlink'}{$type}) eq 'ARRAY') {
12846:                     my @diffs = &Apache::loncommon::compare_arrays($current{'resetpostlink'}{$type},\@postlink);
12847:                     if (@diffs > 0) {
12848:                         $changes{'reset'} = 1;
12849:                     }
12850:                 } else {
12851:                     $changes{'reset'} = 1;
12852:                 }
12853:             } elsif (!ref($domconfig{passwords}) eq 'HASH') {
12854:                 my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetpostlink'}{$type},\@postlink);
12855:                 if (@diffs > 0) {
12856:                     $changes{'reset'} = 1;
12857:                 }
12858:             }
12859:         }
12860:     }
12861:     my @possemailsrc = &Apache::loncommon::get_env_multiple('form.passwords_emailsrc');
12862:     my @resetemail;
12863:     foreach my $item (sort(@possemailsrc)) {
12864:         if ($item =~ /^(permanent|critical|notify)$/) {
12865:             push(@resetemail,$item);
12866:         }
12867:     }
12868:     $newvalues{'resetemail'} = \@resetemail;
12869:     unless ($changes{'reset'}) {
12870:         if (ref($current{'resetemail'}) eq 'ARRAY') {
12871:             my @diffs = &Apache::loncommon::compare_arrays($current{'resetemail'},\@resetemail);
12872:             if (@diffs > 0) {
12873:                 $changes{'reset'} = 1;
12874:             }
12875:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
12876:             my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetemail'},\@resetemail);
12877:             if (@diffs > 0) {
12878:                 $changes{'reset'} = 1;
12879:             }
12880:         }
12881:     }
12882:     if ($env{'form.passwords_stdtext'} == 0) {
12883:         $newvalues{'resetremove'} = 1;
12884:         unless ($current{'resetremove'}) {
12885:             $changes{'reset'} = 1;
12886:         }
12887:     } elsif ($current{'resetremove'}) {
12888:         $changes{'reset'} = 1;
12889:     }
12890:     if ($env{'form.passwords_customfile.filename'} ne '') {
12891:         my $servadm = $r->dir_config('lonAdmEMail');
12892:         my $servadm = $r->dir_config('lonAdmEMail');
12893:         my ($configuserok,$author_ok,$switchserver) =
12894:             &config_check($dom,$confname,$servadm);
12895:         my $error;
12896:         if ($configuserok eq 'ok') {
12897:             if ($switchserver) {
12898:                 $error = &mt("Upload of file containing domain-specific text is not permitted to this server: [_1]",$switchserver);
12899:             } else {
12900:                 if ($author_ok eq 'ok') {
12901:                     my ($result,$customurl) =
12902:                         &publishlogo($r,'upload','passwords_customfile',$dom,
12903:                                      $confname,'customtext/resetpw','','',$customfn);
12904:                     if ($result eq 'ok') {
12905:                         $newvalues{'resetcustom'} = $customurl;
12906:                         $changes{'reset'} = 1;
12907:                     } else {
12908:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$customfn,$result);
12909:                     }
12910:                 } else {
12911:                     $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);
12912:                 }
12913:             }
12914:         } else {
12915:             $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);
12916:         }
12917:         if ($error) {
12918:             &Apache::lonnet::logthis($error);
12919:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12920:         }
12921:     } elsif ($current{'resetcustom'}) {
12922:         if ($env{'form.passwords_custom_del'}) {
12923:             $changes{'reset'} = 1;
12924:         } else {
12925:             $newvalues{'resetcustom'} = $current{'resetcustom'};
12926:         }
12927:     }
12928:     $env{'form.intauth_cost'} =~ s/^\s+|\s+$//g;
12929:     if (($env{'form.intauth_cost'} ne '') && ($env{'form.intauth_cost'} =~ /^\d+$/)) {
12930:         $save_defaults{'intauth_cost'} = $env{'form.intauth_cost'};
12931:         if ($save_defaults{'intauth_cost'} ne $curr_defaults{'intauth_cost'}) {
12932:             $changes{'intauth'} = 1;
12933:         }
12934:     } else {
12935:         $save_defaults{'intauth_cost'} = $curr_defaults{'intauth_cost'};
12936:     }
12937:     if ($env{'form.intauth_check'} =~ /^(0|1|2)$/) {
12938:         $save_defaults{'intauth_check'} = $env{'form.intauth_check'};
12939:         if ($save_defaults{'intauth_check'} ne $curr_defaults{'intauth_check'}) {
12940:             $changes{'intauth'} = 1;
12941:         }
12942:     } else {
12943:         $save_defaults{'intauth_check'} = $curr_defaults{'intauth_check'};
12944:     }
12945:     if ($env{'form.intauth_switch'} =~ /^(0|1|2)$/) {
12946:         $save_defaults{'intauth_switch'} = $env{'form.intauth_switch'};
12947:         if ($save_defaults{'intauth_switch'} ne $curr_defaults{'intauth_switch'}) {
12948:             $changes{'intauth'} = 1;
12949:         }
12950:     } else {
12951:         $save_defaults{'intauth_check'} = $curr_defaults{'intauth_check'};
12952:     }
12953:     foreach my $item ('cost','check','switch') {
12954:         if ($save_defaults{'intauth_'.$item} ne $domdefaults{'intauth_'.$item}) {
12955:             $domdefaults{'intauth_'.$item} = $save_defaults{'intauth_'.$item};
12956:             $updatedefaults = 1;
12957:         }
12958:     }
12959:     foreach my $rule ('min','max','numsaved') {
12960:         $env{'form.passwords_'.$rule} =~ s/^\s+|\s+$//g;
12961:         my $ruleok;
12962:         if ($rule eq 'min') {
12963:             if ($env{'form.passwords_'.$rule} =~ /^\d+$/) {
12964:                 if ($env{'form.passwords_'.$rule} >= $Apache::lonnet::passwdmin) {
12965:                     $ruleok = 1;
12966:                 }
12967:             }
12968:         } elsif (($env{'form.passwords_'.$rule} =~ /^\d+$/) &&
12969:                  ($env{'form.passwords_'.$rule} ne '0')) {
12970:             $ruleok = 1;
12971:         }
12972:         if ($ruleok) {
12973:             $newvalues{$rule} = $env{'form.passwords_'.$rule};
12974:             if (exists($current{$rule})) {
12975:                 if ($newvalues{$rule} ne $current{$rule}) {
12976:                     $changes{'rules'} = 1;
12977:                 }
12978:             } elsif ($rule eq 'min') {
12979:                 if ($staticdefaults{$rule} ne $newvalues{$rule}) {
12980:                     $changes{'rules'} = 1;
12981:                 }
12982:             } else {
12983:                 $changes{'rules'} = 1;
12984:             }
12985:         } elsif (exists($current{$rule})) {
12986:             $changes{'rules'} = 1;
12987:         }
12988:     }
12989:     my @posschars = &Apache::loncommon::get_env_multiple('form.passwords_chars');
12990:     my @chars;
12991:     foreach my $item (sort(@posschars)) {
12992:         if ($item =~ /^(uc|lc|num|spec)$/) {
12993:             push(@chars,$item);
12994:         }
12995:     }
12996:     $newvalues{'chars'} = \@chars;
12997:     unless ($changes{'rules'}) {
12998:         if (ref($current{'chars'}) eq 'ARRAY') {
12999:             my @diffs = &Apache::loncommon::compare_arrays($current{'chars'},\@chars);
13000:             if (@diffs > 0) {
13001:                 $changes{'rules'} = 1;
13002:             }
13003:         } else {
13004:             if (@chars > 0) {
13005:                 $changes{'rules'} = 1;
13006:             }
13007:         }
13008:     }
13009:     my %crsownerchg = (
13010:                         by => [],
13011:                         for => [],
13012:                       );
13013:     foreach my $item ('by','for') {
13014:         my @posstypes = &Apache::loncommon::get_env_multiple('form.passwords_crsowner_'.$item);
13015:         foreach my $type (sort(@posstypes)) {
13016:             if (grep(/^\Q$type\E$/,@oktypes)) {
13017:                 push(@{$crsownerchg{$item}},$type);
13018:             }
13019:         }
13020:     }
13021:     $newvalues{'crsownerchg'} = \%crsownerchg;
13022:     if (ref($current{'crsownerchg'}) eq 'HASH') {
13023:         foreach my $item ('by','for') {
13024:             if (ref($current{'crsownerchg'}{$item}) eq 'ARRAY') {
13025:                 my @diffs = &Apache::loncommon::compare_arrays($current{'crsownerchg'}{$item},$crsownerchg{$item});
13026:                 if (@diffs > 0) {
13027:                     $changes{'crsownerchg'} = 1;
13028:                     last;
13029:                 }
13030:             }
13031:         }
13032:     } elsif (!(ref($domconfig{passwords}) eq 'HASH')) {
13033:         foreach my $item ('by','for') {
13034:             if (@{$crsownerchg{$item}} > 0) {
13035:                 $changes{'crsownerchg'} = 1;
13036:                 last;
13037:             }
13038:         }
13039:     }
13040: 
13041:     my %confighash = (
13042:                         defaults  => \%save_defaults,
13043:                         passwords => \%newvalues,
13044:                      );
13045:     &process_captcha('passwords',\%changes,$confighash{'passwords'},$domconfig{'passwords'});
13046: 
13047:     my $putresult = &Apache::lonnet::put_dom('configuration',\%confighash,$dom);
13048:     if ($putresult eq 'ok') {
13049:         if (keys(%changes) > 0) {
13050:             $resulttext = &mt('Changes made: ').'<ul>';
13051:             foreach my $key ('reset','intauth','rules','crsownerchg') {
13052:                 if ($changes{$key}) {
13053:                     unless ($key eq 'intauth') {
13054:                         $updateconf = 1;
13055:                     }
13056:                     $resulttext .= '<li>'.$titles{$key}.':<ul>';
13057:                     if ($key eq 'reset') {
13058:                         if ($confighash{'passwords'}{'captcha'} eq 'original') {
13059:                             $resulttext .= '<li>'.&mt('CAPTCHA validation set to use: original CAPTCHA').'</li>';
13060:                         } elsif ($confighash{'passwords'}{'captcha'} eq 'recaptcha') {
13061:                             $resulttext .= '<li>'.&mt('CAPTCHA validation set to use: reCAPTCHA').' '.
13062:                                            &mt('version: [_1]',$confighash{'passwords'}{'recaptchaversion'}).'<br />';
13063:                             if (ref($confighash{'passwords'}{'recaptchakeys'}) eq 'HASH') {
13064:                                 $resulttext .= &mt('Public key: [_1]',$confighash{'passwords'}{'recaptchakeys'}{'public'}).'</br>'.
13065:                                                &mt('Private key: [_1]',$confighash{'passwords'}{'recaptchakeys'}{'private'}).'</li>';
13066:                             }
13067:                         } else {
13068:                             $resulttext .= '<li>'.&mt('No CAPTCHA validation').'</li>';
13069:                         }
13070:                         if ($confighash{'passwords'}{'resetlink'}) {
13071:                             $resulttext .= '<li>'.&mt('Reset link expiration set to [quant,_1,hour]',$confighash{'passwords'}{'resetlink'}).'</li>';
13072:                         } else {
13073:                             $resulttext .= '<li>'.&mt('No reset link expiration set.').' '.
13074:                                                   &mt('Will default to 2 hours').'</li>';
13075:                         }
13076:                         if (ref($confighash{'passwords'}{'resetcase'}) eq 'ARRAY') {
13077:                             if (@{$confighash{'passwords'}{'resetcase'}} == 0) {
13078:                                 $resulttext .= '<li>'.&mt('User input for username and/or e-mail address not case sensitive for "Forgot Password" web form').'</li>';
13079:                             } else {
13080:                                 my $casesens;
13081:                                 foreach my $type (@{$confighash{'passwords'}{'resetcase'}}) {
13082:                                     if ($type eq 'default') {
13083:                                         $casesens .= $othertitle.', ';
13084:                                     } elsif ($usertypes->{$type} ne '') {
13085:                                         $casesens .= $usertypes->{$type}.', ';
13086:                                     }
13087:                                 }
13088:                                 $casesens =~ s/\Q, \E$//;
13089:                                 $resulttext .= '<li>'.&mt('"Forgot Password" web form input for username and/or e-mail address is case-sensitive for: [_1]',$casesens).'</li>';
13090:                             }
13091:                         } else {
13092:                             $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>';
13093:                         }
13094:                         if ($confighash{'passwords'}{'resetprelink'} eq 'either') {
13095:                             $resulttext .= '<li>'.&mt('Users can enter either a username or an e-mail address in "Forgot Password" web form').'</li>';
13096:                         } else {
13097:                             $resulttext .= '<li>'.&mt('Users can enter both a username and an e-mail address in "Forgot Password" web form').'</li>';
13098:                         }
13099:                         if (ref($confighash{'passwords'}{'resetpostlink'}) eq 'HASH') {
13100:                             my $output;
13101:                             if (ref($types) eq 'ARRAY') {
13102:                                 foreach my $type (@{$types}) {
13103:                                     if (ref($confighash{'passwords'}{'resetpostlink'}{$type}) eq 'ARRAY') {
13104:                                         if (@{$confighash{'passwords'}{'resetpostlink'}{$type}} == 0) {
13105:                                             $output .= $usertypes->{$type}.' -- '.&mt('none');
13106:                                         } else {
13107:                                             $output .= $usertypes->{$type}.' -- '.
13108:                                                        join(', ',map { $titles{$_}; } (@{$confighash{'passwords'}{'resetpostlink'}{$type}})).'; ';
13109:                                         }
13110:                                     }
13111:                                 }
13112:                             }
13113:                             if (ref($confighash{'passwords'}{'resetpostlink'}{'default'}) eq 'ARRAY') {
13114:                                 if (@{$confighash{'passwords'}{'resetpostlink'}{'default'}} == 0) {
13115:                                     $output .= $othertitle.' -- '.&mt('none');
13116:                                 } else {
13117:                                     $output .= $othertitle.' -- '.
13118:                                                join(', ',map { $titles{$_}; } (@{$confighash{'passwords'}{'resetpostlink'}{'default'}}));
13119:                                 }
13120:                             }
13121:                             if ($output) {
13122:                                 $resulttext .= '<li>'.&mt('Information required for new password form (by user type) set to: [_1]',$output).'</li>';
13123:                             } else {
13124:                                 $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>';
13125:                             }
13126:                         } else {
13127:                             $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>';
13128:                         }
13129:                         if (ref($confighash{'passwords'}{'resetemail'}) eq 'ARRAY') {
13130:                             if (@{$confighash{'passwords'}{'resetemail'}} > 0) {
13131:                                 $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$confighash{'passwords'}{'resetemail'}})).'</li>';
13132:                             } else {
13133:                                 $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$staticdefaults{'resetemail'}})).'</li>';
13134:                             }
13135:                         } else {
13136:                             $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$staticdefaults{'resetemail'}})).'</li>';
13137:                         }
13138:                         if ($confighash{'passwords'}{'resetremove'}) {
13139:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" web form not shown').'</li>';
13140:                         } else {
13141:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" web form is shown').'</li>';
13142:                         }
13143:                         if ($confighash{'passwords'}{'resetcustom'}) {
13144:                             my $customlink = &Apache::loncommon::modal_link($confighash{'passwords'}{'resetcustom'},
13145:                                                                             &mt('custom text'),600,500,undef,undef,
13146:                                                                             undef,undef,'background-color:#ffffff');
13147:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" form includes: [_1]',$customlink).'</li>';
13148:                         } else {
13149:                             $resulttext .= '<li>'.&mt('No custom text included in preamble to "Forgot Password" form').'</li>';
13150:                         }
13151:                     } elsif ($key eq 'intauth') {
13152:                         foreach my $item ('cost','switch','check') {
13153:                             my $value = $save_defaults{$key.'_'.$item};
13154:                             if ($item eq 'switch') {
13155:                                 my %optiondesc = &Apache::lonlocal::texthash (
13156:                                                      0 => 'No',
13157:                                                      1 => 'Yes',
13158:                                                      2 => 'Yes, and copy existing passwd file to passwd.bak file',
13159:                                                  );
13160:                                 if ($value =~ /^(0|1|2)$/) {
13161:                                     $value = $optiondesc{$value};
13162:                                 } else {
13163:                                     $value = &mt('none -- defaults to No');
13164:                                 }
13165:                             } elsif ($item eq 'check') {
13166:                                 my %optiondesc = &Apache::lonlocal::texthash (
13167:                                                      0 => 'No',
13168:                                                      1 => 'Yes, allow login then update passwd file using default cost (if higher)',
13169:                                                      2 => 'Yes, disallow login if stored cost is less than domain default',
13170:                                                  );
13171:                                 if ($value =~ /^(0|1|2)$/) {
13172:                                     $value = $optiondesc{$value};
13173:                                 } else {
13174:                                     $value = &mt('none -- defaults to No');
13175:                                 }
13176:                             }
13177:                             $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$titles{$key.'_'.$item},$value).'</li>';
13178:                         }
13179:                     } elsif ($key eq 'rules') {
13180:                         foreach my $rule ('min','max','numsaved') {
13181:                             if ($confighash{'passwords'}{$rule} eq '') {
13182:                                 if ($rule eq 'min') {
13183:                                     $resulttext .= '<li>'.&mt('[_1] not set.',$titles{$rule});
13184:                                                    ' '.&mt('Default of [_1] will be used',
13185:                                                            $Apache::lonnet::passwdmin).'</li>';
13186:                                 } else {
13187:                                     $resulttext .= '<li>'.&mt('[_1] set to none',$titles{$rule}).'</li>';
13188:                                 }
13189:                             } else {
13190:                                 $resulttext .= '<li>'.&mt('[_1] set to [_2]',$titles{$rule},$confighash{'passwords'}{$rule}).'</li>';
13191:                             }
13192:                         }
13193:                         if (ref($confighash{'passwords'}{'chars'}) eq 'ARRAY') {
13194:                             if (@{$confighash{'passwords'}{'chars'}} > 0) {
13195:                                 my %rulenames = &Apache::lonlocal::texthash(
13196:                                                      uc => 'At least one upper case letter',
13197:                                                      lc => 'At least one lower case letter',
13198:                                                      num => 'At least one number',
13199:                                                      spec => 'At least one non-alphanumeric',
13200:                                                    );
13201:                                 my $needed = '<ul><li>'.
13202:                                              join('</li><li>',map {$rulenames{$_} } @{$confighash{'passwords'}{'chars'}}).
13203:                                              '</li></ul>';
13204:                                 $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$titles{'chars'},$needed).'</li>';
13205:                             } else {
13206:                                 $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
13207:                             }
13208:                         } else {
13209:                             $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
13210:                         }
13211:                     } elsif ($key eq 'crsownerchg') {
13212:                         if (ref($confighash{'passwords'}{'crsownerchg'}) eq 'HASH') {
13213:                             if ((@{$confighash{'passwords'}{'crsownerchg'}{'by'}} == 0) ||
13214:                                 (@{$confighash{'passwords'}{'crsownerchg'}{'for'}} == 0)) {
13215:                                 $resulttext .= '<li>'.&mt('Course owner may not change student passwords.').'</li>';
13216:                             } else {
13217:                                 my %crsownerstr;
13218:                                 foreach my $item ('by','for') {
13219:                                     if (ref($confighash{'passwords'}{'crsownerchg'}{$item}) eq 'ARRAY') {
13220:                                         foreach my $type (@{$confighash{'passwords'}{'crsownerchg'}{$item}}) {
13221:                                             if ($type eq 'default') {
13222:                                                 $crsownerstr{$item} .= $othertitle.', ';
13223:                                             } elsif ($usertypes->{$type} ne '') {
13224:                                                 $crsownerstr{$item} .= $usertypes->{$type}.', ';
13225:                                             }
13226:                                         }
13227:                                         $crsownerstr{$item} =~ s/\Q, \E$//;
13228:                                     }
13229:                                 }
13230:                                 $resulttext .= '<li>'.&mt('Course owner (with status: [_1]) may change passwords for students (with status: [_2]).',
13231:                                            $crsownerstr{'by'},$crsownerstr{'for'}).'</li>';
13232:                             }
13233:                         } else {
13234:                             $resulttext .= '<li>'.&mt('Course owner may not change student passwords.').'</li>';
13235:                         }
13236:                     }
13237:                     $resulttext .= '</ul></li>';
13238:                 }
13239:             }
13240:             $resulttext .= '</ul>';
13241:         } else {
13242:             $resulttext = &mt('No changes made to password settings');
13243:         }
13244:         my $cachetime = 24*60*60;
13245:         if ($updatedefaults) {
13246:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
13247:             if (ref($lastactref) eq 'HASH') {
13248:                 $lastactref->{'domdefaults'} = 1;
13249:             }
13250:         }
13251:         if ($updateconf) {
13252:             &Apache::lonnet::do_cache_new('passwdconf',$dom,$confighash{'passwords'},$cachetime);
13253:             if (ref($lastactref) eq 'HASH') {
13254:                 $lastactref->{'passwdconf'} = 1;
13255:             }
13256:         }
13257:     } else {
13258:         $resulttext = '<span class="LC_error">'.
13259:             &mt('An error occurred: [_1]',$putresult).'</span>';
13260:     }
13261:     if ($errors) {
13262:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
13263:                        $errors.'</ul></p>';
13264:     }
13265:     return $resulttext;
13266: }
13267: 
13268: sub modify_usercreation {
13269:     my ($dom,%domconfig) = @_;
13270:     my ($resulttext,%curr_usercreation,%changes,%authallowed,%cancreate,%save_usercreate);
13271:     my $warningmsg;
13272:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
13273:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
13274:             if ($key eq 'cancreate') {
13275:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
13276:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
13277:                         if (($item eq 'requestcrs') || ($item eq 'course') || ($item eq 'author')) {
13278:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
13279:                         } else {
13280:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
13281:                         }
13282:                     }
13283:                 }
13284:             } elsif ($key eq 'email_rule') {
13285:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
13286:             } else {
13287:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
13288:             }
13289:         }
13290:     }
13291:     my @username_rule = &Apache::loncommon::get_env_multiple('form.username_rule');
13292:     my @id_rule = &Apache::loncommon::get_env_multiple('form.id_rule');
13293:     my @contexts = ('author','course','requestcrs');
13294:     foreach my $item(@contexts) {
13295:         $cancreate{$item} = $env{'form.can_createuser_'.$item};
13296:     }
13297:     if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
13298:         foreach my $item (@contexts) {
13299:             if ($curr_usercreation{'cancreate'}{$item} ne $cancreate{$item}) {
13300:                 push(@{$changes{'cancreate'}},$item);
13301:             }
13302:         }
13303:     } elsif (ref($curr_usercreation{'cancreate'}) eq 'ARRAY') {
13304:         foreach my $item (@contexts) {
13305:             if (!grep(/^\Q$item\E$/,@{$curr_usercreation{'cancreate'}})) {
13306:                 if ($cancreate{$item} ne 'any') {
13307:                     push(@{$changes{'cancreate'}},$item);
13308:                 }
13309:             } else {
13310:                 if ($cancreate{$item} ne 'none') {
13311:                     push(@{$changes{'cancreate'}},$item);
13312:                 }
13313:             }
13314:         }
13315:     } else {
13316:         foreach my $item (@contexts)  {
13317:             push(@{$changes{'cancreate'}},$item);
13318:         }
13319:     }
13320: 
13321:     if (ref($curr_usercreation{'username_rule'}) eq 'ARRAY') {
13322:         foreach my $type (@{$curr_usercreation{'username_rule'}}) {
13323:             if (!grep(/^\Q$type\E$/,@username_rule)) {
13324:                 push(@{$changes{'username_rule'}},$type);
13325:             }
13326:         }
13327:         foreach my $type (@username_rule) {
13328:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'username_rule'}})) {
13329:                 push(@{$changes{'username_rule'}},$type);
13330:             }
13331:         }
13332:     } else {
13333:         push(@{$changes{'username_rule'}},@username_rule);
13334:     }
13335: 
13336:     if (ref($curr_usercreation{'id_rule'}) eq 'ARRAY') {
13337:         foreach my $type (@{$curr_usercreation{'id_rule'}}) {
13338:             if (!grep(/^\Q$type\E$/,@id_rule)) {
13339:                 push(@{$changes{'id_rule'}},$type);
13340:             }
13341:         }
13342:         foreach my $type (@id_rule) {
13343:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'id_rule'}})) {
13344:                 push(@{$changes{'id_rule'}},$type);
13345:             }
13346:         }
13347:     } else {
13348:         push(@{$changes{'id_rule'}},@id_rule);
13349:     }
13350: 
13351:     my @authen_contexts = ('author','course','domain');
13352:     my @authtypes = ('int','krb4','krb5','loc');
13353:     my %authhash;
13354:     foreach my $item (@authen_contexts) {
13355:         my @authallowed =  &Apache::loncommon::get_env_multiple('form.'.$item.'_auth');
13356:         foreach my $auth (@authtypes) {
13357:             if (grep(/^\Q$auth\E$/,@authallowed)) {
13358:                 $authhash{$item}{$auth} = 1;
13359:             } else {
13360:                 $authhash{$item}{$auth} = 0;
13361:             }
13362:         }
13363:     }
13364:     if (ref($curr_usercreation{'authtypes'}) eq 'HASH') {
13365:         foreach my $item (@authen_contexts) {
13366:             if (ref($curr_usercreation{'authtypes'}{$item}) eq 'HASH') {
13367:                 foreach my $auth (@authtypes) {
13368:                     if ($authhash{$item}{$auth} ne $curr_usercreation{'authtypes'}{$item}{$auth}) {
13369:                         push(@{$changes{'authtypes'}},$item);
13370:                         last;
13371:                     }
13372:                 }
13373:             }
13374:         }
13375:     } else {
13376:         foreach my $item (@authen_contexts) {
13377:             push(@{$changes{'authtypes'}},$item);
13378:         }
13379:     }
13380: 
13381:     $save_usercreate{'cancreate'}{'course'} = $cancreate{'course'}; 
13382:     $save_usercreate{'cancreate'}{'author'} = $cancreate{'author'};
13383:     $save_usercreate{'cancreate'}{'requestcrs'} = $cancreate{'requestcrs'};
13384:     $save_usercreate{'id_rule'} = \@id_rule;
13385:     $save_usercreate{'username_rule'} = \@username_rule,
13386:     $save_usercreate{'authtypes'} = \%authhash;
13387: 
13388:     my %usercreation_hash =  (
13389:         usercreation     => \%save_usercreate,
13390:     );
13391: 
13392:     my $putresult = &Apache::lonnet::put_dom('configuration',\%usercreation_hash,
13393:                                              $dom);
13394: 
13395:     if ($putresult eq 'ok') {
13396:         if (keys(%changes) > 0) {
13397:             $resulttext = &mt('Changes made:').'<ul>';
13398:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
13399:                 my %lt = &usercreation_types();
13400:                 foreach my $type (@{$changes{'cancreate'}}) {
13401:                     my $chgtext = $lt{$type}.', ';
13402:                     if ($cancreate{$type} eq 'none') {
13403:                         $chgtext .= &mt('creation of new users is not permitted, except by a Domain Coordinator.');
13404:                     } elsif ($cancreate{$type} eq 'any') {
13405:                         $chgtext .= &mt('creation of new users is permitted for both institutional and non-institutional usernames.');
13406:                     } elsif ($cancreate{$type} eq 'official') {
13407:                         $chgtext .= &mt('creation of new users is only permitted for institutional usernames.');
13408:                     } elsif ($cancreate{$type} eq 'unofficial') {
13409:                         $chgtext .= &mt('creation of new users is only permitted for non-institutional usernames.');
13410:                     }
13411:                     $resulttext .= '<li>'.$chgtext.'</li>';
13412:                 }
13413:             }
13414:             if (ref($changes{'username_rule'}) eq 'ARRAY') {
13415:                 my ($rules,$ruleorder) = 
13416:                     &Apache::lonnet::inst_userrules($dom,'username');
13417:                 my $chgtext = '<ul>';
13418:                 foreach my $type (@username_rule) {
13419:                     if (ref($rules->{$type}) eq 'HASH') {
13420:                         $chgtext .= '<li>'.$rules->{$type}{'name'}.'</li>';
13421:                     }
13422:                 }
13423:                 $chgtext .= '</ul>';
13424:                 if (@username_rule > 0) {
13425:                     $resulttext .= '<li>'.&mt('Usernames with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';     
13426:                 } else {
13427:                     $resulttext .= '<li>'.&mt('There are now no username formats restricted to verified users in the institutional directory.').'</li>'; 
13428:                 }
13429:             }
13430:             if (ref($changes{'id_rule'}) eq 'ARRAY') {
13431:                 my ($idrules,$idruleorder) = 
13432:                     &Apache::lonnet::inst_userrules($dom,'id');
13433:                 my $chgtext = '<ul>';
13434:                 foreach my $type (@id_rule) {
13435:                     if (ref($idrules->{$type}) eq 'HASH') {
13436:                         $chgtext .= '<li>'.$idrules->{$type}{'name'}.'</li>';
13437:                     }
13438:                 }
13439:                 $chgtext .= '</ul>';
13440:                 if (@id_rule > 0) {
13441:                     $resulttext .= '<li>'.&mt('IDs with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';
13442:                 } else {
13443:                     $resulttext .= '<li>'.&mt('There are now no ID formats restricted to verified users in the institutional directory.').'</li>';
13444:                 }
13445:             }
13446:             my %authname = &authtype_names();
13447:             my %context_title = &context_names();
13448:             if (ref($changes{'authtypes'}) eq 'ARRAY') {
13449:                 my $chgtext = '<ul>';
13450:                 foreach my $type (@{$changes{'authtypes'}}) {
13451:                     my @allowed;
13452:                     $chgtext .= '<li><span class="LC_cusr_emph">'.$context_title{$type}.'</span> - '.&mt('assignable authentication types: ');
13453:                     foreach my $auth (@authtypes) {
13454:                         if ($authhash{$type}{$auth}) {
13455:                             push(@allowed,$authname{$auth});
13456:                         }
13457:                     }
13458:                     if (@allowed > 0) {
13459:                         $chgtext .= join(', ',@allowed).'</li>';
13460:                     } else {
13461:                         $chgtext .= &mt('none').'</li>';
13462:                     }
13463:                 }
13464:                 $chgtext .= '</ul>';
13465:                 $resulttext .= '<li>'.&mt('Authentication types available for assignment to new users').'<br />'.$chgtext;
13466:                 $resulttext .= '</li>';
13467:             }
13468:             $resulttext .= '</ul>';
13469:         } else {
13470:             $resulttext = &mt('No changes made to user creation settings');
13471:         }
13472:     } else {
13473:         $resulttext = '<span class="LC_error">'.
13474:             &mt('An error occurred: [_1]',$putresult).'</span>';
13475:     }
13476:     if ($warningmsg ne '') {
13477:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
13478:     }
13479:     return $resulttext;
13480: }
13481: 
13482: sub modify_selfcreation {
13483:     my ($dom,$lastactref,%domconfig) = @_;
13484:     my ($resulttext,$warningmsg,%curr_usercreation,%curr_usermodify,%curr_inststatus,%changes,%cancreate);
13485:     my (%save_usercreate,%save_usermodify,%save_inststatus,@types,%usertypes);
13486:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
13487:     my ($othertitle,$usertypesref,$typesref) = &Apache::loncommon::sorted_inst_types($dom);
13488:     if (ref($typesref) eq 'ARRAY') {
13489:         @types = @{$typesref};
13490:     }
13491:     if (ref($usertypesref) eq 'HASH') {
13492:         %usertypes = %{$usertypesref};
13493:     }
13494:     $usertypes{'default'} = $othertitle;
13495: #
13496: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usercreation'}.
13497: #
13498:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
13499:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
13500:             if ($key eq 'cancreate') {
13501:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
13502:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
13503:                         if (($item eq 'selfcreate') || ($item eq 'statustocreate') ||
13504:                             ($item eq 'captcha') || ($item eq 'recaptchakeys') ||
13505:                             ($item eq 'recaptchaversion') || ($item eq 'notify') ||
13506:                             ($item eq 'emailusername') || ($item eq 'shibenv') ||
13507:                             ($item eq 'selfcreateprocessing') || ($item eq 'emailverified') ||
13508:                             ($item eq 'emailoptions') || ($item eq 'emaildomain')) {
13509:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
13510:                         } else {
13511:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
13512:                         }
13513:                     }
13514:                 }
13515:             } elsif ($key eq 'email_rule') {
13516:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
13517:             } else {
13518:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
13519:             }
13520:         }
13521:     }
13522: #
13523: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usermodification'}.
13524: #
13525:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
13526:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
13527:             if ($key eq 'selfcreate') {
13528:                 $curr_usermodify{$key} = $domconfig{'usermodification'}{$key};
13529:             } else {
13530:                 $save_usermodify{$key} = $domconfig{'usermodification'}{$key};
13531:             }
13532:         }
13533:     }
13534: #
13535: # Retrieve current domain configuration for institutional status types from $domconfig{'inststatus'}.
13536: #
13537:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
13538:         foreach my $key (keys(%{$domconfig{'inststatus'}})) {
13539:             if ($key eq 'inststatusguest') {
13540:                 $curr_inststatus{$key} = $domconfig{'inststatus'}{$key};
13541:             } else {
13542:                 $save_inststatus{$key} = $domconfig{'inststatus'}{$key};
13543:             }
13544:         }
13545:     }
13546: 
13547:     my @contexts = ('selfcreate');
13548:     @{$cancreate{'selfcreate'}} = ();
13549:     %{$cancreate{'emailusername'}} = ();
13550:     if (@types) {
13551:         @{$cancreate{'statustocreate'}} = ();
13552:     }
13553:     %{$cancreate{'selfcreateprocessing'}} = ();
13554:     %{$cancreate{'shibenv'}} = ();
13555:     %{$cancreate{'emailverified'}} = ();
13556:     %{$cancreate{'emailoptions'}} = ();
13557:     %{$cancreate{'emaildomain'}} = ();
13558:     my %selfcreatetypes = (
13559:                              sso   => 'users authenticated by institutional single sign on',
13560:                              login => 'users authenticated by institutional log-in',
13561:                              email => 'users verified by e-mail',
13562:                           );
13563: #
13564: # Populate $cancreate{'selfcreate'} array reference with types of user, for which self-creation of user accounts
13565: # is permitted.
13566: #
13567: 
13568:     my ($emailrules,$emailruleorder) = &Apache::lonnet::inst_userrules($dom,'email');
13569: 
13570:     my (@statuses,%email_rule);
13571:     foreach my $item ('login','sso','email') {
13572:         if ($item eq 'email') {
13573:             if ($env{'form.cancreate_email'}) {
13574:                 if (@types) {
13575:                     my @poss_statuses = &Apache::loncommon::get_env_multiple('form.selfassign');
13576:                     foreach my $status (@poss_statuses) {
13577:                         if (grep(/^\Q$status\E$/,(@types,'default'))) {
13578:                             push(@statuses,$status);
13579:                         }
13580:                     }
13581:                     $save_inststatus{'inststatusguest'} = \@statuses;
13582:                 } else {
13583:                     push(@statuses,'default');
13584:                 }
13585:                 if (@statuses) {
13586:                     my %curr_rule;
13587:                     if (ref($curr_usercreation{'email_rule'}) eq 'ARRAY') {
13588:                         foreach my $type (@statuses) {
13589:                             $curr_rule{$type} = $curr_usercreation{'email_rule'};
13590:                         }
13591:                     } elsif (ref($curr_usercreation{'email_rule'}) eq 'HASH') {
13592:                         foreach my $type (@statuses) {
13593:                             $curr_rule{$type} = $curr_usercreation{'email_rule'}{$type};
13594:                         }
13595:                     }
13596:                     push(@{$cancreate{'selfcreate'}},'email');
13597:                     push(@contexts,('selfcreateprocessing','emailverified','emailoptions'));
13598:                     my %curremaildom;
13599:                     if (ref($curr_usercreation{'cancreate'}{'emaildomain'}) eq 'HASH') {
13600:                         %curremaildom = %{$curr_usercreation{'cancreate'}{'emaildomain'}};
13601:                     }
13602:                     foreach my $type (@statuses) {
13603:                         if ($env{'form.cancreate_emailprocess_'.$type} =~ /^(?:approval|automatic)$/) {
13604:                             $cancreate{'selfcreateprocessing'}{$type} = $env{'form.cancreate_emailprocess_'.$type};
13605:                         }
13606:                         if ($env{'form.cancreate_usernameoptions_'.$type} =~ /^(?:all|first|free)$/) {
13607:                             $cancreate{'emailverified'}{$type} = $env{'form.cancreate_usernameoptions_'.$type};
13608:                         }
13609:                         if ($env{'form.cancreate_emailoptions_'.$type} =~ /^(any|inst|noninst|custom)$/) {
13610: #
13611: # Retrieve rules (if any) governing types of e-mail address which may be used to verify a username.
13612: #
13613:                             my $chosen = $1;
13614:                             if (($chosen eq 'inst') || ($chosen eq 'noninst')) {
13615:                                 my $emaildom;
13616:                                 if ($env{'form.cancreate_emaildomain_'.$chosen.'_'.$type} =~ /^\@[^\@]+$/) {
13617:                                     $emaildom = $env{'form.cancreate_emaildomain_'.$chosen.'_'.$type};
13618:                                     $cancreate{'emaildomain'}{$type}{$chosen} = $emaildom;
13619:                                     if (ref($curremaildom{$type}) eq 'HASH') {
13620:                                         if (exists($curremaildom{$type}{$chosen})) {
13621:                                             if ($curremaildom{$type}{$chosen} ne $emaildom) {
13622:                                                 push(@{$changes{'cancreate'}},'emaildomain');
13623:                                             }
13624:                                         } elsif ($emaildom ne '') {
13625:                                             push(@{$changes{'cancreate'}},'emaildomain');
13626:                                         }
13627:                                     } elsif ($emaildom ne '') {
13628:                                         push(@{$changes{'cancreate'}},'emaildomain');
13629:                                     }
13630:                                 }
13631:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
13632:                             } elsif ($chosen eq 'custom') {
13633:                                 my @possemail_rules = &Apache::loncommon::get_env_multiple('form.email_rule_'.$type);
13634:                                 $email_rule{$type} = [];
13635:                                 if (ref($emailrules) eq 'HASH') {
13636:                                     foreach my $rule (@possemail_rules) {
13637:                                         if (exists($emailrules->{$rule})) {
13638:                                             push(@{$email_rule{$type}},$rule);
13639:                                         }
13640:                                     }
13641:                                 }
13642:                                 if (@{$email_rule{$type}}) {
13643:                                     $cancreate{'emailoptions'}{$type} = 'custom';
13644:                                     if (ref($curr_rule{$type}) eq 'ARRAY') {
13645:                                         if (@{$curr_rule{$type}} > 0) {
13646:                                             foreach my $rule (@{$curr_rule{$type}}) {
13647:                                                 if (!grep(/^\Q$rule\E$/,@{$email_rule{$type}})) {
13648:                                                     push(@{$changes{'email_rule'}},$type);
13649:                                                 }
13650:                                             }
13651:                                         }
13652:                                         foreach my $type (@{$email_rule{$type}}) {
13653:                                             if (!grep(/^\Q$type\E$/,@{$curr_rule{$type}})) {
13654:                                                 push(@{$changes{'email_rule'}},$type);
13655:                                             }
13656:                                         }
13657:                                     } else {
13658:                                         push(@{$changes{'email_rule'}},$type);
13659:                                     }
13660:                                 }
13661:                             } else {
13662:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
13663:                             }
13664:                         }
13665:                     }
13666:                     if (@types) {
13667:                         if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
13668:                             my @changed = &Apache::loncommon::compare_arrays(\@statuses,$curr_inststatus{'inststatusguest'});
13669:                             if (@changed) {
13670:                                 push(@{$changes{'inststatus'}},'inststatusguest');
13671:                             }
13672:                         } else {
13673:                             push(@{$changes{'inststatus'}},'inststatusguest');
13674:                         }
13675:                     }
13676:                 } else {
13677:                     delete($env{'form.cancreate_email'});
13678:                     if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
13679:                         if (@{$curr_inststatus{'inststatusguest'}} > 0) {
13680:                             push(@{$changes{'inststatus'}},'inststatusguest');
13681:                         }
13682:                     }
13683:                 }
13684:             } else {
13685:                 $save_inststatus{'inststatusguest'} = [];
13686:                 if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
13687:                     if (@{$curr_inststatus{'inststatusguest'}} > 0) {
13688:                         push(@{$changes{'inststatus'}},'inststatusguest');
13689:                     }
13690:                 }
13691:             }
13692:         } else {
13693:             if ($env{'form.cancreate_'.$item}) {
13694:                 push(@{$cancreate{'selfcreate'}},$item);
13695:             }
13696:         }
13697:     }
13698:     my (%userinfo,%savecaptcha);
13699:     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
13700: #
13701: # Populate $cancreate{'emailusername'}{$type} hash ref with information fields (if new user will provide data
13702: # value set to one), if self-creation with e-mail address permitted, where $type is user type: faculty, staff, student etc.
13703: #
13704: 
13705:     if ($env{'form.cancreate_email'}) {
13706:         push(@contexts,'emailusername');
13707:         if (@statuses) {
13708:             foreach my $type (@statuses) {
13709:                 if (ref($infofields) eq 'ARRAY') {
13710:                     foreach my $field (@{$infofields}) {
13711:                         if ($env{'form.canmodify_emailusername_'.$type.'_'.$field} =~ /^(required|optional)$/) {
13712:                             $cancreate{'emailusername'}{$type}{$field} = $1;
13713:                         }
13714:                     }
13715:                 }
13716:             }
13717:         }
13718: #
13719: # Populate $cancreate{'notify'} hash ref with names of Domain Coordinators who are to be notified of
13720: # queued requests for self-creation of account verified by e-mail.
13721: #
13722: 
13723:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.selfcreationnotifyapproval');
13724:         @approvalnotify = sort(@approvalnotify);
13725:         $cancreate{'notify'}{'approval'} = join(',',@approvalnotify);
13726:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
13727:             if (ref($curr_usercreation{'cancreate'}{'notify'}) eq 'HASH') {
13728:                 if ($curr_usercreation{'cancreate'}{'notify'}{'approval'} ne $cancreate{'notify'}{'approval'}) {
13729:                     push(@{$changes{'cancreate'}},'notify');
13730:                 }
13731:             } else {
13732:                 if ($cancreate{'notify'}{'approval'}) {
13733:                     push(@{$changes{'cancreate'}},'notify');
13734:                 }
13735:             }
13736:         } elsif ($cancreate{'notify'}{'approval'}) {
13737:             push(@{$changes{'cancreate'}},'notify');
13738:         }
13739: 
13740:         &process_captcha('cancreate',\%changes,\%savecaptcha,$curr_usercreation{'cancreate'});
13741:     }
13742: #  
13743: # Check if domain default is set appropriately, if self-creation of accounts is to be available for
13744: # institutional log-in.
13745: #
13746:     if (grep(/^login$/,@{$cancreate{'selfcreate'}})) {
13747:         if (!((($domdefaults{'auth_def'} =~/^krb/) && ($domdefaults{'auth_arg_def'} ne '')) || 
13748:                ($domdefaults{'auth_def'} eq 'localauth'))) {
13749:             $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.').' '.
13750:                           &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.');
13751:         }
13752:     }
13753:     my @fields = ('lastname','firstname','middlename','generation',
13754:                   'permanentemail','id');
13755:     my @shibfields = (@fields,'inststatus');
13756:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
13757: #
13758: # Where usernames may created for institutional log-in and/or institutional single sign on:
13759: # (a) populate $cancreate{'statustocreate'} array reference with institutional status types who
13760: # may self-create accounts 
13761: # (b) populate $save_usermodify{'selfcreate'} hash reference with status types, and information fields
13762: # which the user may supply, if institutional data is unavailable.
13763: #
13764:     if (($env{'form.cancreate_login'}) || ($env{'form.cancreate_sso'})) {
13765:         if (@types) {
13766:             @{$cancreate{'statustocreate'}} = &Apache::loncommon::get_env_multiple('form.statustocreate');
13767:             push(@contexts,'statustocreate');
13768:             foreach my $type (@types) {
13769:                 my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$type);
13770:                 foreach my $field (@fields) {
13771:                     if (grep(/^\Q$field\E$/,@modifiable)) {
13772:                         $save_usermodify{'selfcreate'}{$type}{$field} = 1;
13773:                     } else {
13774:                         $save_usermodify{'selfcreate'}{$type}{$field} = 0;
13775:                     }
13776:                 }
13777:             }
13778:             if (ref($curr_usermodify{'selfcreate'}) eq 'HASH') {
13779:                 foreach my $type (@types) {
13780:                     if (ref($curr_usermodify{'selfcreate'}{$type}) eq 'HASH') {
13781:                         foreach my $field (@fields) {
13782:                             if ($save_usermodify{'selfcreate'}{$type}{$field} ne
13783:                                 $curr_usermodify{'selfcreate'}{$type}{$field}) {
13784:                                 push(@{$changes{'selfcreate'}},$type);
13785:                                 last;
13786:                             }
13787:                         }
13788:                     }
13789:                 }
13790:             } else {
13791:                 foreach my $type (@types) {
13792:                     push(@{$changes{'selfcreate'}},$type);
13793:                 }
13794:             }
13795:         }
13796:         foreach my $field (@shibfields) {
13797:             if ($env{'form.shibenv_'.$field} ne '') {
13798:                 $cancreate{'shibenv'}{$field} = $env{'form.shibenv_'.$field};
13799:             }
13800:         }
13801:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
13802:             if (ref($curr_usercreation{'cancreate'}{'shibenv'}) eq 'HASH') {
13803:                 foreach my $field (@shibfields) {
13804:                     if ($env{'form.shibenv_'.$field} ne $curr_usercreation{'cancreate'}{'shibenv'}{$field}) {
13805:                         push(@{$changes{'cancreate'}},'shibenv');
13806:                     }
13807:                 }
13808:             } else {
13809:                 foreach my $field (@shibfields) {
13810:                     if ($env{'form.shibenv_'.$field}) {
13811:                         push(@{$changes{'cancreate'}},'shibenv');
13812:                         last;
13813:                     }
13814:                 }
13815:             }
13816:         }
13817:     }
13818:     foreach my $item (@contexts) {
13819:         if (ref($curr_usercreation{'cancreate'}{$item}) eq 'ARRAY') {
13820:             foreach my $curr (@{$curr_usercreation{'cancreate'}{$item}}) {
13821:                 if (ref($cancreate{$item}) eq 'ARRAY') {
13822:                     if (!grep(/^$curr$/,@{$cancreate{$item}})) {
13823:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
13824:                             push(@{$changes{'cancreate'}},$item);
13825:                         }
13826:                     }
13827:                 }
13828:             }
13829:             if (ref($cancreate{$item}) eq 'ARRAY') {
13830:                 foreach my $type (@{$cancreate{$item}}) {
13831:                     if (!grep(/^$type$/,@{$curr_usercreation{'cancreate'}{$item}})) {
13832:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
13833:                             push(@{$changes{'cancreate'}},$item);
13834:                         }
13835:                     }
13836:                 }
13837:             }
13838:         } elsif (ref($curr_usercreation{'cancreate'}{$item}) eq 'HASH') {
13839:             if (ref($cancreate{$item}) eq 'HASH') {
13840:                 foreach my $type (keys(%{$curr_usercreation{'cancreate'}{$item}})) {
13841:                     if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
13842:                         foreach my $field (keys(%{$curr_usercreation{'cancreate'}{$item}{$type}})) {
13843:                             unless ($curr_usercreation{'cancreate'}{$item}{$type}{$field} eq $cancreate{$item}{$type}{$field}) {
13844:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
13845:                                     push(@{$changes{'cancreate'}},$item);
13846:                                 }
13847:                             }
13848:                         }
13849:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
13850:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
13851:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
13852:                                 push(@{$changes{'cancreate'}},$item);
13853:                             }
13854:                         }
13855:                     }
13856:                 }
13857:                 foreach my $type (keys(%{$cancreate{$item}})) {
13858:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
13859:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
13860:                             if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
13861:                                 unless ($curr_usercreation{'cancreate'}{$item}{$type}{$field} eq $cancreate{$item}{$type}{$field}) {
13862:                                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
13863:                                         push(@{$changes{'cancreate'}},$item);
13864:                                     }
13865:                                 }
13866:                             } else {
13867:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
13868:                                     push(@{$changes{'cancreate'}},$item);
13869:                                 }
13870:                             }
13871:                         }
13872:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
13873:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
13874:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
13875:                                 push(@{$changes{'cancreate'}},$item);
13876:                             }
13877:                         }
13878:                     }
13879:                 }
13880:             }
13881:         } elsif ($curr_usercreation{'cancreate'}{$item}) {
13882:             if (ref($cancreate{$item}) eq 'ARRAY') {
13883:                 if (!grep(/^\Q$curr_usercreation{'cancreate'}{$item}\E$/,@{$cancreate{$item}})) {
13884:                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
13885:                         push(@{$changes{'cancreate'}},$item);
13886:                     }
13887:                 }
13888:             }
13889:         } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
13890:             if (ref($cancreate{$item}) eq 'HASH') {
13891:                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
13892:                     push(@{$changes{'cancreate'}},$item);
13893:                 }
13894:             }
13895:         } elsif ($item eq 'emailusername') {
13896:             if (ref($cancreate{$item}) eq 'HASH') {
13897:                 foreach my $type (keys(%{$cancreate{$item}})) {
13898:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
13899:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
13900:                             if ($cancreate{$item}{$type}{$field}) {
13901:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
13902:                                     push(@{$changes{'cancreate'}},$item);
13903:                                 }
13904:                                 last;
13905:                             }
13906:                         }
13907:                     }
13908:                 }
13909:             }
13910:         }
13911:     }
13912: #
13913: # Populate %save_usercreate hash with updates to self-creation configuration.
13914: #
13915:     $save_usercreate{'cancreate'}{'captcha'} = $savecaptcha{'captcha'};
13916:     $save_usercreate{'cancreate'}{'recaptchakeys'} = $savecaptcha{'recaptchakeys'};
13917:     $save_usercreate{'cancreate'}{'recaptchaversion'} = $savecaptcha{'recaptchaversion'};
13918:     $save_usercreate{'cancreate'}{'selfcreate'} = $cancreate{'selfcreate'};
13919:     if (ref($cancreate{'notify'}) eq 'HASH') {
13920:         $save_usercreate{'cancreate'}{'notify'} = $cancreate{'notify'};
13921:     }
13922:     if (ref($cancreate{'selfcreateprocessing'}) eq 'HASH') {
13923:         $save_usercreate{'cancreate'}{'selfcreateprocessing'} = $cancreate{'selfcreateprocessing'};
13924:     }
13925:     if (ref($cancreate{'emailverified'}) eq 'HASH') {
13926:         $save_usercreate{'cancreate'}{'emailverified'} = $cancreate{'emailverified'};
13927:     }
13928:     if (ref($cancreate{'emailoptions'}) eq 'HASH') {
13929:         $save_usercreate{'cancreate'}{'emailoptions'} = $cancreate{'emailoptions'};
13930:     }
13931:     if (ref($cancreate{'emaildomain'}) eq 'HASH') {
13932:         $save_usercreate{'cancreate'}{'emaildomain'} = $cancreate{'emaildomain'};
13933:     }
13934:     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
13935:         $save_usercreate{'cancreate'}{'statustocreate'} = $cancreate{'statustocreate'};
13936:     }
13937:     if (ref($cancreate{'shibenv'}) eq 'HASH') {
13938:         $save_usercreate{'cancreate'}{'shibenv'} = $cancreate{'shibenv'};
13939:     }
13940:     $save_usercreate{'cancreate'}{'emailusername'} = $cancreate{'emailusername'};
13941:     $save_usercreate{'email_rule'} = \%email_rule;
13942: 
13943:     my %userconfig_hash = (
13944:             usercreation     => \%save_usercreate,
13945:             usermodification => \%save_usermodify,
13946:             inststatus       => \%save_inststatus,
13947:     );
13948: 
13949:     my $putresult = &Apache::lonnet::put_dom('configuration',\%userconfig_hash,
13950:                                              $dom);
13951: #
13952: # Accumulate details of changes to domain configuration for self-creation of usernames in $resulttext
13953: #
13954:     if ($putresult eq 'ok') {
13955:         if (keys(%changes) > 0) {
13956:             $resulttext = &mt('Changes made:').'<ul>';
13957:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
13958:                 my %lt = &selfcreation_types();
13959:                 foreach my $type (@{$changes{'cancreate'}}) {
13960:                     my $chgtext = '';
13961:                     if ($type eq 'selfcreate') {
13962:                         if (@{$cancreate{$type}} == 0) {
13963:                             $chgtext .= &mt('Self creation of a new user account is not permitted.');
13964:                         } else {
13965:                             $chgtext .= &mt('Self-creation of a new account is permitted for:').
13966:                                         '<ul>';
13967:                             foreach my $case (@{$cancreate{$type}}) {
13968:                                 $chgtext .= '<li>'.$selfcreatetypes{$case}.'</li>';
13969:                             }
13970:                             $chgtext .= '</ul>';
13971:                             if (ref($cancreate{$type}) eq 'ARRAY') {
13972:                                 if (grep(/^(login|sso)$/,@{$cancreate{$type}})) {
13973:                                     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
13974:                                         if (@{$cancreate{'statustocreate'}} == 0) {
13975:                                             $chgtext .= '<span class="LC_warning">'.
13976:                                                         &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts via log-in or single sign-on.").
13977:                                                         '</span><br />';
13978:                                         }
13979:                                     }
13980:                                 }
13981:                                 if (grep(/^email$/,@{$cancreate{$type}})) {
13982:                                     if (!@statuses) {
13983:                                         $chgtext .= '<span class="LC_warning">'.
13984:                                                     &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.").
13985:                                                     '</span><br />';
13986: 
13987:                                     }
13988:                                 }
13989:                             }
13990:                         }
13991:                     } elsif ($type eq 'shibenv') {
13992:                         if (keys(%{$cancreate{$type}}) == 0) {
13993:                             $chgtext .= &mt('Shibboleth-autheticated user does not use environment variables to set user information').'<br />'; 
13994:                         } else {
13995:                             $chgtext .= &mt('Shibboleth-autheticated user information set from environment variables, as follows:').
13996:                                         '<ul>';
13997:                             foreach my $field (@shibfields) {
13998:                                 next if ($cancreate{$type}{$field} eq '');
13999:                                 if ($field eq 'inststatus') {
14000:                                     $chgtext .= '<li>'.&mt('Institutional status').' -- '.$cancreate{$type}{$field}.'</li>';
14001:                                 } else {
14002:                                     $chgtext .= '<li>'.$fieldtitles{$field}.' -- '.$cancreate{$type}{$field}.'</li>';
14003:                                 }
14004:                             }
14005:                             $chgtext .= '</ul>';
14006:                         }
14007:                     } elsif ($type eq 'statustocreate') {
14008:                         if ((ref($cancreate{'selfcreate'}) eq 'ARRAY') &&
14009:                             (ref($cancreate{'statustocreate'}) eq 'ARRAY')) {
14010:                             if (@{$cancreate{'selfcreate'}} > 0) {
14011:                                 if (@{$cancreate{'statustocreate'}} == 0) {
14012:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts set to 'None'.");
14013:                                     if (!grep(/^email$/,@{$cancreate{'selfcreate'}})) {
14014:                                         $chgtext .= '<br />'.
14015:                                                     '<span class="LC_warning">'.
14016:                                                     &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts.").
14017:                                                     '</span>';
14018:                                     }
14019:                                 } elsif (keys(%usertypes) > 0) {
14020:                                     if (grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
14021:                                         $chgtext .= &mt('Creation of a new account for an institutional user is restricted to the following institutional affiliation(s):');
14022:                                     } else {
14023:                                         $chgtext .= &mt('Institutional affiliations permitted to create accounts with institutional authentication were set as follows:');
14024:                                     }
14025:                                     $chgtext .= '<ul>';
14026:                                     foreach my $case (@{$cancreate{$type}}) {
14027:                                         if ($case eq 'default') {
14028:                                             $chgtext .= '<li>'.$othertitle.'</li>';
14029:                                         } else {
14030:                                             $chgtext .= '<li>'.$usertypes{$case}.'</li>';
14031:                                         }
14032:                                     }
14033:                                     $chgtext .= '</ul>';
14034:                                     if (!grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
14035:                                         $chgtext .= '<span class="LC_warning">'.
14036:                                                     &mt('However, users authenticated by institutional login/single sign on are not currently permitted to create accounts.').
14037:                                                     '</span>';
14038:                                     }
14039:                                 }
14040:                             } else {
14041:                                 if (@{$cancreate{$type}} == 0) {
14042:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts were set to 'none'.");
14043:                                 } else {
14044:                                     $chgtext .= &mt('Although institutional affiliations permitted to create accounts were changed, self creation of accounts is not currently permitted for any authentication types.');
14045:                                 }
14046:                             }
14047:                             $chgtext .= '<br />';
14048:                         }
14049:                     } elsif ($type eq 'selfcreateprocessing') {
14050:                         my %choices = &Apache::lonlocal::texthash (
14051:                                                                     automatic => 'Automatic approval',
14052:                                                                     approval  => 'Queued for approval',
14053:                                                                   );
14054:                         if (@types) {
14055:                             if (@statuses) {
14056:                                 $chgtext .= &mt('Processing of requests to create account with e-mail verification set as follows:').
14057:                                             '<ul>';
14058:                                 foreach my $status (@statuses) {
14059:                                     if ($status eq 'default') {
14060:                                         $chgtext .= '<li>'.$othertitle.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
14061:                                     } else {
14062:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
14063:                                     }
14064:                                 }
14065:                                 $chgtext .= '</ul>';
14066:                             }
14067:                         } else {
14068:                             $chgtext .= &mt('Processing of requests to create account with e-mail verification set to: "[_1]"',
14069:                                             $choices{$cancreate{'selfcreateprocessing'}{'default'}});
14070:                         }
14071:                     } elsif ($type eq 'emailverified') {
14072:                         my %options = &Apache::lonlocal::texthash (
14073:                                                                     all   => 'Same as e-mail',
14074:                                                                     first => 'Omit @domain',
14075:                                                                     free  => 'Free to choose',
14076:                                                                   );
14077:                         if (@types) {
14078:                             if (@statuses) {
14079:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, username is set as follows:').
14080:                                             '<ul>';
14081:                                 foreach my $status (@statuses) {
14082:                                     if ($status eq 'default') {
14083:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
14084:                                     } else {
14085:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
14086:                                     }
14087:                                 }
14088:                                 $chgtext .= '</ul>';
14089:                             }
14090:                         } else {
14091:                             $chgtext .= &mt("For self-created accounts verified by e-mail address, user's username is: '[_1]'",
14092:                                             $options{$cancreate{'emailverified'}{'default'}});
14093:                         }
14094:                     } elsif ($type eq 'emailoptions') {
14095:                         my %options = &Apache::lonlocal::texthash (
14096:                                                                     any     => 'Any e-mail',
14097:                                                                     inst    => 'Institutional only',
14098:                                                                     noninst => 'Non-institutional only',
14099:                                                                     custom  => 'Custom restrictions',
14100:                                                                   );
14101:                         if (@types) {
14102:                             if (@statuses) {
14103:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, requirements for e-mail address are as follows:').
14104:                                             '<ul>';
14105:                                 foreach my $status (@statuses) {
14106:                                     if ($type eq 'default') {
14107:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
14108:                                     } else {
14109:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
14110:                                     }
14111:                                 }
14112:                                 $chgtext .= '</ul>';
14113:                             }
14114:                         } else {
14115:                             if ($cancreate{'emailoptions'}{'default'} eq 'any') {
14116:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, any e-mail may be used');
14117:                             } else {
14118:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, e-mail restricted to: "[_1]"',
14119:                                                 $options{$cancreate{'emailoptions'}{'default'}});
14120:                             }
14121:                         }
14122:                     } elsif ($type eq 'emaildomain') {
14123:                         my $output;
14124:                         if (@statuses) {
14125:                             foreach my $type (@statuses) {
14126:                                 if (ref($cancreate{'emaildomain'}{$type}) eq 'HASH') {
14127:                                     if ($cancreate{'emailoptions'}{$type} eq 'inst') {
14128:                                         if ($type eq 'default') {
14129:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
14130:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} eq '')) {
14131:                                                 $output = '<li>'.$othertitle.' -- '.&mt('No restriction on e-mail domain').'</li>';
14132:                                             } else {
14133:                                                 $output = '<li>'.$othertitle.' -- '.&mt("User's e-mail address needs to end: [_1]",
14134:                                                                                         $cancreate{'emaildomain'}{$type}{'inst'}).'</li>';
14135:                                             }
14136:                                         } else {
14137:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
14138:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} eq '')) {
14139:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
14140:                                             } else {
14141:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address needs to end: [_1]",
14142:                                                                                               $cancreate{'emaildomain'}{$type}{'inst'}).'</li>';
14143:                                             }
14144:                                         }
14145:                                     } elsif ($cancreate{'emailoptions'}{$type} eq 'noninst') {
14146:                                         if ($type eq 'default') {
14147:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
14148:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
14149:                                                 $output = '<li>'.$othertitle.' -- '.&mt('No restriction on e-mail domain').'</li>';
14150:                                             } else {
14151:                                                 $output = '<li>'.$othertitle.' -- '.&mt("User's e-mail address must not end: [_1]",
14152:                                                                                         $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';
14153:                                             }
14154:                                         } else {
14155:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
14156:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
14157:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
14158:                                             } else {
14159:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address must not end: [_1]",
14160:                                                                                                 $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';
14161:                                             }
14162:                                         }
14163:                                     }
14164:                                 }
14165:                             }
14166:                         }
14167:                         if ($output ne '') {
14168:                             $chgtext .= &mt('For self-created accounts verified by e-mail address:').
14169:                                         '<ul>'.$output.'</ul>';
14170:                         }
14171:                     } elsif ($type eq 'captcha') {
14172:                         if ($savecaptcha{$type} eq 'notused') {
14173:                             $chgtext .= &mt('No CAPTCHA validation in use for self-creation screen.');
14174:                         } else {
14175:                             my %captchas = &captcha_phrases();
14176:                             if ($captchas{$savecaptcha{$type}}) {
14177:                                 $chgtext .= &mt("Validation for self-creation screen set to $captchas{$savecaptcha{$type}}.");
14178:                             } else {
14179:                                 $chgtext .= &mt('Validation for self-creation screen set to unknown type.');
14180:                             }
14181:                         }
14182:                     } elsif ($type eq 'recaptchakeys') {
14183:                         my ($privkey,$pubkey);
14184:                         if (ref($savecaptcha{$type}) eq 'HASH') {
14185:                             $pubkey = $savecaptcha{$type}{'public'};
14186:                             $privkey = $savecaptcha{$type}{'private'};
14187:                         }
14188:                         $chgtext .= &mt('ReCAPTCHA keys changes').'<ul>';
14189:                         if (!$pubkey) {
14190:                             $chgtext .= '<li>'.&mt('Public key deleted').'</li>';
14191:                         } else {
14192:                             $chgtext .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
14193:                         }
14194:                         if (!$privkey) {
14195:                             $chgtext .= '<li>'.&mt('Private key deleted').'</li>';
14196:                         } else {
14197:                             $chgtext .= '<li>'.&mt('Private key set to [_1]',$pubkey).'</li>';
14198:                         }
14199:                         $chgtext .= '</ul>';
14200:                     } elsif ($type eq 'recaptchaversion') {
14201:                         if ($savecaptcha{'captcha'} eq 'recaptcha') {
14202:                             $chgtext .= &mt('ReCAPTCHA set to version [_1]',$savecaptcha{$type});
14203:                         }
14204:                     } elsif ($type eq 'emailusername') {
14205:                         if (ref($cancreate{'emailusername'}) eq 'HASH') {
14206:                             if (@statuses) {
14207:                                 foreach my $type (@statuses) {
14208:                                     if (ref($cancreate{'emailusername'}{$type}) eq 'HASH') {
14209:                                         if (keys(%{$cancreate{'emailusername'}{$type}}) > 0) {
14210:                                             $chgtext .= &mt('When self-creating account with e-mail verification, the following information will be provided by [_1]:',"'$usertypes{$type}'").
14211:                                                     '<ul>';
14212:                                             foreach my $field (@{$infofields}) {
14213:                                                 if ($cancreate{'emailusername'}{$type}{$field}) {
14214:                                                     $chgtext .= '<li>'.$infotitles->{$field}.'</li>';
14215:                                                 }
14216:                                             }
14217:                                             $chgtext .= '</ul>';
14218:                                         } else {
14219:                                             $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
14220:                                         }
14221:                                     } else {
14222:                                         $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
14223:                                     }
14224:                                 }
14225:                             }
14226:                         }
14227:                     } elsif ($type eq 'notify') {
14228:                         my $numapprove = 0;
14229:                         if (ref($changes{'cancreate'}) eq 'ARRAY') {
14230:                             if ((grep(/^notify$/,@{$changes{'cancreate'}})) && (ref($cancreate{'notify'}) eq 'HASH')) {
14231:                                 if ($cancreate{'notify'}{'approval'}) {
14232:                                     $chgtext .= &mt('Notification of username requests requiring approval will be sent to: ').$cancreate{'notify'}{'approval'};
14233:                                     $numapprove ++;
14234:                                 }
14235:                             }
14236:                         }
14237:                         unless ($numapprove) {
14238:                             $chgtext .= &mt('No Domain Coordinators will receive notification of username requests requiring approval.');
14239:                         }
14240:                     }
14241:                     if ($chgtext) {
14242:                         $resulttext .= '<li>'.$chgtext.'</li>';
14243:                     }
14244:                 }
14245:             }
14246:             if ((ref($changes{'email_rule'}) eq 'ARRAY') && (@{$changes{'email_rule'}} > 0)) {
14247:                 my ($emailrules,$emailruleorder) =
14248:                     &Apache::lonnet::inst_userrules($dom,'email');
14249:                 foreach my $type (@{$changes{'email_rule'}}) {
14250:                     if (ref($email_rule{$type}) eq 'ARRAY') {
14251:                         my $chgtext = '<ul>';
14252:                         foreach my $rule (@{$email_rule{$type}}) {
14253:                             if (ref($emailrules->{$rule}) eq 'HASH') {
14254:                                 $chgtext .= '<li>'.$emailrules->{$rule}{'name'}.'</li>';
14255:                             }
14256:                         }
14257:                         $chgtext .= '</ul>';
14258:                         my $typename;
14259:                         if (@types) {
14260:                             if ($type eq 'default') {
14261:                                 $typename = $othertitle;
14262:                             } else {
14263:                                 $typename = $usertypes{$type};
14264:                             }
14265:                             $chgtext .= &mt('(Affiliation: [_1])',$typename);
14266:                         }
14267:                         if (@{$email_rule{$type}} > 0) {
14268:                             $resulttext .= '<li>'.
14269:                                            &mt('Accounts may not be created by users verified by e-mail, for e-mail addresses of the following types: ',
14270:                                                $usertypes{$type}).
14271:                                            $chgtext.
14272:                                            '</li>';
14273:                         } else {
14274:                             $resulttext .= '<li>'.
14275:                                            &mt('There are now no restrictions on e-mail addresses which may be used for verification when a user requests an account.').
14276:                                            '</li>'.
14277:                                            &mt('(Affiliation: [_1])',$typename);
14278:                         }
14279:                     }
14280:                 }
14281:             }
14282:             if (ref($changes{'inststatus'}) eq 'ARRAY') {
14283:                 if (ref($save_inststatus{'inststatusguest'}) eq 'ARRAY') {
14284:                     if (@{$save_inststatus{'inststatusguest'}} > 0) {
14285:                         my $chgtext = '<ul>';
14286:                         foreach my $type (@{$save_inststatus{'inststatusguest'}}) {
14287:                             $chgtext .= '<li>'.$usertypes{$type}.'</li>';
14288:                         }
14289:                         $chgtext .= '</ul>';
14290:                         $resulttext .= '<li>'.
14291:                                        &mt('A user will self-report one of the following affiliations when requesting an account verified by e-mail: ').
14292:                                           $chgtext.
14293:                                        '</li>';
14294:                     } else {
14295:                         $resulttext .= '<li>'.
14296:                                        &mt('No affiliations available for self-reporting when requesting an account verified by e-mail.').
14297:                                        '</li>';
14298:                     }
14299:                 }
14300:             }
14301:             if (ref($changes{'selfcreate'}) eq 'ARRAY') {
14302:                 $resulttext .= '<li>'.&mt('When self-creating institutional account:').'<ul>';
14303:                 my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
14304:                 foreach my $type (@{$changes{'selfcreate'}}) {
14305:                     my $typename = $type;
14306:                     if (keys(%usertypes) > 0) {
14307:                         if ($usertypes{$type} ne '') {
14308:                             $typename = $usertypes{$type};
14309:                         }
14310:                     }
14311:                     my @modifiable;
14312:                     $resulttext .= '<li>'.
14313:                                     &mt('Self-creation of account by users with status: [_1]',
14314:                                         '<span class="LC_cusr_emph">'.$typename.'</span>').
14315:                                     ' - '.&mt('modifiable fields (if institutional data blank): ');
14316:                     foreach my $field (@fields) {
14317:                         if ($save_usermodify{'selfcreate'}{$type}{$field}) {
14318:                             push(@modifiable,'<b>'.$fieldtitles{$field}.'</b>');
14319:                         }
14320:                     }
14321:                     if (@modifiable > 0) {
14322:                         $resulttext .= join(', ',@modifiable);
14323:                     } else {
14324:                         $resulttext .= &mt('none');
14325:                     }
14326:                     $resulttext .= '</li>';
14327:                 }
14328:                 $resulttext .= '</ul></li>';
14329:             }
14330:             $resulttext .= '</ul>';
14331:             my $cachetime = 24*60*60;
14332:             $domdefaults{'inststatusguest'} = $save_inststatus{'inststatusguest'};
14333:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
14334:             if (ref($lastactref) eq 'HASH') {
14335:                 $lastactref->{'domdefaults'} = 1;
14336:             }
14337:         } else {
14338:             $resulttext = &mt('No changes made to self-creation settings');
14339:         }
14340:     } else {
14341:         $resulttext = '<span class="LC_error">'.
14342:             &mt('An error occurred: [_1]',$putresult).'</span>';
14343:     }
14344:     if ($warningmsg ne '') {
14345:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
14346:     }
14347:     return $resulttext;
14348: }
14349: 
14350: sub process_captcha {
14351:     my ($container,$changes,$newsettings,$currsettings) = @_;
14352:     return unless ((ref($changes) eq 'HASH') && (ref($newsettings) eq 'HASH'));
14353:     $newsettings->{'captcha'} = $env{'form.'.$container.'_captcha'};
14354:     unless ($newsettings->{'captcha'} eq 'recaptcha' || $newsettings->{'captcha'} eq 'notused') {
14355:         $newsettings->{'captcha'} = 'original';
14356:     }
14357:     my %current;
14358:     if (ref($currsettings) eq 'HASH') {
14359:         %current = %{$currsettings};
14360:     }
14361:     if ($current{'captcha'} ne $newsettings->{'captcha'}) {
14362:         if ($container eq 'cancreate') {
14363:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
14364:                 push(@{$changes->{'cancreate'}},'captcha');
14365:             } elsif (!defined($changes->{'cancreate'})) {
14366:                 $changes->{'cancreate'} = ['captcha'];
14367:             }
14368:         } elsif ($container eq 'passwords') {
14369:             $changes->{'reset'} = 1;
14370:         } else {
14371:             $changes->{'captcha'} = 1;
14372:         }
14373:     }
14374:     my ($newpub,$newpriv,$currpub,$currpriv,$newversion,$currversion);
14375:     if ($newsettings->{'captcha'} eq 'recaptcha') {
14376:         $newpub = $env{'form.'.$container.'_recaptchapub'};
14377:         $newpriv = $env{'form.'.$container.'_recaptchapriv'};
14378:         $newpub =~ s/[^\w\-]//g;
14379:         $newpriv =~ s/[^\w\-]//g;
14380:         $newsettings->{'recaptchakeys'} = {
14381:                                              public  => $newpub,
14382:                                              private => $newpriv,
14383:                                           };
14384:         $newversion = $env{'form.'.$container.'_recaptchaversion'};
14385:         $newversion =~ s/\D//g;
14386:         if ($newversion ne '2') {
14387:             $newversion = 1;
14388:         }
14389:         $newsettings->{'recaptchaversion'} = $newversion;
14390:     }
14391:     if (ref($current{'recaptchakeys'}) eq 'HASH') {
14392:         $currpub = $current{'recaptchakeys'}{'public'};
14393:         $currpriv = $current{'recaptchakeys'}{'private'};
14394:         unless ($newsettings->{'captcha'} eq 'recaptcha') {
14395:             $newsettings->{'recaptchakeys'} = {
14396:                                                  public  => '',
14397:                                                  private => '',
14398:                                               }
14399:         }
14400:     }
14401:     if ($current{'captcha'} eq 'recaptcha') {
14402:         $currversion = $current{'recaptchaversion'};
14403:         if ($currversion ne '2') {
14404:             $currversion = 1;
14405:         }
14406:     }
14407:     if ($currversion ne $newversion) {
14408:         if ($container eq 'cancreate') {
14409:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
14410:                 push(@{$changes->{'cancreate'}},'recaptchaversion');
14411:             } elsif (!defined($changes->{'cancreate'})) {
14412:                 $changes->{'cancreate'} = ['recaptchaversion'];
14413:             }
14414:         } elsif ($container eq 'passwords') {
14415:             $changes->{'reset'} = 1;
14416:         } else {
14417:             $changes->{'recaptchaversion'} = 1;
14418:         }
14419:     }
14420:     if (($newpub ne $currpub) || ($newpriv ne $currpriv)) {
14421:         if ($container eq 'cancreate') {
14422:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
14423:                 push(@{$changes->{'cancreate'}},'recaptchakeys');
14424:             } elsif (!defined($changes->{'cancreate'})) {
14425:                 $changes->{'cancreate'} = ['recaptchakeys'];
14426:             }
14427:         } elsif ($container eq 'passwords') {
14428:             $changes->{'reset'} = 1;
14429:         } else {
14430:             $changes->{'recaptchakeys'} = 1;
14431:         }
14432:     }
14433:     return;
14434: }
14435: 
14436: sub modify_usermodification {
14437:     my ($dom,%domconfig) = @_;
14438:     my ($resulttext,%curr_usermodification,%changes,%modifyhash);
14439:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
14440:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
14441:             if ($key eq 'selfcreate') {
14442:                 $modifyhash{$key} = $domconfig{'usermodification'}{$key};
14443:             } else {  
14444:                 $curr_usermodification{$key} = $domconfig{'usermodification'}{$key};
14445:             }
14446:         }
14447:     }
14448:     my @contexts = ('author','course');
14449:     my %context_title = (
14450:                            author => 'In author context',
14451:                            course => 'In course context',
14452:                         );
14453:     my @fields = ('lastname','firstname','middlename','generation',
14454:                   'permanentemail','id');
14455:     my %roles = (
14456:                   author => ['ca','aa'],
14457:                   course => ['st','ep','ta','in','cr'],
14458:                 );
14459:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
14460:     foreach my $context (@contexts) {
14461:         foreach my $role (@{$roles{$context}}) {
14462:             my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$role);
14463:             foreach my $item (@fields) {
14464:                 if (grep(/^\Q$item\E$/,@modifiable)) {
14465:                     $modifyhash{$context}{$role}{$item} = 1;
14466:                 } else {
14467:                     $modifyhash{$context}{$role}{$item} = 0;
14468:                 }
14469:             }
14470:         }
14471:         if (ref($curr_usermodification{$context}) eq 'HASH') {
14472:             foreach my $role (@{$roles{$context}}) {
14473:                 if (ref($curr_usermodification{$context}{$role}) eq 'HASH') {
14474:                     foreach my $field (@fields) {
14475:                         if ($modifyhash{$context}{$role}{$field} ne 
14476:                                 $curr_usermodification{$context}{$role}{$field}) {
14477:                             push(@{$changes{$context}},$role);
14478:                             last;
14479:                         }
14480:                     }
14481:                 }
14482:             }
14483:         } else {
14484:             foreach my $context (@contexts) {
14485:                 foreach my $role (@{$roles{$context}}) {
14486:                     push(@{$changes{$context}},$role);
14487:                 }
14488:             }
14489:         }
14490:     }
14491:     my %usermodification_hash =  (
14492:                                    usermodification => \%modifyhash,
14493:                                  );
14494:     my $putresult = &Apache::lonnet::put_dom('configuration',
14495:                                              \%usermodification_hash,$dom);
14496:     if ($putresult eq 'ok') {
14497:         if (keys(%changes) > 0) {
14498:             $resulttext = &mt('Changes made: ').'<ul>';
14499:             foreach my $context (@contexts) {
14500:                 if (ref($changes{$context}) eq 'ARRAY') {
14501:                     $resulttext .= '<li>'.$context_title{$context}.':<ul>';
14502:                     if (ref($changes{$context}) eq 'ARRAY') {
14503:                         foreach my $role (@{$changes{$context}}) {
14504:                             my $rolename;
14505:                             if ($role eq 'cr') {
14506:                                 $rolename = &mt('Custom');
14507:                             } else {
14508:                                 $rolename = &Apache::lonnet::plaintext($role);
14509:                             }
14510:                             my @modifiable;
14511:                             $resulttext .= '<li><span class="LC_cusr_emph">'.&mt('Target user with [_1] role',$rolename).'</span> - '.&mt('modifiable fields: ');
14512:                             foreach my $field (@fields) {
14513:                                 if ($modifyhash{$context}{$role}{$field}) {
14514:                                     push(@modifiable,$fieldtitles{$field});
14515:                                 }
14516:                             }
14517:                             if (@modifiable > 0) {
14518:                                 $resulttext .= join(', ',@modifiable);
14519:                             } else {
14520:                                 $resulttext .= &mt('none'); 
14521:                             }
14522:                             $resulttext .= '</li>';
14523:                         }
14524:                         $resulttext .= '</ul></li>';
14525:                     }
14526:                 }
14527:             }
14528:             $resulttext .= '</ul>';
14529:         } else {
14530:             $resulttext = &mt('No changes made to user modification settings');
14531:         }
14532:     } else {
14533:         $resulttext = '<span class="LC_error">'.
14534:             &mt('An error occurred: [_1]',$putresult).'</span>';
14535:     }
14536:     return $resulttext;
14537: }
14538: 
14539: sub modify_defaults {
14540:     my ($dom,$lastactref,%domconfig) = @_;
14541:     my ($resulttext,$mailmsgtxt,%newvalues,%changes,@errors);
14542:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
14543:     my @items = ('auth_def','auth_arg_def','lang_def','timezone_def','datelocale_def',
14544:                  'portal_def');
14545:     my @authtypes = ('internal','krb4','krb5','localauth');
14546:     foreach my $item (@items) {
14547:         $newvalues{$item} = $env{'form.'.$item};
14548:         if ($item eq 'auth_def') {
14549:             if ($newvalues{$item} ne '') {
14550:                 if (!grep(/^\Q$newvalues{$item}\E$/,@authtypes)) {
14551:                     push(@errors,$item);
14552:                 }
14553:             }
14554:         } elsif ($item eq 'lang_def') {
14555:             if ($newvalues{$item} ne '') {
14556:                 if ($newvalues{$item} =~ /^(\w+)/) {
14557:                     my $langcode = $1;
14558:                     if ($langcode ne 'x_chef') {
14559:                         if (code2language($langcode) eq '') {
14560:                             push(@errors,$item);
14561:                         }
14562:                     }
14563:                 } else {
14564:                     push(@errors,$item);
14565:                 }
14566:             }
14567:         } elsif ($item eq 'timezone_def') {
14568:             if ($newvalues{$item} ne '') {
14569:                 if (!DateTime::TimeZone->is_valid_name($newvalues{$item})) {
14570:                     push(@errors,$item);   
14571:                 }
14572:             }
14573:         } elsif ($item eq 'datelocale_def') {
14574:             if ($newvalues{$item} ne '') {
14575:                 my @datelocale_ids = DateTime::Locale->ids();
14576:                 if (!grep(/^\Q$newvalues{$item}\E$/,@datelocale_ids)) {
14577:                     push(@errors,$item);
14578:                 }
14579:             }
14580:         } elsif ($item eq 'portal_def') {
14581:             if ($newvalues{$item} ne '') {
14582:                 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])\/?$/) {
14583:                     push(@errors,$item);
14584:                 }
14585:             }
14586:         }
14587:         if (grep(/^\Q$item\E$/,@errors)) {
14588:             $newvalues{$item} = $domdefaults{$item};
14589:         } elsif ($domdefaults{$item} ne $newvalues{$item}) {
14590:             $changes{$item} = 1;
14591:         }
14592:         $domdefaults{$item} = $newvalues{$item};
14593:     }
14594:     my %staticdefaults = (
14595:                            'intauth_cost'   => 10,
14596:                            'intauth_check'  => 0,
14597:                            'intauth_switch' => 0,
14598:                          );
14599:     foreach my $item ('intauth_cost','intauth_check','intauth_switch') {
14600:         if (exists($domdefaults{$item})) {
14601:             $newvalues{$item} = $domdefaults{$item};
14602:         } else {
14603:             $newvalues{$item} = $staticdefaults{$item};
14604:         }
14605:     }
14606:     my ($unamemaprules,$ruleorder);
14607:     my @possunamemaprules = &Apache::loncommon::get_env_multiple('form.unamemap_rule');
14608:     if (@possunamemaprules) {
14609:         ($unamemaprules,$ruleorder) =
14610:             &Apache::lonnet::inst_userrules($dom,'unamemap');
14611:         if ((ref($unamemaprules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
14612:             if (@{$ruleorder} > 0) {
14613:                 my %possrules;
14614:                 map { $possrules{$_} = 1; } @possunamemaprules;
14615:                 foreach my $rule (@{$ruleorder}) {
14616:                     if ($possrules{$rule}) {
14617:                         push(@{$newvalues{'unamemap_rule'}},$rule);
14618:                     }
14619:                 }
14620:             }
14621:         }
14622:     }
14623:     if (ref($domdefaults{'unamemap_rule'}) eq 'ARRAY') {
14624:         if (ref($newvalues{'unamemap_rule'}) eq 'ARRAY') {
14625:             my @rulediffs = &Apache::loncommon::compare_arrays($domdefaults{'unamemap_rule'},
14626:                                                                $newvalues{'unamemap_rule'});
14627:             if (@rulediffs) {
14628:                 $changes{'unamemap_rule'} = 1;
14629:                 $domdefaults{'unamemap_rule'} = $newvalues{'unamemap_rule'};
14630:             }
14631:         } elsif (@{$domdefaults{'unamemap_rule'}} > 0) {
14632:             $changes{'unamemap_rule'} = 1;
14633:             delete($domdefaults{'unamemap_rule'});
14634:         }
14635:     } elsif (ref($newvalues{'unamemap_rule'}) eq 'ARRAY') {
14636:         if (@{$newvalues{'unamemap_rule'}} > 0) {
14637:             $changes{'unamemap_rule'} = 1;
14638:             $domdefaults{'unamemap_rule'} = $newvalues{'unamemap_rule'};
14639:         }
14640:     }
14641:     my %defaults_hash = (
14642:                          defaults => \%newvalues,
14643:                         );
14644:     my $title = &defaults_titles();
14645: 
14646:     my $currinststatus;
14647:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
14648:         $currinststatus = $domconfig{'inststatus'};
14649:     } else {
14650:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
14651:         $currinststatus = {
14652:                              inststatustypes => $usertypes,
14653:                              inststatusorder => $types,
14654:                              inststatusguest => [],
14655:                           };
14656:     }
14657:     my @todelete = &Apache::loncommon::get_env_multiple('form.inststatus_delete');
14658:     my @allpos;
14659:     my %alltypes;
14660:     my @inststatusguest;
14661:     if (ref($currinststatus) eq 'HASH') {
14662:         if (ref($currinststatus->{'inststatusguest'}) eq 'ARRAY') {
14663:             foreach my $type (@{$currinststatus->{'inststatusguest'}}) {
14664:                 unless (grep(/^\Q$type\E$/,@todelete)) {
14665:                     push(@inststatusguest,$type);
14666:                 }
14667:             }
14668:         }
14669:     }
14670:     my ($currtitles,$currorder);
14671:     if (ref($currinststatus) eq 'HASH') {
14672:         if (ref($currinststatus->{'inststatusorder'}) eq 'ARRAY') {
14673:             foreach my $type (@{$currinststatus->{'inststatusorder'}}) {
14674:                 if (ref($currinststatus->{inststatustypes}) eq 'HASH') {
14675:                     if ($currinststatus->{inststatustypes}->{$type} ne '') {
14676:                         $currtitles .= $currinststatus->{inststatustypes}->{$type}.',';
14677:                     }
14678:                 }
14679:                 unless (grep(/^\Q$type\E$/,@todelete)) { 
14680:                     my $position = $env{'form.inststatus_pos_'.$type};
14681:                     $position =~ s/\D+//g;
14682:                     $allpos[$position] = $type;
14683:                     $alltypes{$type} = $env{'form.inststatus_title_'.$type};
14684:                     $alltypes{$type} =~ s/`//g;
14685:                 }
14686:             }
14687:             $currorder = join(',',@{$currinststatus->{'inststatusorder'}});
14688:             $currtitles =~ s/,$//;
14689:         }
14690:     }
14691:     if ($env{'form.addinststatus'}) {
14692:         my $newtype = $env{'form.addinststatus'};
14693:         $newtype =~ s/\W//g;
14694:         unless (exists($alltypes{$newtype})) {
14695:             $alltypes{$newtype} = $env{'form.addinststatus_title'};
14696:             $alltypes{$newtype} =~ s/`//g; 
14697:             my $position = $env{'form.addinststatus_pos'};
14698:             $position =~ s/\D+//g;
14699:             if ($position ne '') {
14700:                 $allpos[$position] = $newtype;
14701:             }
14702:         }
14703:     }
14704:     my @orderedstatus;
14705:     foreach my $type (@allpos) {
14706:         unless (($type eq '') || (grep(/^\Q$type\E$/,@orderedstatus))) {
14707:             push(@orderedstatus,$type);
14708:         }
14709:     }
14710:     foreach my $type (keys(%alltypes)) {
14711:         unless (grep(/^\Q$type\E$/,@orderedstatus)) {
14712:             delete($alltypes{$type});
14713:         }
14714:     }
14715:     $defaults_hash{'inststatus'} = {
14716:                                      inststatustypes => \%alltypes,
14717:                                      inststatusorder => \@orderedstatus,
14718:                                      inststatusguest => \@inststatusguest,
14719:                                    };
14720:     if (ref($defaults_hash{'inststatus'}) eq 'HASH') {
14721:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
14722:             $domdefaults{$item} = $defaults_hash{'inststatus'}{$item};
14723:         }
14724:     }
14725:     if ($currorder ne join(',',@orderedstatus)) {
14726:         $changes{'inststatus'}{'inststatusorder'} = 1;
14727:     }
14728:     my $newtitles;
14729:     foreach my $item (@orderedstatus) {
14730:         $newtitles .= $alltypes{$item}.',';
14731:     }
14732:     $newtitles =~ s/,$//;
14733:     if ($currtitles ne $newtitles) {
14734:         $changes{'inststatus'}{'inststatustypes'} = 1;
14735:     }
14736:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaults_hash,
14737:                                              $dom);
14738:     if ($putresult eq 'ok') {
14739:         if (keys(%changes) > 0) {
14740:             $resulttext = &mt('Changes made:').'<ul>';
14741:             my $version = &Apache::lonnet::get_server_loncaparev($dom);
14742:             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";
14743:             foreach my $item (sort(keys(%changes))) {
14744:                 if ($item eq 'inststatus') {
14745:                     if (ref($changes{'inststatus'}) eq 'HASH') {
14746:                         if (@orderedstatus) {
14747:                             $resulttext .= '<li>'.&mt('Institutional user status types set to:').' ';
14748:                             foreach my $type (@orderedstatus) { 
14749:                                 $resulttext .= $alltypes{$type}.', ';
14750:                             }
14751:                             $resulttext =~ s/, $//;
14752:                             $resulttext .= '</li>';
14753:                         } else {
14754:                             $resulttext .= '<li>'.&mt('Institutional user status types deleted').'</li>';
14755:                         }
14756:                     }
14757:                 } elsif ($item eq 'unamemap_rule') {
14758:                     if (ref($newvalues{'unamemap_rule'}) eq 'ARRAY') {
14759:                         my @rulenames;
14760:                         if (ref($unamemaprules) eq 'HASH') {
14761:                             foreach my $rule (@{$newvalues{'unamemap_rule'}}) {
14762:                                 if (ref($unamemaprules->{$rule}) eq 'HASH') {
14763:                                     push(@rulenames,$unamemaprules->{$rule}->{'name'});
14764:                                 }
14765:                             }
14766:                         }
14767:                         if (@rulenames) {
14768:                             $resulttext .= '<li>'.&mt('Mapping for missing usernames includes: [_1]',
14769:                                                      '<ul><li>'.join('</li><li>',@rulenames).'</li></ul>').
14770:                                            '</li>';
14771:                         } else {
14772:                             $resulttext .= '<li>'.&mt('No mapping for missing usernames via standard log-in').'</li>';
14773:                         }
14774:                     } else {
14775:                         $resulttext .= '<li>'.&mt('Mapping for missing usernames via standard log-in deleted').'</li>';
14776:                     }
14777:                 } else {
14778:                     my $value = $env{'form.'.$item};
14779:                     if ($value eq '') {
14780:                         $value = &mt('none');
14781:                     } elsif ($item eq 'auth_def') {
14782:                         my %authnames = &authtype_names();
14783:                         my %shortauth = (
14784:                                           internal   => 'int',
14785:                                           krb4       => 'krb4',
14786:                                           krb5       => 'krb5',
14787:                                           localauth  => 'loc',
14788:                         );
14789:                         $value = $authnames{$shortauth{$value}};
14790:                     }
14791:                     $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$title->{$item},$value).'</li>';
14792:                     $mailmsgtext .= "$title->{$item} set to $value\n";  
14793:                 }
14794:             }
14795:             $resulttext .= '</ul>';
14796:             $mailmsgtext .= "\n";
14797:             my $cachetime = 24*60*60;
14798:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
14799:             if (ref($lastactref) eq 'HASH') {
14800:                 $lastactref->{'domdefaults'} = 1;
14801:             }
14802:             if ($changes{'auth_def'} || $changes{'auth_arg_def'} || $changes{'lang_def'} || $changes{'datelocale_def'}) {
14803:                 my $notify = 1;
14804:                 if (ref($domconfig{'contacts'}) eq 'HASH') {
14805:                     if ($domconfig{'contacts'}{'reportupdates'} == 0) {
14806:                         $notify = 0;
14807:                     }
14808:                 }
14809:                 if ($notify) {
14810:                     &Apache::lonmsg::sendemail('installrecord@loncapa.org',
14811:                                                "LON-CAPA Domain Settings Change - $dom",
14812:                                                $mailmsgtext);
14813:                 }
14814:             }
14815:         } else {
14816:             $resulttext = &mt('No changes made to default authentication/language/timezone settings');
14817:         }
14818:     } else {
14819:         $resulttext = '<span class="LC_error">'.
14820:             &mt('An error occurred: [_1]',$putresult).'</span>';
14821:     }
14822:     if (@errors > 0) {
14823:         $resulttext .= '<br />'.&mt('The following were left unchanged because the values entered were invalid:');
14824:         foreach my $item (@errors) {
14825:             $resulttext .= ' "'.$title->{$item}.'",';
14826:         }
14827:         $resulttext =~ s/,$//;
14828:     }
14829:     return $resulttext;
14830: }
14831: 
14832: sub modify_scantron {
14833:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
14834:     my ($resulttext,%confhash,%changes,$errors);
14835:     my $custom = 'custom.tab';
14836:     my $default = 'default.tab';
14837:     my $servadm = $r->dir_config('lonAdmEMail');
14838:     my ($configuserok,$author_ok,$switchserver) =
14839:         &config_check($dom,$confname,$servadm);
14840:     if ($env{'form.scantronformat.filename'} ne '') {
14841:         my $error;
14842:         if ($configuserok eq 'ok') {
14843:             if ($switchserver) {
14844:                 $error = &mt("Upload of bubblesheet format file is not permitted to this server: [_1]",$switchserver);
14845:             } else {
14846:                 if ($author_ok eq 'ok') {
14847:                     my ($result,$scantronurl) =
14848:                         &publishlogo($r,'upload','scantronformat',$dom,
14849:                                      $confname,'scantron','','',$custom);
14850:                     if ($result eq 'ok') {
14851:                         $confhash{'scantron'}{'scantronformat'} = $scantronurl;
14852:                         $changes{'scantronformat'} = 1;
14853:                     } else {
14854:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$custom,$result);
14855:                     }
14856:                 } else {
14857:                     $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);
14858:                 }
14859:             }
14860:         } else {
14861:             $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);
14862:         }
14863:         if ($error) {
14864:             &Apache::lonnet::logthis($error);
14865:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
14866:         }
14867:     }
14868:     if (ref($domconfig{'scantron'}) eq 'HASH') {
14869:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
14870:             if ($env{'form.scantronformat_del'}) {
14871:                 $confhash{'scantron'}{'scantronformat'} = '';
14872:                 $changes{'scantronformat'} = 1;
14873:             } else {
14874:                 $confhash{'scantron'}{'scantronformat'} = $domconfig{'scantron'}{'scantronformat'};
14875:             }
14876:         }
14877:     }
14878:     my @options = ('hdr','pad','rem');
14879:     my @fields = &scantroncsv_fields();
14880:     my %titles = &scantronconfig_titles();
14881:     my @formats = &Apache::loncommon::get_env_multiple('form.scantronconfig');
14882:     my ($newdat,$currdat,%newcol,%currcol);
14883:     if (grep(/^dat$/,@formats)) {
14884:         $confhash{'scantron'}{config}{dat} = 1;
14885:         $newdat = 1;
14886:     } else {
14887:         $newdat = 0;
14888:     }
14889:     if (grep(/^csv$/,@formats)) {
14890:         my %bynum;
14891:         foreach my $field (@fields) {
14892:             if ($env{'form.scantronconfig_csv_'.$field} =~ /^(\d+)$/) {
14893:                 my $posscol = $1;
14894:                 if (($posscol < 20) && (!$bynum{$posscol})) {
14895:                     $confhash{'scantron'}{config}{csv}{fields}{$field} = $posscol;
14896:                     $bynum{$posscol} = $field;
14897:                     $newcol{$field} = $posscol;
14898:                 }
14899:             }
14900:         }
14901:         if (keys(%newcol)) {
14902:             foreach my $option (@options) {
14903:                 if ($env{'form.scantroncsv_'.$option}) {
14904:                     $confhash{'scantron'}{config}{csv}{options}{$option} = 1;
14905:                 }
14906:             }
14907:         }
14908:     }
14909:     $currdat = 1;
14910:     if (ref($domconfig{'scantron'}) eq 'HASH') {
14911:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
14912:             unless (exists($domconfig{'scantron'}{'config'}{'dat'})) {
14913:                 $currdat = 0;
14914:             }
14915:             if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
14916:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
14917:                     %currcol = %{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}};
14918:                 }
14919:             }
14920:         }
14921:     }
14922:     if ($currdat != $newdat) {
14923:         $changes{'config'} = 1;
14924:     } else {
14925:         foreach my $field (@fields) {
14926:             if ($currcol{$field} ne '') {
14927:                 if ($currcol{$field} ne $newcol{$field}) {
14928:                     $changes{'config'} = 1;
14929:                     last;
14930:                 }
14931:             } elsif ($newcol{$field} ne '') {
14932:                 $changes{'config'} = 1;
14933:                 last;
14934:             }
14935:         }
14936:     }
14937:     if (keys(%confhash) > 0) {
14938:         my $putresult = &Apache::lonnet::put_dom('configuration',\%confhash,
14939:                                                  $dom);
14940:         if ($putresult eq 'ok') {
14941:             if (keys(%changes) > 0) {
14942:                 if (ref($confhash{'scantron'}) eq 'HASH') {
14943:                     $resulttext = &mt('Changes made:').'<ul>';
14944:                     if ($changes{'scantronformat'}) {
14945:                         if ($confhash{'scantron'}{'scantronformat'} eq '') {
14946:                             $resulttext .= '<li>'.&mt('[_1] bubblesheet format file removed; [_2] file will be used for courses in this domain.',$custom,$default).'</li>';
14947:                         } else {
14948:                             $resulttext .= '<li>'.&mt('Custom bubblesheet format file ([_1]) uploaded for use with courses in this domain.',$custom).'</li>';
14949:                         }
14950:                     }
14951:                     if ($changes{'config'}) {
14952:                         if (ref($confhash{'scantron'}{'config'}) eq 'HASH') {
14953:                             if ($confhash{'scantron'}{'config'}{'dat'}) {
14954:                                 $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .dat format').'</li>';
14955:                             }
14956:                             if (ref($confhash{'scantron'}{'config'}{'csv'}) eq 'HASH') {
14957:                                 if (ref($confhash{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
14958:                                     if (keys(%{$confhash{'scantron'}{'config'}{'csv'}{'fields'}})) {
14959:                                         $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .csv format, with following fields/column numbers supported:').'<ul>';
14960:                                         foreach my $field (@fields) {
14961:                                             if ($confhash{'scantron'}{'config'}{'csv'}{'fields'}{$field} ne '') {
14962:                                                 my $showcol = $confhash{'scantron'}{'config'}{'csv'}{'fields'}{$field} + 1;
14963:                                                 $resulttext .= '<li>'.$titles{$field}.': '.$showcol.'</li>';
14964:                                             }
14965:                                         }
14966:                                         $resulttext .= '</ul></li>';
14967:                                         if (ref($confhash{'scantron'}{'config'}{'csv'}{'options'}) eq 'HASH') {
14968:                                             if (keys(%{$confhash{'scantron'}{'config'}{'csv'}{'options'}})) {
14969:                                                 $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .csv format, with following options:').'<ul>';
14970:                                                 foreach my $option (@options) {
14971:                                                     if ($confhash{'scantron'}{'config'}{'csv'}{'options'}{$option} ne '') {
14972:                                                         $resulttext .= '<li>'.$titles{$option}.'</li>';
14973:                                                     }
14974:                                                 }
14975:                                                 $resulttext .= '</ul></li>';
14976:                                             }
14977:                                         }
14978:                                     }
14979:                                 }
14980:                             }
14981:                         } else {
14982:                             $resulttext .= '<li>'.&mt('No bubblesheet data upload formats set -- will default to assuming .dat format').'</li>';
14983:                         }
14984:                     }
14985:                     $resulttext .= '</ul>';
14986:                 } else {
14987:                     $resulttext = &mt('Changes made to bubblesheet format file.');
14988:                 }
14989:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
14990:                 if (ref($lastactref) eq 'HASH') {
14991:                     $lastactref->{'domainconfig'} = 1;
14992:                 }
14993:             } else {
14994:                 $resulttext = &mt('No changes made to bubblesheet format settings');
14995:             }
14996:         } else {
14997:             $resulttext = '<span class="LC_error">'.
14998:                 &mt('An error occurred: [_1]',$putresult).'</span>';
14999:         }
15000:     } else {
15001:         $resulttext = &mt('No changes made to bubblesheet format settings');
15002:     }
15003:     if ($errors) {
15004:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
15005:                        $errors.'</ul>';
15006:     }
15007:     return $resulttext;
15008: }
15009: 
15010: sub modify_coursecategories {
15011:     my ($dom,$lastactref,%domconfig) = @_;
15012:     my ($resulttext,%deletions,%reorderings,%needreordering,%adds,%changes,$errors,
15013:         $cathash);
15014:     my @deletecategory = &Apache::loncommon::get_env_multiple('form.deletecategory');
15015:     my @catitems = ('unauth','auth');
15016:     my @cattypes = ('std','domonly','codesrch','none');
15017:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
15018:         $cathash = $domconfig{'coursecategories'}{'cats'};
15019:         if ($domconfig{'coursecategories'}{'togglecats'} ne $env{'form.togglecats'}) {
15020:             $changes{'togglecats'} = 1;
15021:             $domconfig{'coursecategories'}{'togglecats'} = $env{'form.togglecats'};
15022:         }
15023:         if ($domconfig{'coursecategories'}{'categorize'} ne $env{'form.categorize'}) {
15024:             $changes{'categorize'} = 1;
15025:             $domconfig{'coursecategories'}{'categorize'} = $env{'form.categorize'};
15026:         }
15027:         if ($domconfig{'coursecategories'}{'togglecatscomm'} ne $env{'form.togglecatscomm'}) {
15028:             $changes{'togglecatscomm'} = 1;
15029:             $domconfig{'coursecategories'}{'togglecatscomm'} = $env{'form.togglecatscomm'};
15030:         }
15031:         if ($domconfig{'coursecategories'}{'categorizecomm'} ne $env{'form.categorizecomm'}) {
15032:             $changes{'categorizecomm'} = 1;
15033:             $domconfig{'coursecategories'}{'categorizecomm'} = $env{'form.categorizecomm'};
15034:         }
15035:         foreach my $item (@catitems) {
15036:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
15037:                 if ($domconfig{'coursecategories'}{$item} ne $env{'form.coursecat_'.$item}) {
15038:                     $changes{$item} = 1;
15039:                     $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
15040:                 }
15041:             }
15042:         }
15043:     } else {
15044:         $changes{'togglecats'} = 1;
15045:         $changes{'categorize'} = 1;
15046:         $changes{'togglecatscomm'} = 1;
15047:         $changes{'categorizecomm'} = 1;
15048:         $domconfig{'coursecategories'} = {
15049:                                              togglecats => $env{'form.togglecats'},
15050:                                              categorize => $env{'form.categorize'},
15051:                                              togglecatscomm => $env{'form.togglecatscomm'},
15052:                                              categorizecomm => $env{'form.categorizecomm'},
15053:                                          };
15054:         foreach my $item (@catitems) {
15055:             if ($env{'form.coursecat_'.$item} ne 'std') {
15056:                 $changes{$item} = 1;
15057:             }
15058:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
15059:                 $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
15060:             }
15061:         }
15062:     }
15063:     if (ref($cathash) eq 'HASH') {
15064:         if (($domconfig{'coursecategories'}{'cats'}{'instcode::0'} ne '')  && ($env{'form.instcode'} == 0)) {
15065:             push (@deletecategory,'instcode::0');
15066:         }
15067:         if (($domconfig{'coursecategories'}{'cats'}{'communities::0'} ne '')  && ($env{'form.communities'} == 0)) {
15068:             push(@deletecategory,'communities::0');
15069:         }
15070:     }
15071:     my (@predelcats,@predeltrails,%predelallitems,%sort_by_deltrail);
15072:     if (ref($cathash) eq 'HASH') {
15073:         if (@deletecategory > 0) {
15074:             #FIXME Need to remove category from all courses using a deleted category 
15075:             &Apache::loncommon::extract_categories($cathash,\@predelcats,\@predeltrails,\%predelallitems);
15076:             foreach my $item (@deletecategory) {
15077:                 if ($domconfig{'coursecategories'}{'cats'}{$item} ne '') {
15078:                     delete($domconfig{'coursecategories'}{'cats'}{$item});
15079:                     $deletions{$item} = 1;
15080:                     &recurse_cat_deletes($item,$cathash,\%deletions);
15081:                 }
15082:             }
15083:         }
15084:         foreach my $item (keys(%{$cathash})) {
15085:             my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
15086:             if ($cathash->{$item} ne $env{'form.'.$item}) {
15087:                 $reorderings{$item} = 1;
15088:                 $domconfig{'coursecategories'}{'cats'}{$item} = $env{'form.'.$item};
15089:             }
15090:             if ($env{'form.addcategory_name_'.$item} ne '') {
15091:                 my $newcat = $env{'form.addcategory_name_'.$item};
15092:                 my $newdepth = $depth+1;
15093:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
15094:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos_'.$item};
15095:                 $adds{$newitem} = 1; 
15096:             }
15097:             if ($env{'form.subcat_'.$item} ne '') {
15098:                 my $newcat = $env{'form.subcat_'.$item};
15099:                 my $newdepth = $depth+1;
15100:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
15101:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = 0;
15102:                 $adds{$newitem} = 1;
15103:             }
15104:         }
15105:     }
15106:     if ($env{'form.instcode'} eq '1') {
15107:         if (ref($cathash) eq 'HASH') {
15108:             my $newitem = 'instcode::0';
15109:             if ($cathash->{$newitem} eq '') {  
15110:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
15111:                 $adds{$newitem} = 1;
15112:             }
15113:         } else {
15114:             my $newitem = 'instcode::0';
15115:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
15116:             $adds{$newitem} = 1;
15117:         }
15118:     }
15119:     if ($env{'form.communities'} eq '1') {
15120:         if (ref($cathash) eq 'HASH') {
15121:             my $newitem = 'communities::0';
15122:             if ($cathash->{$newitem} eq '') {
15123:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
15124:                 $adds{$newitem} = 1;
15125:             }
15126:         } else {
15127:             my $newitem = 'communities::0';
15128:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
15129:             $adds{$newitem} = 1;
15130:         }
15131:     }
15132:     if ($env{'form.addcategory_name'} ne '') {
15133:         if (($env{'form.addcategory_name'} ne 'instcode') &&
15134:             ($env{'form.addcategory_name'} ne 'communities')) {
15135:             my $newitem = &escape($env{'form.addcategory_name'}).'::0';
15136:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos'};
15137:             $adds{$newitem} = 1;
15138:         }
15139:     }
15140:     my $putresult;
15141:     if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
15142:         if (keys(%deletions) > 0) {
15143:             foreach my $key (keys(%deletions)) {
15144:                 if ($predelallitems{$key} ne '') {
15145:                     $sort_by_deltrail{$predelallitems{$key}} = $predeltrails[$predelallitems{$key}];
15146:                 }
15147:             }
15148:         }
15149:         my (@chkcats,@chktrails,%chkallitems);
15150:         &Apache::loncommon::extract_categories($domconfig{'coursecategories'}{'cats'},\@chkcats,\@chktrails,\%chkallitems);
15151:         if (ref($chkcats[0]) eq 'ARRAY') {
15152:             my $depth = 0;
15153:             my $chg = 0;
15154:             for (my $i=0; $i<@{$chkcats[0]}; $i++) {
15155:                 my $name = $chkcats[0][$i];
15156:                 my $item;
15157:                 if ($name eq '') {
15158:                     $chg ++;
15159:                 } else {
15160:                     $item = &escape($name).'::0';
15161:                     if ($chg) {
15162:                         $domconfig{'coursecategories'}{'cats'}{$item} -= $chg;
15163:                     }
15164:                     $depth ++; 
15165:                     &recurse_check(\@chkcats,$domconfig{'coursecategories'}{'cats'},$depth,$name);
15166:                     $depth --;
15167:                 }
15168:             }
15169:         }
15170:     }
15171:     if ((keys(%changes) > 0) || (keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
15172:         $putresult = &Apache::lonnet::put_dom('configuration',\%domconfig,$dom);
15173:         if ($putresult eq 'ok') {
15174:             my %title = (
15175:                          togglecats     => 'Show/Hide a course in catalog',
15176:                          categorize     => 'Assign a category to a course',
15177:                          togglecatscomm => 'Show/Hide a community in catalog',
15178:                          categorizecomm => 'Assign a category to a community',
15179:                         );
15180:             my %level = (
15181:                          dom  => 'set in Domain ("Modify Course/Community")',
15182:                          crs  => 'set in Course ("Course Configuration")',
15183:                          comm => 'set in Community ("Community Configuration")',
15184:                          none     => 'No catalog',
15185:                          std      => 'Standard catalog',
15186:                          domonly  => 'Domain-only catalog',
15187:                          codesrch => 'Code search form',
15188:                         );
15189:             $resulttext = &mt('Changes made:').'<ul>';
15190:             if ($changes{'togglecats'}) {
15191:                 $resulttext .= '<li>'.&mt("$title{'togglecats'} $level{$env{'form.togglecats'}}").'</li>'; 
15192:             }
15193:             if ($changes{'categorize'}) {
15194:                 $resulttext .= '<li>'.&mt("$title{'categorize'} $level{$env{'form.categorize'}}").'</li>';
15195:             }
15196:             if ($changes{'togglecatscomm'}) {
15197:                 $resulttext .= '<li>'.&mt("$title{'togglecatscomm'} $level{$env{'form.togglecatscomm'}}").'</li>';
15198:             }
15199:             if ($changes{'categorizecomm'}) {
15200:                 $resulttext .= '<li>'.&mt("$title{'categorizecomm'} $level{$env{'form.categorizecomm'}}").'</li>';
15201:             }
15202:             if ($changes{'unauth'}) {
15203:                 $resulttext .= '<li>'.&mt('Catalog type for unauthenticated users set to "'.$level{$env{'form.coursecat_unauth'}}.'"').'</li>';
15204:             }
15205:             if ($changes{'auth'}) {
15206:                 $resulttext .= '<li>'.&mt('Catalog type for authenticated users set to "'.$level{$env{'form.coursecat_auth'}}.'"').'</li>';
15207:             }
15208:             if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
15209:                 my $cathash;
15210:                 if (ref($domconfig{'coursecategories'}) eq 'HASH') {
15211:                     $cathash = $domconfig{'coursecategories'}{'cats'};
15212:                 } else {
15213:                     $cathash = {};
15214:                 } 
15215:                 my (@cats,@trails,%allitems);
15216:                     &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,\%allitems);
15217:                 if (keys(%deletions) > 0) {
15218:                     $resulttext .= '<li>'.&mt('Deleted categories:').'<ul>';
15219:                     foreach my $predeltrail (sort {$a <=> $b } (keys(%sort_by_deltrail))) { 
15220:                         $resulttext .= '<li>'.$predeltrails[$predeltrail].'</li>';
15221:                     }
15222:                     $resulttext .= '</ul></li>';
15223:                 }
15224:                 if (keys(%reorderings) > 0) {
15225:                     my %sort_by_trail;
15226:                     $resulttext .= '<li>'.&mt('Reordered categories:').'<ul>';
15227:                     foreach my $key (keys(%reorderings)) {
15228:                         if ($allitems{$key} ne '') {
15229:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
15230:                         }
15231:                     }
15232:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
15233:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
15234:                     }
15235:                     $resulttext .= '</ul></li>';
15236:                 }
15237:                 if (keys(%adds) > 0) {
15238:                     my %sort_by_trail;
15239:                     $resulttext .= '<li>'.&mt('Added categories:').'<ul>';
15240:                     foreach my $key (keys(%adds)) {
15241:                         if ($allitems{$key} ne '') {
15242:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
15243:                         }
15244:                     }
15245:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
15246:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
15247:                     }
15248:                     $resulttext .= '</ul></li>';
15249:                 }
15250:                 &Apache::lonnet::do_cache_new('cats',$dom,$cathash,3600);
15251:                 if (ref($lastactref) eq 'HASH') {
15252:                     $lastactref->{'cats'} = 1;
15253:                 }
15254:             }
15255:             $resulttext .= '</ul>';
15256:             if ($changes{'unauth'} || $changes{'auth'}) {
15257:                 my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
15258:                 if ($changes{'auth'}) {
15259:                     $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
15260:                 }
15261:                 if ($changes{'unauth'}) {
15262:                     $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
15263:                 }
15264:                 my $cachetime = 24*60*60;
15265:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
15266:                 if (ref($lastactref) eq 'HASH') {
15267:                     $lastactref->{'domdefaults'} = 1;
15268:                 }
15269:             }
15270:         } else {
15271:             $resulttext = '<span class="LC_error">'.
15272:                           &mt('An error occurred: [_1]',$putresult).'</span>';
15273:         }
15274:     } else {
15275:         $resulttext = &mt('No changes made to course and community categories');
15276:     }
15277:     return $resulttext;
15278: }
15279: 
15280: sub modify_serverstatuses {
15281:     my ($dom,%domconfig) = @_;
15282:     my ($resulttext,%changes,%currserverstatus,%newserverstatus);
15283:     if (ref($domconfig{'serverstatuses'}) eq 'HASH') {
15284:         %currserverstatus = %{$domconfig{'serverstatuses'}};
15285:     }
15286:     my @pages = &serverstatus_pages();
15287:     foreach my $type (@pages) {
15288:         $newserverstatus{$type}{'namedusers'} = '';
15289:         $newserverstatus{$type}{'machines'} = '';
15290:         if (defined($env{'form.'.$type.'_namedusers'})) {
15291:             my @users = split(/,/,$env{'form.'.$type.'_namedusers'});
15292:             my @okusers;
15293:             foreach my $user (@users) {
15294:                 my ($uname,$udom) = split(/:/,$user);
15295:                 if (($udom =~ /^$match_domain$/) &&   
15296:                     (&Apache::lonnet::domain($udom)) &&
15297:                     ($uname =~ /^$match_username$/)) {
15298:                     if (!grep(/^\Q$user\E/,@okusers)) {
15299:                         push(@okusers,$user);
15300:                     }
15301:                 }
15302:             }
15303:             if (@okusers > 0) {
15304:                  @okusers = sort(@okusers);
15305:                  $newserverstatus{$type}{'namedusers'} = join(',',@okusers);
15306:             }
15307:         }
15308:         if (defined($env{'form.'.$type.'_machines'})) {
15309:             my @machines = split(/,/,$env{'form.'.$type.'_machines'});
15310:             my @okmachines;
15311:             foreach my $ip (@machines) {
15312:                 my @parts = split(/\./,$ip);
15313:                 next if (@parts < 4);
15314:                 my $badip = 0;
15315:                 for (my $i=0; $i<4; $i++) {
15316:                     if (!(($parts[$i] >= 0) && ($parts[$i] <= 255))) {
15317:                         $badip = 1;
15318:                         last;
15319:                     }
15320:                 }
15321:                 if (!$badip) {
15322:                     push(@okmachines,$ip);     
15323:                 }
15324:             }
15325:             @okmachines = sort(@okmachines);
15326:             $newserverstatus{$type}{'machines'} = join(',',@okmachines);
15327:         }
15328:     }
15329:     my %serverstatushash =  (
15330:                                 serverstatuses => \%newserverstatus,
15331:                             );
15332:     foreach my $type (@pages) {
15333:         foreach my $setting ('namedusers','machines') {
15334:             my (@current,@new);
15335:             if (ref($currserverstatus{$type}) eq 'HASH') {
15336:                 if ($currserverstatus{$type}{$setting} ne '') { 
15337:                     @current = split(/,/,$currserverstatus{$type}{$setting});
15338:                 }
15339:             }
15340:             if ($newserverstatus{$type}{$setting} ne '') {
15341:                 @new = split(/,/,$newserverstatus{$type}{$setting});
15342:             }
15343:             if (@current > 0) {
15344:                 if (@new > 0) {
15345:                     foreach my $item (@current) {
15346:                         if (!grep(/^\Q$item\E$/,@new)) {
15347:                             $changes{$type}{$setting} = 1;
15348:                             last;
15349:                         }
15350:                     }
15351:                     foreach my $item (@new) {
15352:                         if (!grep(/^\Q$item\E$/,@current)) {
15353:                             $changes{$type}{$setting} = 1;
15354:                             last;
15355:                         }
15356:                     }
15357:                 } else {
15358:                     $changes{$type}{$setting} = 1;
15359:                 }
15360:             } elsif (@new > 0) {
15361:                 $changes{$type}{$setting} = 1;
15362:             }
15363:         }
15364:     }
15365:     if (keys(%changes) > 0) {
15366:         my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
15367:         my $putresult = &Apache::lonnet::put_dom('configuration',
15368:                                                  \%serverstatushash,$dom);
15369:         if ($putresult eq 'ok') {
15370:             $resulttext .= &mt('Changes made:').'<ul>';
15371:             foreach my $type (@pages) {
15372:                 if (ref($changes{$type}) eq 'HASH') {
15373:                     $resulttext .= '<li>'.$titles->{$type}.'<ul>';
15374:                     if ($changes{$type}{'namedusers'}) {
15375:                         if ($newserverstatus{$type}{'namedusers'} eq '') {
15376:                             $resulttext .= '<li>'.&mt("Access terminated for all specific (named) users").'</li>'."\n";
15377:                         } else {
15378:                             $resulttext .= '<li>'.&mt("Access available for the following specified users: ").$newserverstatus{$type}{'namedusers'}.'</li>'."\n";
15379:                         }
15380:                     }
15381:                     if ($changes{$type}{'machines'}) {
15382:                         if ($newserverstatus{$type}{'machines'} eq '') {
15383:                             $resulttext .= '<li>'.&mt("Access terminated for all specific IP addresses").'</li>'."\n";
15384:                         } else {
15385:                             $resulttext .= '<li>'.&mt("Access available for the following specified IP addresses: ").$newserverstatus{$type}{'machines'}.'</li>'."\n";
15386:                         }
15387: 
15388:                     }
15389:                     $resulttext .= '</ul></li>';
15390:                 }
15391:             }
15392:             $resulttext .= '</ul>';
15393:         } else {
15394:             $resulttext = '<span class="LC_error">'.
15395:                           &mt('An error occurred saving access settings for server status pages: [_1].',$putresult).'</span>';
15396: 
15397:         }
15398:     } else {
15399:         $resulttext = &mt('No changes made to access to server status pages');
15400:     }
15401:     return $resulttext;
15402: }
15403: 
15404: sub modify_helpsettings {
15405:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
15406:     my ($resulttext,$errors,%changes,%helphash);
15407:     my %defaultchecked = ('submitbugs' => 'on');
15408:     my @offon = ('off','on');
15409:     my @toggles = ('submitbugs');
15410:     my %current = ('submitbugs' => '',
15411:                    'adhoc'      => {},
15412:                   );
15413:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
15414:         %current = %{$domconfig{'helpsettings'}};
15415:     }
15416:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
15417:     foreach my $item (@toggles) {
15418:         if ($defaultchecked{$item} eq 'on') { 
15419:             if ($current{$item} eq '') {
15420:                 if ($env{'form.'.$item} eq '0') {
15421:                     $changes{$item} = 1;
15422:                 }
15423:             } elsif ($current{$item} ne $env{'form.'.$item}) {
15424:                 $changes{$item} = 1;
15425:             }
15426:         } elsif ($defaultchecked{$item} eq 'off') {
15427:             if ($current{$item} eq '') {
15428:                 if ($env{'form.'.$item} eq '1') {
15429:                     $changes{$item} = 1;
15430:                 }
15431:             } elsif ($current{$item} ne $env{'form.'.$item}) {
15432:                 $changes{$item} = 1;
15433:             }
15434:         }
15435:         if (($env{'form.'.$item} eq '0') || ($env{'form.'.$item} eq '1')) {
15436:             $helphash{'helpsettings'}{$item} = $env{'form.'.$item};
15437:         }
15438:     }
15439:     my $maxnum = $env{'form.helproles_maxnum'};
15440:     my $confname = $dom.'-domainconfig';
15441:     my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
15442:     my (@allpos,%newsettings,%changedprivs,$newrole);
15443:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
15444:     my @accesstypes = ('all','dh','da','none','status','inc','exc');
15445:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh','da']);
15446:     my %lt = &Apache::lonlocal::texthash(
15447:                     s      => 'system',
15448:                     d      => 'domain',
15449:                     order  => 'Display order',
15450:                     access => 'Role usage',
15451:                     all    => 'All with domain helpdesk or helpdesk assistant role',
15452:                     dh     => 'All with domain helpdesk role',
15453:                     da     => 'All with domain helpdesk assistant role',
15454:                     none   => 'None',
15455:                     status => 'Determined based on institutional status',
15456:                     inc    => 'Include all, but exclude specific personnel',
15457:                     exc    => 'Exclude all, but include specific personnel',
15458:     );
15459:     for (my $num=0; $num<=$maxnum; $num++) {
15460:         my ($prefix,$identifier,$rolename,%curr);
15461:         if ($num == $maxnum) {
15462:             next unless ($env{'form.newcusthelp'} == $maxnum);
15463:             $identifier = 'custhelp'.$num;
15464:             $prefix = 'helproles_'.$num;
15465:             $rolename = $env{'form.custhelpname'.$num};
15466:             $rolename=~s/[^A-Za-z0-9]//gs;
15467:             next if ($rolename eq '');
15468:             next if (exists($existing{'rolesdef_'.$rolename}));
15469:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
15470:             my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
15471:                                                      $newprivs{'c'},$confname,$dom);
15472:             if ($result ne 'ok') {
15473:                 $errors .= '<li><span class="LC_error">'.
15474:                            &mt('An error occurred storing the new custom role: [_1]',
15475:                            $result).'</span></li>';
15476:                 next;
15477:             } else {
15478:                 $changedprivs{$rolename} = \%newprivs;
15479:                 $newrole = $rolename;
15480:             }
15481:         } else {
15482:             $prefix = 'helproles_'.$num;
15483:             $rolename = $env{'form.'.$prefix};
15484:             next if ($rolename eq '');
15485:             next unless (exists($existing{'rolesdef_'.$rolename}));
15486:             $identifier = 'custhelp'.$num;
15487:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
15488:             my %currprivs;
15489:             ($currprivs{'s'},$currprivs{'d'},$currprivs{'c'}) =
15490:                 split(/\_/,$existing{'rolesdef_'.$rolename});
15491:             foreach my $level ('c','d','s') {
15492:                 if ($newprivs{$level} ne $currprivs{$level}) {
15493:                     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
15494:                                                              $newprivs{'c'},$confname,$dom);
15495:                     if ($result ne 'ok') {
15496:                         $errors .= '<li><span class="LC_error">'.
15497:                                    &mt('An error occurred storing privileges for existing role [_1]: [_2]',
15498:                                        $rolename,$result).'</span></li>';
15499:                     } else {
15500:                         $changedprivs{$rolename} = \%newprivs;
15501:                     }
15502:                     last;
15503:                 }
15504:             }
15505:             if (ref($current{'adhoc'}) eq 'HASH') {
15506:                 if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
15507:                     %curr = %{$current{'adhoc'}{$rolename}};
15508:                 }
15509:             }
15510:         }
15511:         my $newpos = $env{'form.'.$prefix.'_pos'};
15512:         $newpos =~ s/\D+//g;
15513:         $allpos[$newpos] = $rolename;
15514:         my $newdesc = $env{'form.'.$prefix.'_desc'};
15515:         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'desc'} = $newdesc;
15516:         if ($curr{'desc'}) {
15517:             if ($curr{'desc'} ne $newdesc) {
15518:                 $changes{'customrole'}{$rolename}{'desc'} = 1;
15519:                 $newsettings{$rolename}{'desc'} = $newdesc;
15520:             }
15521:         } elsif ($newdesc ne '') {
15522:             $changes{'customrole'}{$rolename}{'desc'} = 1;
15523:             $newsettings{$rolename}{'desc'} = $newdesc;
15524:         }
15525:         my $access = $env{'form.'.$prefix.'_access'};
15526:         if (grep(/^\Q$access\E$/,@accesstypes)) {
15527:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = $access;
15528:             if ($access eq 'status') {
15529:                 my @statuses = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_status');
15530:                 if (scalar(@statuses) == 0) {
15531:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'none';
15532:                 } else {
15533:                     my (@shownstatus,$numtypes);
15534:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
15535:                     if (ref($types) eq 'ARRAY') {
15536:                         $numtypes = scalar(@{$types});
15537:                         foreach my $type (sort(@statuses)) {
15538:                             if ($type eq 'default') {
15539:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
15540:                             } elsif (grep(/^\Q$type\E$/,@{$types})) {
15541:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
15542:                                 push(@shownstatus,$usertypes->{$type});
15543:                             }
15544:                         }
15545:                     }
15546:                     if (grep(/^default$/,@statuses)) {
15547:                         push(@shownstatus,$othertitle);
15548:                     }
15549:                     if (scalar(@shownstatus) == 1+$numtypes) {
15550:                         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'all';
15551:                         delete($helphash{'helpsettings'}{'adhoc'}{$rolename}{'status'});
15552:                     } else {
15553:                         $newsettings{$rolename}{'status'} = join(' '.&mt('or').' ',@shownstatus);
15554:                         if (ref($curr{'status'}) eq 'ARRAY') {
15555:                             my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
15556:                             if (@diffs) {
15557:                                 $changes{'customrole'}{$rolename}{$access} = 1;
15558:                             }
15559:                         } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
15560:                             $changes{'customrole'}{$rolename}{$access} = 1;
15561:                         }
15562:                     }
15563:                 }
15564:             } elsif (($access eq 'inc') || ($access eq 'exc')) {
15565:                 my @personnel = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_staff_'.$access);
15566:                 my @newspecstaff;
15567:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
15568:                 foreach my $person (sort(@personnel)) {
15569:                     if ($domhelpdesk{$person}) {
15570:                         push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$person);
15571:                     }
15572:                 }
15573:                 if (ref($curr{$access}) eq 'ARRAY') {
15574:                     my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
15575:                     if (@diffs) {
15576:                         $changes{'customrole'}{$rolename}{$access} = 1;
15577:                     }
15578:                 } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
15579:                     $changes{'customrole'}{$rolename}{$access} = 1;
15580:                 }
15581:                 foreach my $person (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
15582:                     my ($uname,$udom) = split(/:/,$person);
15583:                         push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
15584:                 }
15585:                 $newsettings{$rolename}{$access} = join(', ',sort(@newspecstaff));
15586:             }
15587:         } else {
15588:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}= 'all';
15589:         }
15590:         unless ($curr{'access'} eq $access) {
15591:             $changes{'customrole'}{$rolename}{'access'} = 1;
15592:             $newsettings{$rolename}{'access'} = $lt{$helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}};
15593:         }
15594:     }
15595:     if (@allpos > 0) {
15596:         my $idx = 0;
15597:         foreach my $rolename (@allpos) {
15598:             if ($rolename ne '') {
15599:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{'order'} = $idx;
15600:                 if (ref($current{'adhoc'}) eq 'HASH') {
15601:                     if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
15602:                         if ($current{'adhoc'}{$rolename}{'order'} ne $idx) {
15603:                             $changes{'customrole'}{$rolename}{'order'} = 1;
15604:                             $newsettings{$rolename}{'order'} = $idx+1;
15605:                         }
15606:                     }
15607:                 }
15608:                 $idx ++;
15609:             }
15610:         }
15611:     }
15612:     my $putresult;
15613:     if (keys(%changes) > 0) {
15614:         $putresult = &Apache::lonnet::put_dom('configuration',\%helphash,$dom);
15615:         if ($putresult eq 'ok') {
15616:             if (ref($helphash{'helpsettings'}) eq 'HASH') {
15617:                 $domdefaults{'submitbugs'} = $helphash{'helpsettings'}{'submitbugs'};
15618:                 if (ref($helphash{'helpsettings'}{'adhoc'}) eq 'HASH') {
15619:                     $domdefaults{'adhocroles'} = $helphash{'helpsettings'}{'adhoc'};
15620:                 }
15621:             }
15622:             my $cachetime = 24*60*60;
15623:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
15624:             if (ref($lastactref) eq 'HASH') {
15625:                 $lastactref->{'domdefaults'} = 1;
15626:             }
15627:         } else {
15628:             $errors .= '<li><span class="LC_error">'.
15629:                        &mt('An error occurred storing the settings: [_1]',
15630:                            $putresult).'</span></li>';
15631:         }
15632:     }
15633:     if ((keys(%changes) && ($putresult eq 'ok')) || (keys(%changedprivs))) {
15634:         $resulttext = &mt('Changes made:').'<ul>';
15635:         my (%shownprivs,@levelorder);
15636:         @levelorder = ('c','d','s');
15637:         if ((keys(%changes)) && ($putresult eq 'ok')) {
15638:             foreach my $item (sort(keys(%changes))) {
15639:                 if ($item eq 'submitbugs') {
15640:                     $resulttext .= '<li>'.&mt('Display link to: [_1] set to "'.$offon[$env{'form.'.$item}].'".',
15641:                                               &Apache::loncommon::modal_link('http://bugs.loncapa.org',
15642:                                               &mt('LON-CAPA bug tracker'),600,500)).'</li>';
15643:                 } elsif ($item eq 'customrole') {
15644:                     if (ref($changes{'customrole'}) eq 'HASH') {
15645:                         my @keyorder = ('order','desc','access','status','exc','inc');
15646:                         my %keytext = &Apache::lonlocal::texthash(
15647:                                                                    order  => 'Order',
15648:                                                                    desc   => 'Role description',
15649:                                                                    access => 'Role usage',
15650:                                                                    status => 'Allowed institutional types',
15651:                                                                    exc    => 'Allowed personnel',
15652:                                                                    inc    => 'Disallowed personnel',
15653:                         );
15654:                         foreach my $role (sort(keys(%{$changes{'customrole'}}))) {
15655:                             if (ref($changes{'customrole'}{$role}) eq 'HASH') {
15656:                                 if ($role eq $newrole) {
15657:                                     $resulttext .= '<li>'.&mt('New custom role added: [_1]',
15658:                                                               $role).'<ul>';
15659:                                 } else {
15660:                                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
15661:                                                               $role).'<ul>';
15662:                                 }
15663:                                 foreach my $key (@keyorder) {
15664:                                     if ($changes{'customrole'}{$role}{$key}) {
15665:                                         $resulttext .= '<li>'.&mt("[_1] set to: [_2]",
15666:                                                                   $keytext{$key},$newsettings{$role}{$key}).
15667:                                                        '</li>';
15668:                                     }
15669:                                 }
15670:                                 if (ref($changedprivs{$role}) eq 'HASH') {
15671:                                     $shownprivs{$role} = 1;
15672:                                     $resulttext .= '<li>'.&mt('Privileges set to :').'<ul>';
15673:                                     foreach my $level (@levelorder) {
15674:                                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
15675:                                             next if ($item eq '');
15676:                                             my ($priv) = split(/\&/,$item,2);
15677:                                             if (&Apache::lonnet::plaintext($priv)) {
15678:                                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
15679:                                                 unless ($level eq 'c') {
15680:                                                     $resulttext .= ' ('.$lt{$level}.')';
15681:                                                 }
15682:                                                 $resulttext .= '</li>';
15683:                                             }
15684:                                         }
15685:                                     }
15686:                                     $resulttext .= '</ul>';
15687:                                 }
15688:                                 $resulttext .= '</ul></li>';
15689:                             }
15690:                         }
15691:                     }
15692:                 }
15693:             }
15694:         }
15695:         if (keys(%changedprivs)) {
15696:             foreach my $role (sort(keys(%changedprivs))) {
15697:                 unless ($shownprivs{$role}) {
15698:                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
15699:                                               $role).'<ul>'.
15700:                                    '<li>'.&mt('Privileges set to :').'<ul>';
15701:                     foreach my $level (@levelorder) {
15702:                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
15703:                             next if ($item eq '');
15704:                             my ($priv) = split(/\&/,$item,2);
15705:                             if (&Apache::lonnet::plaintext($priv)) {
15706:                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
15707:                                 unless ($level eq 'c') {
15708:                                     $resulttext .= ' ('.$lt{$level}.')';
15709:                                 }
15710:                                 $resulttext .= '</li>';
15711:                             }
15712:                         }
15713:                     }
15714:                     $resulttext .= '</ul></li></ul></li>';
15715:                 }
15716:             }
15717:         }
15718:         $resulttext .= '</ul>';
15719:     } else {
15720:         $resulttext = &mt('No changes made to help settings');
15721:     }
15722:     if ($errors) {
15723:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
15724:                                     $errors.'</ul>';
15725:     }
15726:     return $resulttext;
15727: }
15728: 
15729: sub modify_coursedefaults {
15730:     my ($dom,$lastactref,%domconfig) = @_;
15731:     my ($resulttext,$errors,%changes,%defaultshash);
15732:     my %defaultchecked = (
15733:                            'uselcmath'       => 'on',
15734:                            'usejsme'         => 'on',
15735:                            'inline_chem'     => 'on',
15736:                          );
15737:     my @toggles = ('uselcmath','usejsme','inline_chem');
15738:     my @numbers = ('anonsurvey_threshold','uploadquota_official','uploadquota_unofficial',
15739:                    'uploadquota_community','uploadquota_textbook','mysqltables_official',
15740:                    'mysqltables_unofficial','mysqltables_community','mysqltables_textbook');
15741:     my @types = ('official','unofficial','community','textbook');
15742:     my %staticdefaults = (
15743:                            anonsurvey_threshold => 10,
15744:                            uploadquota          => 500,
15745:                            postsubmit           => 60,
15746:                            mysqltables          => 172800,
15747:                          );
15748:     my %texoptions = (
15749:                         MathJax  => 'MathJax',
15750:                         mimetex  => &mt('Convert to Images'),
15751:                         tth      => &mt('TeX to HTML'),
15752:                      );
15753:     $defaultshash{'coursedefaults'} = {};
15754: 
15755:     if (ref($domconfig{'coursedefaults'}) ne 'HASH') {
15756:         if ($domconfig{'coursedefaults'} eq '') {
15757:             $domconfig{'coursedefaults'} = {};
15758:         }
15759:     }
15760: 
15761:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
15762:         foreach my $item (@toggles) {
15763:             if ($defaultchecked{$item} eq 'on') {
15764:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
15765:                     ($env{'form.'.$item} eq '0')) {
15766:                     $changes{$item} = 1;
15767:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
15768:                     $changes{$item} = 1;
15769:                 }
15770:             } elsif ($defaultchecked{$item} eq 'off') {
15771:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
15772:                     ($env{'form.'.$item} eq '1')) {
15773:                     $changes{$item} = 1;
15774:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
15775:                     $changes{$item} = 1;
15776:                 }
15777:             }
15778:             $defaultshash{'coursedefaults'}{$item} = $env{'form.'.$item};
15779:         }
15780:         foreach my $item (@numbers) {
15781:             my ($currdef,$newdef);
15782:             $newdef = $env{'form.'.$item};
15783:             if ($item eq 'anonsurvey_threshold') {
15784:                 $currdef = $domconfig{'coursedefaults'}{$item};
15785:                 $newdef =~ s/\D//g;
15786:                 if ($newdef eq '' || $newdef < 1) {
15787:                     $newdef = 1;
15788:                 }
15789:                 $defaultshash{'coursedefaults'}{$item} = $newdef;
15790:             } else {
15791:                 my ($setting,$type) = ($item =~ /^(uploadquota|mysqltables)_(\w+)$/);
15792:                 if (ref($domconfig{'coursedefaults'}{$setting}) eq 'HASH') {
15793:                     $currdef = $domconfig{'coursedefaults'}{$setting}{$type};
15794:                 }
15795:                 $newdef =~ s/[^\w.\-]//g;
15796:                 $defaultshash{'coursedefaults'}{$setting}{$type} = $newdef;
15797:             }
15798:             if ($currdef ne $newdef) {
15799:                 if ($item eq 'anonsurvey_threshold') {
15800:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$item})) {
15801:                         $changes{$item} = 1;
15802:                     }
15803:                 } elsif ($item =~ /^(uploadquota|mysqltables)_/) {
15804:                     my $setting = $1;
15805:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$setting})) {
15806:                         $changes{$setting} = 1;
15807:                     }
15808:                 }
15809:             }
15810:         }
15811:         my $texengine;
15812:         if ($env{'form.texengine'} =~ /^(MathJax|mimetex|tth)$/) {
15813:             $texengine = $env{'form.texengine'};
15814:             my $currdef = $domconfig{'coursedefaults'}{'texengine'};
15815:             if ($currdef eq '') {
15816:                 unless ($texengine eq $Apache::lonnet::deftex) {
15817:                     $changes{'texengine'} = 1;
15818:                 }
15819:             } elsif ($currdef ne $texengine) {
15820:                 $changes{'texengine'} = 1;
15821:             }
15822:         }
15823:         if ($texengine ne '') {
15824:             $defaultshash{'coursedefaults'}{'texengine'} = $texengine;
15825:         }
15826:         my $currclone = $domconfig{'coursedefaults'}{'canclone'};
15827:         my @currclonecode;
15828:         if (ref($currclone) eq 'HASH') {
15829:             if (ref($currclone->{'instcode'}) eq 'ARRAY') {
15830:                 @currclonecode = @{$currclone->{'instcode'}};
15831:             }
15832:         }
15833:         my $newclone;
15834:         if ($env{'form.canclone'} =~ /^(none|domain|instcode)$/) {
15835:             $newclone = $env{'form.canclone'};
15836:         }
15837:         if ($newclone eq 'instcode') {
15838:             my @newcodes = &Apache::loncommon::get_env_multiple('form.clonecode');
15839:             my (%codedefaults,@code_order,@clonecode);
15840:             &Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
15841:                                                     \@code_order);
15842:             foreach my $item (@code_order) {
15843:                 if (grep(/^\Q$item\E$/,@newcodes)) {
15844:                     push(@clonecode,$item);
15845:                 }
15846:             }
15847:             if (@clonecode) {
15848:                 $defaultshash{'coursedefaults'}{'canclone'} = { $newclone => \@clonecode };
15849:                 my @diffs = &Apache::loncommon::compare_arrays(\@currclonecode,\@clonecode);
15850:                 if (@diffs) {
15851:                     $changes{'canclone'} = 1;
15852:                 }
15853:             } else {
15854:                 $newclone eq '';
15855:             }
15856:         } elsif ($newclone ne '') {
15857:             $defaultshash{'coursedefaults'}{'canclone'} = $newclone;
15858:         }
15859:         if ($newclone ne $currclone) {
15860:             $changes{'canclone'} = 1;
15861:         }
15862:         my %credits;
15863:         foreach my $type (@types) {
15864:             unless ($type eq 'community') {
15865:                 $credits{$type} = $env{'form.'.$type.'_credits'};
15866:                 $credits{$type} =~ s/[^\d.]+//g;
15867:             }
15868:         }
15869:         if ((ref($domconfig{'coursedefaults'}{'coursecredits'}) ne 'HASH') &&
15870:             ($env{'form.coursecredits'} eq '1')) {
15871:             $changes{'coursecredits'} = 1;
15872:             foreach my $type (keys(%credits)) {
15873:                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
15874:             }
15875:         } else {
15876:             if ($env{'form.coursecredits'} eq '1') {
15877:                 foreach my $type (@types) {
15878:                     unless ($type eq 'community') {
15879:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type} ne $credits{$type}) {
15880:                             $changes{'coursecredits'} = 1;
15881:                         }
15882:                         $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
15883:                     }
15884:                 }
15885:             } elsif (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
15886:                 foreach my $type (@types) {
15887:                     unless ($type eq 'community') {
15888:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type}) {
15889:                             $changes{'coursecredits'} = 1;
15890:                             last;
15891:                         }
15892:                     }
15893:                 }
15894:             }
15895:         }
15896:         if ($env{'form.postsubmit'} eq '1') {
15897:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'on';
15898:             my %currtimeout;
15899:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
15900:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'off') {
15901:                     $changes{'postsubmit'} = 1;
15902:                 }
15903:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
15904:                     %currtimeout = %{$domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}};
15905:                 }
15906:             } else {
15907:                 $changes{'postsubmit'} = 1;
15908:             }
15909:             foreach my $type (@types) {
15910:                 my $timeout = $env{'form.'.$type.'_timeout'};
15911:                 $timeout =~ s/\D//g;
15912:                 if ($timeout == $staticdefaults{'postsubmit'}) {
15913:                     $timeout = '';
15914:                 } elsif (($timeout eq '') || ($timeout =~ /^0+$/)) {
15915:                     $timeout = '0';
15916:                 }
15917:                 unless ($timeout eq '') {
15918:                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type} = $timeout;
15919:                 }
15920:                 if (exists($currtimeout{$type})) {
15921:                     if ($timeout ne $currtimeout{$type}) {
15922:                         $changes{'postsubmit'} = 1;
15923:                     }
15924:                 } elsif ($timeout ne '') {
15925:                     $changes{'postsubmit'} = 1;
15926:                 }
15927:             }
15928:         } else {
15929:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'off';
15930:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
15931:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'on') {
15932:                     $changes{'postsubmit'} = 1;
15933:                 }
15934:             } else {
15935:                 $changes{'postsubmit'} = 1;
15936:             }
15937:         }
15938:     }
15939:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
15940:                                              $dom);
15941:     if ($putresult eq 'ok') {
15942:         if (keys(%changes) > 0) {
15943:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
15944:             if (($changes{'uploadquota'}) || ($changes{'postsubmit'}) ||
15945:                 ($changes{'coursecredits'}) || ($changes{'uselcmath'}) || ($changes{'usejsme'}) ||
15946:                 ($changes{'canclone'}) || ($changes{'mysqltables'}) || ($changes{'texengine'}) ||
15947:                 ($changes{'inline_chem'})) {
15948:                 foreach my $item ('uselcmath','usejsme','inline_chem','texengine') {
15949:                     if ($changes{$item}) {
15950:                         $domdefaults{$item}=$defaultshash{'coursedefaults'}{$item};
15951:                     }
15952:                 }
15953:                 if ($changes{'coursecredits'}) {
15954:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
15955:                         foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'coursecredits'}})) {
15956:                             $domdefaults{$type.'credits'} =
15957:                                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type};
15958:                         }
15959:                     }
15960:                 }
15961:                 if ($changes{'postsubmit'}) {
15962:                     if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
15963:                         $domdefaults{'postsubmit'} = $defaultshash{'coursedefaults'}{'postsubmit'}{'client'};
15964:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
15965:                             foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}})) {
15966:                                 $domdefaults{$type.'postsubtimeout'} =
15967:                                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
15968:                             }
15969:                         }
15970:                     }
15971:                 }
15972:                 if ($changes{'uploadquota'}) {
15973:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
15974:                         foreach my $type (@types) {
15975:                             $domdefaults{$type.'quota'}=$defaultshash{'coursedefaults'}{'uploadquota'}{$type};
15976:                         }
15977:                     }
15978:                 }
15979:                 if ($changes{'canclone'}) {
15980:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
15981:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
15982:                             my @clonecodes = @{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}};
15983:                             if (@clonecodes) {
15984:                                 $domdefaults{'canclone'} = join('+',@clonecodes);
15985:                             }
15986:                         }
15987:                     } else {
15988:                         $domdefaults{'canclone'}=$defaultshash{'coursedefaults'}{'canclone'};
15989:                     }
15990:                 }
15991:                 my $cachetime = 24*60*60;
15992:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
15993:                 if (ref($lastactref) eq 'HASH') {
15994:                     $lastactref->{'domdefaults'} = 1;
15995:                 }
15996:             }
15997:             $resulttext = &mt('Changes made:').'<ul>';
15998:             foreach my $item (sort(keys(%changes))) {
15999:                 if ($item eq 'uselcmath') {
16000:                     if ($env{'form.'.$item} eq '1') {
16001:                         $resulttext .= '<li>'.&mt('Math preview uses LON-CAPA previewer (javascript), if supported by browser.').'</li>';
16002:                     } else {
16003:                         $resulttext .= '<li>'.&mt('Math preview uses DragMath (Java), if supported by client OS.').'</li>';
16004:                     }
16005:                 } elsif ($item eq 'usejsme') {
16006:                     if ($env{'form.'.$item} eq '1') {
16007:                         $resulttext .= '<li>'.&mt('Molecule editor uses JSME (HTML5), if supported by browser.').'</li>';
16008:                     } else {
16009:                         $resulttext .= '<li>'.&mt('Molecule editor uses JME (Java), if supported by client OS.').'</li>';
16010:                     }
16011:                 } elsif ($item eq 'inline_chem') {
16012:                     if ($env{'form.'.$item} eq '1') {
16013:                         $resulttext .= '<li>'.&mt('Chemical Reaction Response uses inline previewer').'</li>';
16014:                     } else {
16015:                         $resulttext .= '<li>'.&mt('Chemical Reaction Response uses pop-up previewer').'</li>';
16016:                     }
16017:                 } elsif ($item eq 'texengine') {
16018:                     if ($defaultshash{'coursedefaults'}{'texengine'} ne '') {
16019:                         $resulttext .= '<li>'.&mt('Default method to display mathematics set to: "[_1]"',
16020:                                                   $texoptions{$defaultshash{'coursedefaults'}{'texengine'}}).'</li>';
16021:                     }
16022:                 } elsif ($item eq 'anonsurvey_threshold') {
16023:                     $resulttext .= '<li>'.&mt('Responder count required for display of anonymous survey submissions set to [_1].',$defaultshash{'coursedefaults'}{'anonsurvey_threshold'}).'</li>';
16024:                 } elsif ($item eq 'uploadquota') {
16025:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
16026:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded to a course/community via Course Editor set as follows:').'<ul>'.
16027:                                        '<li>'.&mt('Official courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'official'}.'</b>').'</li>'.
16028:                                        '<li>'.&mt('Unofficial courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'unofficial'}.'</b>').'</li>'.
16029:                                        '<li>'.&mt('Textbook courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'textbook'}.'</b>').'</li>'.
16030: 
16031:                                        '<li>'.&mt('Communities: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'community'}.'</b>').'</li>'.
16032:                                        '</ul>'.
16033:                                        '</li>';
16034:                     } else {
16035:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded via Course Editor remains default: [_1] MB',$staticdefaults{'uploadquota'}).'</li>';
16036:                     }
16037:                 } elsif ($item eq 'mysqltables') {
16038:                     if (ref($defaultshash{'coursedefaults'}{'mysqltables'}) eq 'HASH') {
16039:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver').'<ul>'.
16040:                                        '<li>'.&mt('Official courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'official'}.'</b>').'</li>'.
16041:                                        '<li>'.&mt('Unofficial courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'unofficial'}.'</b>').'</li>'.
16042:                                        '<li>'.&mt('Textbook courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'textbook'}.'</b>').'</li>'.
16043:                                        '<li>'.&mt('Communities: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'community'}.'</b>').'</li>'.
16044:                                        '</ul>'.
16045:                                        '</li>';
16046:                     } else {
16047:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver remains default: [_1] s',$staticdefaults{'uploadquota'}).'</li>';
16048:                     }
16049:                 } elsif ($item eq 'postsubmit') {
16050:                     if ($domdefaults{'postsubmit'} eq 'off') {
16051:                         $resulttext .= '<li>'.&mt('Submit button(s) remain enabled on page after student makes submission.');
16052:                     } else {
16053:                         $resulttext .= '<li>'.&mt('Submit button(s) disabled on page after student makes submission').'; ';
16054:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
16055:                             $resulttext .= &mt('durations:').'<ul>';
16056:                             foreach my $type (@types) {
16057:                                 $resulttext .= '<li>';
16058:                                 my $timeout;
16059:                                 if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
16060:                                     $timeout = $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
16061:                                 }
16062:                                 my $display;
16063:                                 if ($timeout eq '0') {
16064:                                     $display = &mt('unlimited');
16065:                                 } elsif ($timeout eq '') {
16066:                                     $display = &mt('[quant,_1,second] (default)',$staticdefaults{'postsubmit'});
16067:                                 } else {
16068:                                     $display = &mt('[quant,_1,second]',$timeout);
16069:                                 }
16070:                                 if ($type eq 'community') {
16071:                                     $resulttext .= &mt('Communities');
16072:                                 } elsif ($type eq 'official') {
16073:                                     $resulttext .= &mt('Official courses');
16074:                                 } elsif ($type eq 'unofficial') {
16075:                                     $resulttext .= &mt('Unofficial courses');
16076:                                 } elsif ($type eq 'textbook') {
16077:                                     $resulttext .= &mt('Textbook courses');
16078:                                 }
16079:                                 $resulttext .= ' -- '.$display.'</li>';
16080:                             }
16081:                             $resulttext .= '</ul>';
16082:                         }
16083:                         $resulttext .= '</li>';
16084:                     }
16085:                 } elsif ($item eq 'coursecredits') {
16086:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
16087:                         if (($domdefaults{'officialcredits'} eq '') &&
16088:                             ($domdefaults{'unofficialcredits'} eq '') &&
16089:                             ($domdefaults{'textbookcredits'} eq '')) {
16090:                             $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
16091:                         } else {
16092:                             $resulttext .= '<li>'.&mt('Student credits can be set per course by a Domain Coordinator, with the following defaults applying:').'<ul>'.
16093:                                            '<li>'.&mt('Official courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'official'}).'</li>'.
16094:                                            '<li>'.&mt('Unofficial courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'unofficial'}).'</li>'.
16095:                                            '<li>'.&mt('Textbook courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'textbook'}).'</li>'.
16096:                                            '</ul>'.
16097:                                            '</li>';
16098:                         }
16099:                     } else {
16100:                         $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
16101:                     }
16102:                 } elsif ($item eq 'canclone') {
16103:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
16104:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
16105:                             my $clonecodes = join(' '.&mt('and').' ',@{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}});
16106:                             $resulttext .= '<li>'.&mt('By default, official courses can be cloned from existing courses with the same: [_1]','<b>'.$clonecodes.'</b>').'</li>';
16107:                         }
16108:                     } elsif ($defaultshash{'coursedefaults'}{'canclone'} eq 'domain') {
16109:                         $resulttext .= '<li>'.&mt('By default, a course requester can clone any course from his/her domain.').'</li>';
16110:                     } else {
16111:                         $resulttext .= '<li>'.&mt('By default, only course owner and coordinators may clone a course.').'</li>';
16112:                     }
16113:                 }
16114:             }
16115:             $resulttext .= '</ul>';
16116:         } else {
16117:             $resulttext = &mt('No changes made to course defaults');
16118:         }
16119:     } else {
16120:         $resulttext = '<span class="LC_error">'.
16121:             &mt('An error occurred: [_1]',$putresult).'</span>';
16122:     }
16123:     return $resulttext;
16124: }
16125: 
16126: sub modify_selfenrollment {
16127:     my ($dom,$lastactref,%domconfig) = @_;
16128:     my ($resulttext,$errors,%changes,%selfenrollhash,%ordered);
16129:     my @types = ('official','unofficial','community','textbook');
16130:     my %titles = &tool_titles();
16131:     my %descs = &Apache::lonuserutils::selfenroll_default_descs();
16132:     ($ordered{'admin'},my $titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
16133:     $ordered{'default'} = ['types','registered','approval','limit'];
16134: 
16135:     my (%roles,%shown,%toplevel);
16136:     $roles{'0'} = &Apache::lonnet::plaintext('dc');
16137: 
16138:     if (ref($domconfig{'selfenrollment'}) ne 'HASH') {
16139:         if ($domconfig{'selfenrollment'} eq '') {
16140:             $domconfig{'selfenrollment'} = {};
16141:         }
16142:     }
16143:     %toplevel = (
16144:                   admin      => 'Configuration Rights',
16145:                   default    => 'Default settings',
16146:                   validation => 'Validation of self-enrollment requests',
16147:                 );
16148:     my ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
16149: 
16150:     if (ref($ordered{'admin'}) eq 'ARRAY') {
16151:         foreach my $item (@{$ordered{'admin'}}) {
16152:             foreach my $type (@types) {
16153:                 if ($env{'form.selfenrolladmin_'.$item.'_'.$type}) {
16154:                     $selfenrollhash{'admin'}{$type}{$item} = 1;
16155:                 } else {
16156:                     $selfenrollhash{'admin'}{$type}{$item} = 0;
16157:                 }
16158:                 if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
16159:                     if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
16160:                         if ($selfenrollhash{'admin'}{$type}{$item} ne
16161:                             $domconfig{'selfenrollment'}{'admin'}{$type}{$item})  {
16162:                             push(@{$changes{'admin'}{$type}},$item);
16163:                         }
16164:                     } else {
16165:                         if (!$selfenrollhash{'admin'}{$type}{$item}) {
16166:                             push(@{$changes{'admin'}{$type}},$item);
16167:                         }
16168:                     }
16169:                 } elsif (!$selfenrollhash{'admin'}{$type}{$item}) {
16170:                     push(@{$changes{'admin'}{$type}},$item);
16171:                 }
16172:             }
16173:         }
16174:     }
16175: 
16176:     foreach my $item (@{$ordered{'default'}}) {
16177:         foreach my $type (@types) {
16178:             my $value = $env{'form.selfenrolldefault_'.$item.'_'.$type};
16179:             if ($item eq 'types') {
16180:                 unless (($value eq 'all') || ($value eq 'dom')) {
16181:                     $value = '';
16182:                 }
16183:             } elsif ($item eq 'registered') {
16184:                 unless ($value eq '1') {
16185:                     $value = 0;
16186:                 }
16187:             } elsif ($item eq 'approval') {
16188:                 unless ($value =~ /^[012]$/) {
16189:                     $value = 0;
16190:                 }
16191:             } else {
16192:                 unless (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
16193:                     $value = 'none';
16194:                 }
16195:             }
16196:             $selfenrollhash{'default'}{$type}{$item} = $value;
16197:             if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
16198:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
16199:                     if ($selfenrollhash{'default'}{$type}{$item} ne
16200:                          $domconfig{'selfenrollment'}{'default'}{$type}{$item})  {
16201:                          push(@{$changes{'default'}{$type}},$item);
16202:                     }
16203:                 } else {
16204:                     push(@{$changes{'default'}{$type}},$item);
16205:                 }
16206:             } else {
16207:                 push(@{$changes{'default'}{$type}},$item);
16208:             }
16209:             if ($item eq 'limit') {
16210:                 if (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
16211:                     $env{'form.selfenrolldefault_cap_'.$type} =~ s/\D//g;
16212:                     if ($env{'form.selfenrolldefault_cap_'.$type} ne '') {
16213:                         $selfenrollhash{'default'}{$type}{'cap'} = $env{'form.selfenrolldefault_cap_'.$type};
16214:                     }
16215:                 } else {
16216:                     $selfenrollhash{'default'}{$type}{'cap'} = '';
16217:                 }
16218:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
16219:                     if ($selfenrollhash{'default'}{$type}{'cap'} ne
16220:                          $domconfig{'selfenrollment'}{'admin'}{$type}{'cap'})  {
16221:                          push(@{$changes{'default'}{$type}},'cap');
16222:                     }
16223:                 } elsif ($selfenrollhash{'default'}{$type}{'cap'} ne '') {
16224:                     push(@{$changes{'default'}{$type}},'cap');
16225:                 }
16226:             }
16227:         }
16228:     }
16229: 
16230:     foreach my $item (@{$itemsref}) {
16231:         if ($item eq 'fields') {
16232:             my @changed;
16233:             @{$selfenrollhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.selfenroll_validation_'.$item);
16234:             if (@{$selfenrollhash{'validation'}{$item}} > 0) {
16235:                 @{$selfenrollhash{'validation'}{$item}} = sort(@{$selfenrollhash{'validation'}{$item}});
16236:             }
16237:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
16238:                 if (ref($domconfig{'selfenrollment'}{'validation'}{$item}) eq 'ARRAY') {
16239:                     @changed = &Apache::loncommon::compare_arrays($selfenrollhash{'validation'}{$item},
16240:                                                                   $domconfig{'selfenrollment'}{'validation'}{$item});
16241:                 } else {
16242:                     @changed = @{$selfenrollhash{'validation'}{$item}};
16243:                 }
16244:             } else {
16245:                 @changed = @{$selfenrollhash{'validation'}{$item}};
16246:             }
16247:             if (@changed) {
16248:                 if ($selfenrollhash{'validation'}{$item}) { 
16249:                     $changes{'validation'}{$item} = join(', ',@{$selfenrollhash{'validation'}{$item}});
16250:                 } else {
16251:                     $changes{'validation'}{$item} = &mt('None');
16252:                 }
16253:             }
16254:         } else {
16255:             $selfenrollhash{'validation'}{$item} = $env{'form.selfenroll_validation_'.$item};
16256:             if ($item eq 'markup') {
16257:                if ($env{'form.selfenroll_validation_'.$item}) {
16258:                    $env{'form.selfenroll_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
16259:                }
16260:             }
16261:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
16262:                 if ($domconfig{'selfenrollment'}{'validation'}{$item} ne $selfenrollhash{'validation'}{$item}) {
16263:                     $changes{'validation'}{$item} = $selfenrollhash{'validation'}{$item};
16264:                 }
16265:             }
16266:         }
16267:     }
16268: 
16269:     my $putresult = &Apache::lonnet::put_dom('configuration',{'selfenrollment' => \%selfenrollhash},
16270:                                              $dom);
16271:     if ($putresult eq 'ok') {
16272:         if (keys(%changes) > 0) {
16273:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
16274:             $resulttext = &mt('Changes made:').'<ul>';
16275:             foreach my $key ('admin','default','validation') {
16276:                 if (ref($changes{$key}) eq 'HASH') {
16277:                     $resulttext .= '<li>'.$toplevel{$key}.'<ul>';
16278:                     if ($key eq 'validation') {
16279:                         foreach my $item (@{$itemsref}) {
16280:                             if (exists($changes{$key}{$item})) {
16281:                                 if ($item eq 'markup') {
16282:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
16283:                                                               '<br /><pre>'.$changes{$key}{$item}.'</pre>').'</li>';
16284:                                 } else {  
16285:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
16286:                                                               '<b>'.$changes{$key}{$item}.'</b>').'</li>';
16287:                                 }
16288:                             }
16289:                         }
16290:                     } else {
16291:                         foreach my $type (@types) {
16292:                             if ($type eq 'community') {
16293:                                 $roles{'1'} = &mt('Community personnel');
16294:                             } else {
16295:                                 $roles{'1'} = &mt('Course personnel');
16296:                             }
16297:                             if (ref($changes{$key}{$type}) eq 'ARRAY') {
16298:                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') {
16299:                                     if ($key eq 'admin') {
16300:                                         my @mgrdc = ();
16301:                                         if (ref($ordered{$key}) eq 'ARRAY') {
16302:                                             foreach my $item (@{$ordered{'admin'}}) {
16303:                                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') { 
16304:                                                     if ($selfenrollhash{$key}{$type}{$item} eq '0') {
16305:                                                         push(@mgrdc,$item);
16306:                                                     }
16307:                                                 }
16308:                                             }
16309:                                             if (@mgrdc) {
16310:                                                 $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
16311:                                             } else {
16312:                                                 delete($domdefaults{$type.'selfenrolladmdc'});
16313:                                             }
16314:                                         }
16315:                                     } else {
16316:                                         if (ref($ordered{$key}) eq 'ARRAY') {
16317:                                             foreach my $item (@{$ordered{$key}}) {
16318:                                                 if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
16319:                                                     $domdefaults{$type.'selfenroll'.$item} =
16320:                                                         $selfenrollhash{$key}{$type}{$item};
16321:                                                 }
16322:                                             }
16323:                                         }
16324:                                     }
16325:                                 }
16326:                                 $resulttext .= '<li>'.$titles{$type}.'<ul>';
16327:                                 foreach my $item (@{$ordered{$key}}) {
16328:                                     if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
16329:                                         $resulttext .= '<li>';
16330:                                         if ($key eq 'admin') {
16331:                                             $resulttext .= &mt('[_1] -- management by: [_2]',$titlesref->{$item},
16332:                                                                '<b>'.$roles{$selfenrollhash{'admin'}{$type}{$item}}.'</b>');
16333:                                         } else {
16334:                                             $resulttext .= &mt('[_1] set to: [_2]',$titlesref->{$item},
16335:                                                                '<b>'.$descs{$item}{$selfenrollhash{'default'}{$type}{$item}}.'</b>');
16336:                                         }
16337:                                         $resulttext .= '</li>';
16338:                                     }
16339:                                 }
16340:                                 $resulttext .= '</ul></li>';
16341:                             }
16342:                         }
16343:                         $resulttext .= '</ul></li>'; 
16344:                     }
16345:                 }
16346:             }
16347:             if ((exists($changes{'admin'})) || (exists($changes{'default'}))) {
16348:                 my $cachetime = 24*60*60;
16349:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
16350:                 if (ref($lastactref) eq 'HASH') {
16351:                     $lastactref->{'domdefaults'} = 1;
16352:                 }
16353:             }
16354:             $resulttext .= '</ul>';
16355:         } else {
16356:             $resulttext = &mt('No changes made to self-enrollment settings');
16357:         }
16358:     } else {
16359:         $resulttext = '<span class="LC_error">'.
16360:             &mt('An error occurred: [_1]',$putresult).'</span>';
16361:     }
16362:     return $resulttext;
16363: }
16364: 
16365: sub modify_wafproxy {
16366:     my ($dom,$action,$lastactref,%domconfig) = @_;
16367:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
16368:     my (%othercontrol,%canset,%values,%curralias,%currsaml,%currvalue,@warnings,
16369:         %wafproxy,%changes,%expirecache,%expiresaml);
16370:     foreach my $server (sort(keys(%servers))) {
16371:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
16372:         if ($serverhome eq $server) {
16373:             my $serverdom = &Apache::lonnet::host_domain($server);
16374:             if ($serverdom eq $dom) {
16375:                 $canset{$server} = 1;
16376:             }
16377:         }
16378:     }
16379:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
16380:         %{$values{$dom}} = ();
16381:         if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
16382:             %curralias = %{$domconfig{'wafproxy'}{'alias'}};
16383:         }
16384:         if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
16385:             %currsaml = %{$domconfig{'wafproxy'}{'saml'}};
16386:         }
16387:         foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
16388:             $currvalue{$item} = $domconfig{'wafproxy'}{$item};
16389:         }
16390:     }
16391:     my $output;
16392:     if (keys(%canset)) {
16393:         %{$wafproxy{'alias'}} = ();
16394:         %{$wafproxy{'saml'}} = ();
16395:         foreach my $key (sort(keys(%canset))) {
16396:             if ($env{'form.wafproxy_'.$dom}) {
16397:                 $wafproxy{'alias'}{$key} = $env{'form.wafproxy_alias_'.$key};
16398:                 $wafproxy{'alias'}{$key} =~ s/^\s+|\s+$//g;
16399:                 if ($wafproxy{'alias'}{$key} ne $curralias{$key}) {
16400:                     $changes{'alias'} = 1;
16401:                 }
16402:                 if ($env{'form.wafproxy_alias_saml_'.$key}) {
16403:                     $wafproxy{'saml'}{$key} = 1;
16404:                 }
16405:                 if ($wafproxy{'saml'}{$key} ne $currsaml{$key}) {
16406:                     $changes{'saml'} = 1;
16407:                 }
16408:             } else {
16409:                 $wafproxy{'alias'}{$key} = '';
16410:                 $wafproxy{'saml'}{$key} = '';
16411:                 if ($curralias{$key}) {
16412:                     $changes{'alias'} = 1;
16413:                 }
16414:                 if ($currsaml{$key}) {
16415:                     $changes{'saml'} = 1;
16416:                 }
16417:             }
16418:             if ($wafproxy{'alias'}{$key} eq '') {
16419:                 if ($curralias{$key}) {
16420:                     $expirecache{$key} = 1;
16421:                 }
16422:                 delete($wafproxy{'alias'}{$key});
16423:             }
16424:             if ($wafproxy{'saml'}{$key} eq '') {
16425:                 if ($currsaml{$key}) {
16426:                     $expiresaml{$key} = 1;
16427:                 }
16428:                 delete($wafproxy{'saml'}{$key});
16429:             }
16430:         }
16431:         unless (keys(%{$wafproxy{'alias'}})) {
16432:             delete($wafproxy{'alias'});
16433:         }
16434:         unless (keys(%{$wafproxy{'saml'}})) {
16435:             delete($wafproxy{'saml'});
16436:         }
16437:         # Localization for values in %warn occurs in &mt() calls separately.
16438:         my %warn = (
16439:                      trusted => 'trusted IP range(s)',
16440:                      vpnint => 'internal IP range(s) for VPN sessions(s)',
16441:                      vpnext => 'IP range(s) for backend WAF connections',
16442:                    );
16443:         foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
16444:             my $possible = $env{'form.wafproxy_'.$item};
16445:             $possible =~ s/^\s+|\s+$//g;
16446:             if ($possible ne '') {
16447:                 if ($item eq 'remoteip') {
16448:                     if ($possible =~ /^[mhn]$/) {
16449:                         $wafproxy{$item} = $possible;
16450:                     }
16451:                 } elsif ($item eq 'ipheader') {
16452:                     if ($wafproxy{'remoteip'} eq 'h') {
16453:                         $wafproxy{$item} = $possible;
16454:                     }
16455:                 } elsif ($item eq 'sslopt') {
16456:                     if ($possible =~ /^0|1$/) {
16457:                         $wafproxy{$item} = $possible;
16458:                     }
16459:                 } else {
16460:                     my (@ok,$count);
16461:                     if (($item eq 'vpnint') || ($item eq 'vpnext')) {
16462:                         unless ($env{'form.wafproxy_vpnaccess'}) {
16463:                             $possible = '';
16464:                         }
16465:                     } elsif ($item eq 'trusted') {
16466:                         unless ($wafproxy{'remoteip'} eq 'h') {
16467:                             $possible = '';
16468:                         }
16469:                     }
16470:                     unless ($possible eq '') {
16471:                         $possible =~ s/[\r\n]+/\s/g;
16472:                         $possible =~ s/\s*-\s*/-/g;
16473:                         $possible =~ s/\s+/,/g;
16474:                         $possible =~ s/,+/,/g;
16475:                     }
16476:                     $count = 0;
16477:                     if ($possible ne '') {
16478:                         foreach my $poss (split(/\,/,$possible)) {
16479:                             $count ++;
16480:                             $poss = &validate_ip_pattern($poss);
16481:                             if ($poss ne '') {
16482:                                 push(@ok,$poss);
16483:                             }
16484:                         }
16485:                         my $diff = $count - scalar(@ok);
16486:                         if ($diff) {
16487:                             push(@warnings,'<li>'.
16488:                                  &mt('[quant,_1,IP] invalid and excluded from saved value for [_2]',
16489:                                      $diff,$warn{$item}).
16490:                                  '</li>');
16491:                         }
16492:                         if (@ok) {
16493:                             my @cidr_list;
16494:                             foreach my $item (@ok) {
16495:                                 @cidr_list = &Net::CIDR::cidradd($item,@cidr_list);
16496:                             }
16497:                             $wafproxy{$item} = join(',',@cidr_list);
16498:                         }
16499:                     }
16500:                 }
16501:                 if ($wafproxy{$item} ne $currvalue{$item}) {
16502:                     $changes{$item} = 1;
16503:                 }
16504:             } elsif ($currvalue{$item}) {
16505:                 $changes{$item} = 1;
16506:             }
16507:         }
16508:     } else {
16509:         if (keys(%curralias)) {
16510:             $changes{'alias'} = 1;
16511:         }
16512:         if (keys(%currsaml)) {
16513:             $changes{'saml'} = 1;
16514:         }
16515:         if (keys(%currvalue)) {
16516:             foreach my $key (keys(%currvalue)) {
16517:                 $changes{$key} = 1;
16518:             }
16519:         }
16520:     }
16521:     if (keys(%changes)) {
16522:         my %defaultshash = (
16523:                               wafproxy => \%wafproxy,
16524:                            );
16525:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
16526:                                                  $dom);
16527:         if ($putresult eq 'ok') {
16528:             my $cachetime = 24*60*60;
16529:             my (%domdefaults,$updatedomdefs);
16530:             foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
16531:                 if ($changes{$item}) {
16532:                     unless ($updatedomdefs) {
16533:                         %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
16534:                         $updatedomdefs = 1;
16535:                     }
16536:                     if ($wafproxy{$item}) {
16537:                         $domdefaults{'waf_'.$item} = $wafproxy{$item};
16538:                     } elsif (exists($domdefaults{'waf_'.$item})) {
16539:                         delete($domdefaults{'waf_'.$item});
16540:                     }
16541:                 }
16542:             }
16543:             if ($updatedomdefs) {
16544:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
16545:                 if (ref($lastactref) eq 'HASH') {
16546:                     $lastactref->{'domdefaults'} = 1;
16547:                 }
16548:             }
16549:             if ((exists($wafproxy{'alias'})) || (keys(%expirecache))) {
16550:                 my %updates = %expirecache;
16551:                 foreach my $key (keys(%expirecache)) {
16552:                     &Apache::lonnet::devalidate_cache_new('proxyalias',$key);
16553:                 }
16554:                 if (ref($wafproxy{'alias'}) eq 'HASH') {
16555:                     my $cachetime = 24*60*60;
16556:                     foreach my $key (keys(%{$wafproxy{'alias'}})) {
16557:                         $updates{$key} = 1;
16558:                         &Apache::lonnet::do_cache_new('proxyalias',$key,$wafproxy{'alias'}{$key},
16559:                                                       $cachetime);
16560:                     }
16561:                 }
16562:                 if (ref($lastactref) eq 'HASH') {
16563:                     $lastactref->{'proxyalias'} = \%updates;
16564:                 }
16565:             }
16566:             if ((exists($wafproxy{'saml'})) || (keys(%expiresaml))) {
16567:                 my %samlupdates = %expiresaml;
16568:                 foreach my $key (keys(%expiresaml)) {
16569:                     &Apache::lonnet::devalidate_cache_new('proxysaml',$key);
16570:                 }
16571:                 if (ref($wafproxy{'saml'}) eq 'HASH') {
16572:                     my $cachetime = 24*60*60;
16573:                     foreach my $key (keys(%{$wafproxy{'saml'}})) {
16574:                         $samlupdates{$key} = 1;
16575:                         &Apache::lonnet::do_cache_new('proxysaml',$key,$wafproxy{'saml'}{$key},
16576:                                                       $cachetime);
16577:                     }
16578:                 }
16579:                 if (ref($lastactref) eq 'HASH') {
16580:                     $lastactref->{'proxysaml'} = \%samlupdates;
16581:                 }
16582:             }
16583:             $output = &mt('Changes were made to Web Application Firewall/Reverse Proxy').'<ul>';
16584:             foreach my $item ('alias','saml','remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
16585:                 if ($changes{$item}) {
16586:                     if ($item eq 'alias') {
16587:                         my $numaliased = 0;
16588:                         if (ref($wafproxy{'alias'}) eq 'HASH') {
16589:                             my $shown;
16590:                             if (keys(%{$wafproxy{'alias'}})) {
16591:                                 foreach my $server (sort(keys(%{$wafproxy{'alias'}}))) {
16592:                                     $shown .= '<li>'.&mt('[_1] aliased by [_2]',
16593:                                                          &Apache::lonnet::hostname($server),
16594:                                                          $wafproxy{'alias'}{$server}).'</li>';
16595:                                     $numaliased ++;
16596:                                 }
16597:                                 if ($numaliased) {
16598:                                     $output .= '<li>'.&mt('Aliases for hostnames set to: [_1]',
16599:                                                           '<ul>'.$shown.'</ul>').'</li>';
16600:                                 }
16601:                             }
16602:                         }
16603:                         unless ($numaliased) {
16604:                             $output .= '<li>'.&mt('Aliases deleted for hostnames').'</li>';
16605:                         }
16606:                     } elsif ($item eq 'saml') {
16607:                         my $shown;
16608:                         if (ref($wafproxy{'saml'}) eq 'HASH') {
16609:                             if (keys(%{$wafproxy{'saml'}})) {
16610:                                 $shown = join(', ',sort(keys(%{$wafproxy{'saml'}})));
16611:                             }
16612:                         }
16613:                         if ($shown) {
16614:                             $output .= '<li>'.&mt('Alias used by SSO Auth for: [_1]',
16615:                                                   $shown).'</li>';
16616:                         } else {
16617:                             $output .= '<li>'.&mt('No alias used for SSO Auth').'</li>';
16618:                         }
16619:                     } else {
16620:                         if ($item eq 'remoteip') {
16621:                             my %ip_methods = &remoteip_methods();
16622:                             if ($wafproxy{$item} =~ /^[mh]$/) {
16623:                                 $output .= '<li>'.&mt("Method for determining user's IP set to: [_1]",
16624:                                                       $ip_methods{$wafproxy{$item}}).'</li>';
16625:                             } else {
16626:                                 if (($env{'form.wafproxy_'.$dom}) && (ref($wafproxy{'alias'}) eq 'HASH')) {
16627:                                     $output .= '<li>'.&mt("No method in use to get user's real IP (will report IP used by WAF).").
16628:                                                '</li>';
16629:                                 } else {
16630:                                     $output .= '<li>'.&mt('WAF/Reverse Proxy not in use').'</li>';
16631:                                 }
16632:                             }
16633:                         } elsif ($item eq 'ipheader') {
16634:                             if ($wafproxy{$item}) {
16635:                                 $output .= '<li>'.&mt('Request header with remote IP set to: [_1]',
16636:                                                       $wafproxy{$item}).'</li>';
16637:                             } else {
16638:                                 $output .= '<li>'.&mt('Request header with remote IP deleted').'</li>';
16639:                             }
16640:                         } elsif ($item eq 'trusted') {
16641:                             if ($wafproxy{$item}) {
16642:                                 $output .= '<li>'.&mt('Trusted IP range(s) set to: [_1]',
16643:                                                       $wafproxy{$item}).'</li>';
16644:                             } else {
16645:                                 $output .= '<li>'.&mt('Trusted IP range(s) deleted').'</li>';
16646:                             }
16647:                         } elsif ($item eq 'vpnint') {
16648:                             if ($wafproxy{$item}) {
16649:                                 $output .= '<li>'.&mt('Internal IP Range(s) for VPN sessions set to: [_1]',
16650:                                                        $wafproxy{$item}).'</li>';
16651:                             } else {
16652:                                 $output .= '<li>'.&mt('Internal IP Range(s) for VPN sessions deleted').'</li>';
16653:                             }
16654:                         } elsif ($item eq 'vpnext') {
16655:                             if ($wafproxy{$item}) {
16656:                                 $output .= '<li>'.&mt('IP Range(s) for backend WAF connections set to: [_1]',
16657:                                                        $wafproxy{$item}).'</li>';
16658:                             } else {
16659:                                 $output .= '<li>'.&mt('IP Range(s) for backend WAF connections deleted').'</li>';
16660:                             }
16661:                         } elsif ($item eq 'sslopt') {
16662:                             if ($wafproxy{$item}) {
16663:                                 $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>';
16664:                             } else {
16665:                                 $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>';
16666:                             }
16667:                         }
16668:                     }
16669:                 }
16670:             }
16671:             $output .= '</ul>';
16672:         } else {
16673:             $output = '<span class="LC_error">'.
16674:                       &mt('An error occurred: [_1]',$putresult).'</span>';
16675:         }
16676:     } elsif (keys(%canset)) {
16677:         $output = &mt('No changes made to Web Application Firewall/Reverse Proxy settings');
16678:     }
16679:     if (@warnings) {
16680:         $output .= '<br />'.&mt('Warnings:').'<ul>'.
16681:                        join("\n",@warnings).'</ul>';
16682:     }
16683:     return $output;
16684: }
16685: 
16686: sub validate_ip_pattern {
16687:     my ($pattern) = @_;
16688:     if ($pattern =~ /^([^-]+)\-([^-]+)$/) {
16689:         my ($start,$end) = ($1,$2);
16690:         if ((&Net::CIDR::cidrvalidate($start)) && (&Net::CIDR::cidrvalidate($end))) {
16691:             if (($start !~ m{/}) && ($end !~ m{/})) {
16692:                 return $start.'-'.$end;
16693:             }
16694:         }
16695:     } elsif ($pattern ne '') {
16696:         $pattern = &Net::CIDR::cidrvalidate($pattern);
16697:         if ($pattern ne '') {
16698:             return $pattern;
16699:         }
16700:     }
16701:     return;
16702: }
16703: 
16704: sub modify_usersessions {
16705:     my ($dom,$lastactref,%domconfig) = @_;
16706:     my @hostingtypes = ('version','excludedomain','includedomain');
16707:     my @offloadtypes = ('primary','default');
16708:     my %types = (
16709:                   remote => \@hostingtypes,
16710:                   hosted => \@hostingtypes,
16711:                   spares => \@offloadtypes,
16712:                 );
16713:     my @prefixes = ('remote','hosted','spares');
16714:     my @lcversions = &Apache::lonnet::all_loncaparevs();
16715:     my (%by_ip,%by_location,@intdoms);
16716:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location);
16717:     my @locations = sort(keys(%by_location));
16718:     my (%defaultshash,%changes);
16719:     foreach my $prefix (@prefixes) {
16720:         $defaultshash{'usersessions'}{$prefix} = {};
16721:     }
16722:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
16723:     my $resulttext;
16724:     my %iphost = &Apache::lonnet::get_iphost();
16725:     foreach my $prefix (@prefixes) {
16726:         next if ($prefix eq 'spares');
16727:         foreach my $type (@{$types{$prefix}}) {
16728:             my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
16729:             if ($type eq 'version') {
16730:                 my $value = $env{'form.'.$prefix.'_'.$type};
16731:                 my $okvalue;
16732:                 if ($value ne '') {
16733:                     if (grep(/^\Q$value\E$/,@lcversions)) {
16734:                         $okvalue = $value;
16735:                     }
16736:                 }
16737:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
16738:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
16739:                         if ($domconfig{'usersessions'}{$prefix}{$type} ne '') {
16740:                             if ($inuse == 0) {
16741:                                 $changes{$prefix}{$type} = 1;
16742:                             } else {
16743:                                 if ($okvalue ne $domconfig{'usersessions'}{$prefix}{$type}) {
16744:                                     $changes{$prefix}{$type} = 1;
16745:                                 }
16746:                                 if ($okvalue ne '') {
16747:                                     $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
16748:                                 } 
16749:                             }
16750:                         } else {
16751:                             if (($inuse == 1) && ($okvalue ne '')) {
16752:                                 $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
16753:                                 $changes{$prefix}{$type} = 1;
16754:                             }
16755:                         }
16756:                     } else {
16757:                         if (($inuse == 1) && ($okvalue ne '')) {
16758:                             $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
16759:                             $changes{$prefix}{$type} = 1;
16760:                         }
16761:                     }
16762:                 } else {
16763:                     if (($inuse == 1) && ($okvalue ne '')) {
16764:                         $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
16765:                         $changes{$prefix}{$type} = 1;
16766:                     }
16767:                 }
16768:             } else {
16769:                 my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
16770:                 my @okvals;
16771:                 foreach my $val (@vals) {
16772:                     if ($val =~ /:/) {
16773:                         my @items = split(/:/,$val);
16774:                         foreach my $item (@items) {
16775:                             if (ref($by_location{$item}) eq 'ARRAY') {
16776:                                 push(@okvals,$item);
16777:                             }
16778:                         }
16779:                     } else {
16780:                         if (ref($by_location{$val}) eq 'ARRAY') {
16781:                             push(@okvals,$val);
16782:                         }
16783:                     }
16784:                 }
16785:                 @okvals = sort(@okvals);
16786:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
16787:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
16788:                         if (ref($domconfig{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
16789:                             if ($inuse == 0) {
16790:                                 $changes{$prefix}{$type} = 1; 
16791:                             } else {
16792:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
16793:                                 my @changed = &Apache::loncommon::compare_arrays($domconfig{'usersessions'}{$prefix}{$type},$defaultshash{'usersessions'}{$prefix}{$type});
16794:                                 if (@changed > 0) {
16795:                                     $changes{$prefix}{$type} = 1;
16796:                                 }
16797:                             }
16798:                         } else {
16799:                             if ($inuse == 1) {
16800:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
16801:                                 $changes{$prefix}{$type} = 1;
16802:                             }
16803:                         } 
16804:                     } else {
16805:                         if ($inuse == 1) {
16806:                             $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
16807:                             $changes{$prefix}{$type} = 1;
16808:                         }
16809:                     }
16810:                 } else {
16811:                     if ($inuse == 1) {
16812:                         $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
16813:                         $changes{$prefix}{$type} = 1;
16814:                     }
16815:                 }
16816:             }
16817:         }
16818:     }
16819: 
16820:     my @alldoms = &Apache::lonnet::all_domains();
16821:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
16822:     my %spareid = &current_offloads_to($dom,$domconfig{'usersessions'},\%servers);
16823:     my $savespares;
16824: 
16825:     foreach my $lonhost (sort(keys(%servers))) {
16826:         my $serverhomeID =
16827:             &Apache::lonnet::get_server_homeID($servers{$lonhost});
16828:         my $serverhostname = &Apache::lonnet::hostname($lonhost);
16829:         $defaultshash{'usersessions'}{'spares'}{$lonhost} = {};
16830:         my %spareschg;
16831:         foreach my $type (@{$types{'spares'}}) {
16832:             my @okspares;
16833:             my @checked = &Apache::loncommon::get_env_multiple('form.spare_'.$type.'_'.$lonhost);
16834:             foreach my $server (@checked) {
16835:                 if (&Apache::lonnet::hostname($server) ne '') {
16836:                     unless (&Apache::lonnet::hostname($server) eq $serverhostname) {
16837:                         unless (grep(/^\Q$server\E$/,@okspares)) {
16838:                             push(@okspares,$server);
16839:                         }
16840:                     }
16841:                 }
16842:             }
16843:             my $new = $env{'form.newspare_'.$type.'_'.$lonhost};
16844:             my $newspare;
16845:             if (($new ne '') && (&Apache::lonnet::hostname($new))) {
16846:                 unless (&Apache::lonnet::hostname($new) eq $serverhostname) {
16847:                     $newspare = $new;
16848:                 }
16849:             }
16850:             my @spares;
16851:             if (($newspare ne '') && (!grep(/^\Q$newspare\E$/,@okspares))) {
16852:                 @spares = sort(@okspares,$newspare);
16853:             } else {
16854:                 @spares = sort(@okspares);
16855:             }
16856:             $defaultshash{'usersessions'}{'spares'}{$lonhost}{$type} = \@spares;
16857:             if (ref($spareid{$lonhost}) eq 'HASH') {
16858:                 if (ref($spareid{$lonhost}{$type}) eq 'ARRAY') {
16859:                     my @diffs = &Apache::loncommon::compare_arrays($spareid{$lonhost}{$type},\@spares);
16860:                     if (@diffs > 0) {
16861:                         $spareschg{$type} = 1;
16862:                     }
16863:                 }
16864:             }
16865:         }
16866:         if (keys(%spareschg) > 0) {
16867:             $changes{'spares'}{$lonhost} = \%spareschg;
16868:         }
16869:     }
16870:     $defaultshash{'usersessions'}{'offloadnow'} = {};
16871:     $defaultshash{'usersessions'}{'offloadoth'} = {};
16872:     my @offloadnow = &Apache::loncommon::get_env_multiple('form.offloadnow');
16873:     my @okoffload;
16874:     if (@offloadnow) {
16875:         foreach my $server (@offloadnow) {
16876:             if (&Apache::lonnet::hostname($server) ne '') {
16877:                 unless (grep(/^\Q$server\E$/,@okoffload)) {
16878:                     push(@okoffload,$server);
16879:                 }
16880:             }
16881:         }
16882:         if (@okoffload) {
16883:             foreach my $lonhost (@okoffload) {
16884:                 $defaultshash{'usersessions'}{'offloadnow'}{$lonhost} = 1;
16885:             }
16886:         }
16887:     }
16888:     my @offloadoth = &Apache::loncommon::get_env_multiple('form.offloadoth');
16889:     my @okoffloadoth;
16890:     if (@offloadoth) {
16891:         foreach my $server (@offloadoth) {
16892:             if (&Apache::lonnet::hostname($server) ne '') {
16893:                 unless (grep(/^\Q$server\E$/,@okoffloadoth)) {
16894:                     push(@okoffloadoth,$server);
16895:                 }
16896:             }
16897:         }
16898:         if (@okoffloadoth) {
16899:             foreach my $lonhost (@okoffloadoth) {
16900:                 $defaultshash{'usersessions'}{'offloadoth'}{$lonhost} = 1;
16901:             }
16902:         }
16903:     }
16904:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
16905:         if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
16906:             if (ref($changes{'spares'}) eq 'HASH') {
16907:                 if (keys(%{$changes{'spares'}}) > 0) {
16908:                     $savespares = 1;
16909:                 }
16910:             }
16911:         } else {
16912:             $savespares = 1;
16913:         }
16914:         foreach my $offload ('offloadnow','offloadoth') {
16915:             if (ref($domconfig{'usersessions'}{$offload}) eq 'HASH') {
16916:                 foreach my $lonhost (keys(%{$domconfig{'usersessions'}{$offload}})) {
16917:                     unless ($defaultshash{'usersessions'}{$offload}{$lonhost}) {
16918:                         $changes{$offload} = 1;
16919:                         last;
16920:                     }
16921:                 }
16922:                 unless ($changes{$offload}) {
16923:                     foreach my $lonhost (keys(%{$defaultshash{'usersessions'}{$offload}})) {
16924:                         unless ($domconfig{'usersessions'}{$offload}{$lonhost}) {
16925:                             $changes{$offload} = 1;
16926:                             last;
16927:                         }
16928:                     }
16929:                 }
16930:             } else {
16931:                 if (($offload eq 'offloadnow') && (@okoffload)) {
16932:                      $changes{'offloadnow'} = 1;
16933:                 }
16934:                 if (($offload eq 'offloadoth') && (@okoffloadoth)) {
16935:                     $changes{'offloadoth'} = 1;
16936:                 }
16937:             }
16938:         }
16939:     } else {
16940:         if (@okoffload) {
16941:             $changes{'offloadnow'} = 1;
16942:         }
16943:         if (@okoffloadoth) {
16944:             $changes{'offloadoth'} = 1;
16945:         }
16946:     }
16947:     my $nochgmsg = &mt('No changes made to settings for user session hosting/offloading.');
16948:     if ((keys(%changes) > 0) || ($savespares)) {
16949:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
16950:                                                  $dom);
16951:         if ($putresult eq 'ok') {
16952:             if (ref($defaultshash{'usersessions'}) eq 'HASH') {
16953:                 if (ref($defaultshash{'usersessions'}{'remote'}) eq 'HASH') {
16954:                     $domdefaults{'remotesessions'} = $defaultshash{'usersessions'}{'remote'};
16955:                 }
16956:                 if (ref($defaultshash{'usersessions'}{'hosted'}) eq 'HASH') {
16957:                     $domdefaults{'hostedsessions'} = $defaultshash{'usersessions'}{'hosted'};
16958:                 }
16959:                 if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
16960:                     $domdefaults{'offloadnow'} = $defaultshash{'usersessions'}{'offloadnow'};
16961:                 }
16962:                 if (ref($defaultshash{'usersessions'}{'offloadoth'}) eq 'HASH') {
16963:                     $domdefaults{'offloadoth'} = $defaultshash{'usersessions'}{'offloadoth'};
16964:                 }
16965:             }
16966:             my $cachetime = 24*60*60;
16967:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
16968:             &Apache::lonnet::do_cache_new('usersessions',$dom,$defaultshash{'usersessions'},3600);
16969:             if (ref($lastactref) eq 'HASH') {
16970:                 $lastactref->{'domdefaults'} = 1;
16971:                 $lastactref->{'usersessions'} = 1;
16972:             }
16973:             if (keys(%changes) > 0) {
16974:                 my %lt = &usersession_titles();
16975:                 $resulttext = &mt('Changes made:').'<ul>';
16976:                 foreach my $prefix (@prefixes) {
16977:                     if (ref($changes{$prefix}) eq 'HASH') {
16978:                         $resulttext .= '<li>'.$lt{$prefix}.'<ul>';
16979:                         if ($prefix eq 'spares') {
16980:                             if (ref($changes{$prefix}) eq 'HASH') {
16981:                                 foreach my $lonhost (sort(keys(%{$changes{$prefix}}))) {
16982:                                     $resulttext .= '<li><b>'.$lonhost.'</b> ';
16983:                                     my $lonhostdom = &Apache::lonnet::host_domain($lonhost);
16984:                                     my $cachekey = &escape('spares').':'.&escape($lonhostdom);
16985:                                     &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
16986:                                     if (ref($changes{$prefix}{$lonhost}) eq 'HASH') {
16987:                                         foreach my $type (@{$types{$prefix}}) {
16988:                                             if ($changes{$prefix}{$lonhost}{$type}) {
16989:                                                 my $offloadto = &mt('None');
16990:                                                 if (ref($defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}) eq 'ARRAY') {
16991:                                                     if (@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}} > 0) {   
16992:                                                         $offloadto = join(', ',@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}});
16993:                                                     }
16994:                                                 }
16995:                                                 $resulttext .= &mt('[_1] set to: [_2].','<i>'.$lt{$type}.'</i>',$offloadto).('&nbsp;'x3);
16996:                                             }
16997:                                         }
16998:                                     }
16999:                                     $resulttext .= '</li>';
17000:                                 }
17001:                             }
17002:                         } else {
17003:                             foreach my $type (@{$types{$prefix}}) {
17004:                                 if (defined($changes{$prefix}{$type})) {
17005:                                     my $newvalue;
17006:                                     if (ref($defaultshash{'usersessions'}) eq 'HASH') {
17007:                                         if (ref($defaultshash{'usersessions'}{$prefix})) {
17008:                                             if ($type eq 'version') {
17009:                                                 $newvalue = $defaultshash{'usersessions'}{$prefix}{$type};
17010:                                             } elsif (ref($defaultshash{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
17011:                                                 if (@{$defaultshash{'usersessions'}{$prefix}{$type}} > 0) {
17012:                                                     $newvalue = join(', ',@{$defaultshash{'usersessions'}{$prefix}{$type}});
17013:                                                 }
17014:                                             }
17015:                                         }
17016:                                     }
17017:                                     if ($newvalue eq '') {
17018:                                         if ($type eq 'version') {
17019:                                             $resulttext .= '<li>'.&mt('[_1] set to: off',$lt{$type}).'</li>';
17020:                                         } else {
17021:                                             $resulttext .= '<li>'.&mt('[_1] set to: none',$lt{$type}).'</li>';
17022:                                         }
17023:                                     } else {
17024:                                         if ($type eq 'version') {
17025:                                             $newvalue .= ' '.&mt('(or later)'); 
17026:                                         }
17027:                                         $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$lt{$type},$newvalue).'</li>';
17028:                                     }
17029:                                 }
17030:                             }
17031:                         }
17032:                         $resulttext .= '</ul>';
17033:                     }
17034:                 }
17035:                 if ($changes{'offloadnow'}) {
17036:                     if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
17037:                         if (keys(%{$defaultshash{'usersessions'}{'offloadnow'}}) > 0) {
17038:                             $resulttext .= '<li>'.&mt('Switch any active user on next access, for server(s):').'<ul>';
17039:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadnow'}}))) {
17040:                                 $resulttext .= '<li>'.$lonhost.'</li>';
17041:                             }
17042:                             $resulttext .= '</ul>';
17043:                         } else {
17044:                             $resulttext .= '<li>'.&mt('No servers now set to switch any active user on next access.');
17045:                         }
17046:                     } else {
17047:                         $resulttext .= '<li>'.&mt('No servers now set to switch any active user on next access.').'</li>';
17048:                     }
17049:                 }
17050:                 if ($changes{'offloadoth'}) {
17051:                     if (ref($defaultshash{'usersessions'}{'offloadoth'}) eq 'HASH') {
17052:                         if (keys(%{$defaultshash{'usersessions'}{'offloadoth'}}) > 0) {
17053:                             $resulttext .= '<li>'.&mt('Switch other institutions on next access, for server(s):').'<ul>';
17054:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadoth'}}))) {
17055:                                 $resulttext .= '<li>'.$lonhost.'</li>';
17056:                             }
17057:                             $resulttext .= '</ul>';
17058:                         } else {
17059:                             $resulttext .= '<li>'.&mt('No servers now set to switch other institutions on next access.');
17060:                         }
17061:                     } else {
17062:                         $resulttext .= '<li>'.&mt('No servers now set to switch other institutions on next access.').'</li>';
17063:                     }
17064:                 }
17065:                 $resulttext .= '</ul>';
17066:             } else {
17067:                 $resulttext = $nochgmsg;
17068:             }
17069:         } else {
17070:             $resulttext = '<span class="LC_error">'.
17071:                           &mt('An error occurred: [_1]',$putresult).'</span>';
17072:         }
17073:     } else {
17074:         $resulttext = $nochgmsg;
17075:     }
17076:     return $resulttext;
17077: }
17078: 
17079: sub modify_loadbalancing {
17080:     my ($dom,%domconfig) = @_;
17081:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
17082:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
17083:     my ($othertitle,$usertypes,$types) =
17084:         &Apache::loncommon::sorted_inst_types($dom);
17085:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
17086:     my %libraryservers = &Apache::lonnet::get_servers($dom,'library');
17087:     my @sparestypes = ('primary','default');
17088:     my %typetitles = &sparestype_titles();
17089:     my $resulttext;
17090:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
17091:     if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
17092:         %existing = %{$domconfig{'loadbalancing'}};
17093:     }
17094:     &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
17095:                               \%currtargets,\%currrules,\%currcookies);
17096:     my ($saveloadbalancing,%defaultshash,%changes);
17097:     my ($alltypes,$othertypes,$titles) =
17098:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
17099:     my %ruletitles = &offloadtype_text();
17100:     my @deletions = &Apache::loncommon::get_env_multiple('form.loadbalancing_delete');
17101:     for (my $i=0; $i<$env{'form.loadbalancing_total'}; $i++) {
17102:         my $balancer = $env{'form.loadbalancing_lonhost_'.$i};
17103:         if ($balancer eq '') {
17104:             next;
17105:         }
17106:         if (!exists($servers{$balancer})) {
17107:             if (exists($currbalancer{$balancer})) {
17108:                 push(@{$changes{'delete'}},$balancer);
17109:             }
17110:             next;
17111:         }
17112:         if ((@deletions > 0) && (grep(/^\Q$i\E$/,@deletions))) {
17113:             push(@{$changes{'delete'}},$balancer);
17114:             next;
17115:         }
17116:         if (!exists($currbalancer{$balancer})) {
17117:             push(@{$changes{'add'}},$balancer);
17118:         }
17119:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'} = [];
17120:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'default'} = [];
17121:         $defaultshash{'loadbalancing'}{$balancer}{'rules'} = {};
17122:         unless (ref($domconfig{'loadbalancing'}) eq 'HASH') {
17123:             $saveloadbalancing = 1;
17124:         }
17125:         foreach my $sparetype (@sparestypes) {
17126:             my @targets = &Apache::loncommon::get_env_multiple('form.loadbalancing_target_'.$i.'_'.$sparetype);
17127:             my @offloadto;
17128:             foreach my $target (@targets) {
17129:                 if (($servers{$target}) && ($target ne $balancer)) {
17130:                     if ($sparetype eq 'default') {
17131:                         if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}) eq 'ARRAY') {
17132:                             next if (grep(/^\Q$target\E$/,@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}}));
17133:                         }
17134:                     }
17135:                     unless(grep(/^\Q$target\E$/,@offloadto)) {
17136:                         push(@offloadto,$target);
17137:                     }
17138:                 }
17139:             }
17140:             if ($env{'form.loadbalancing_target_'.$i.'_hosthere'} eq $sparetype) {
17141:                 unless(grep(/^\Q$balancer\E$/,@offloadto)) {
17142:                     push(@offloadto,$balancer);
17143:                 }
17144:             }
17145:             $defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype} = \@offloadto;
17146:         }
17147:         if ($env{'form.loadbalancing_cookie_'.$i}) {
17148:             $defaultshash{'loadbalancing'}{$balancer}{'cookie'} = 1;
17149:             if (exists($currbalancer{$balancer})) {
17150:                 unless ($currcookies{$balancer}) {
17151:                     $changes{'curr'}{$balancer}{'cookie'} = 1;
17152:                 }
17153:             }
17154:         } elsif (exists($currbalancer{$balancer})) {
17155:             if ($currcookies{$balancer}) {
17156:                 $changes{'curr'}{$balancer}{'cookie'} = 1;
17157:             }
17158:         }
17159:         if (ref($currtargets{$balancer}) eq 'HASH') {
17160:             foreach my $sparetype (@sparestypes) {
17161:                 if (ref($currtargets{$balancer}{$sparetype}) eq 'ARRAY') {
17162:                     my @targetdiffs = &Apache::loncommon::compare_arrays($currtargets{$balancer}{$sparetype},$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype});
17163:                     if (@targetdiffs > 0) {
17164:                         $changes{'curr'}{$balancer}{'targets'} = 1;
17165:                     }
17166:                 } elsif (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
17167:                     if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
17168:                         $changes{'curr'}{$balancer}{'targets'} = 1;
17169:                     }
17170:                 }
17171:             }
17172:         } else {
17173:             if (ref($defaultshash{'loadbalancing'}{$balancer}) eq 'HASH') {
17174:                 foreach my $sparetype (@sparestypes) {
17175:                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
17176:                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
17177:                             $changes{'curr'}{$balancer}{'targets'} = 1;
17178:                         }
17179:                     }
17180:                 }
17181:             }
17182:         }
17183:         my $ishomedom;
17184:         if (&Apache::lonnet::host_domain($balancer) eq $dom) {
17185:             $ishomedom = 1;
17186:         }
17187:         if (ref($alltypes) eq 'ARRAY') {
17188:             foreach my $type (@{$alltypes}) {
17189:                 my $rule;
17190:                 unless ((($type eq '_LC_external') || ($type eq '_LC_internetdom')) &&
17191:                          (!$ishomedom)) {
17192:                     $rule = $env{'form.loadbalancing_rules_'.$i.'_'.$type};
17193:                 }
17194:                 if ($rule eq 'specific') {
17195:                     my $specifiedhost = $env{'form.loadbalancing_singleserver_'.$i.'_'.$type};
17196:                     if (exists($servers{$specifiedhost})) {
17197:                         $rule = $specifiedhost;
17198:                     }
17199:                 }
17200:                 $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type} = $rule;
17201:                 if (ref($currrules{$balancer}) eq 'HASH') {
17202:                     if ($rule ne $currrules{$balancer}{$type}) {
17203:                         $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
17204:                     }
17205:                 } elsif ($rule ne '') {
17206:                     $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
17207:                 }
17208:             }
17209:         }
17210:     }
17211:     my $nochgmsg = &mt('No changes made to Load Balancer settings.');
17212:     if ((keys(%changes) > 0) || ($saveloadbalancing)) {
17213:         unless (ref($defaultshash{'loadbalancing'}) eq 'HASH') {
17214:             $defaultshash{'loadbalancing'} = {};
17215:         }
17216:         my $putresult = &Apache::lonnet::put_dom('configuration',
17217:                                                  \%defaultshash,$dom);
17218:         if ($putresult eq 'ok') {
17219:             if (keys(%changes) > 0) {
17220:                 my %toupdate;
17221:                 if (ref($changes{'delete'}) eq 'ARRAY') {
17222:                     foreach my $balancer (sort(@{$changes{'delete'}})) {
17223:                         $resulttext .= '<li>'.&mt('Load Balancing discontinued for: [_1]',$balancer).'</li>';
17224:                         $toupdate{$balancer} = 1;
17225:                     }
17226:                 }
17227:                 if (ref($changes{'add'}) eq 'ARRAY') {
17228:                     foreach my $balancer (sort(@{$changes{'add'}})) {
17229:                         $resulttext .= '<li>'.&mt('Load Balancing enabled for: [_1]',$balancer);
17230:                         $toupdate{$balancer} = 1;
17231:                     }
17232:                 }
17233:                 if (ref($changes{'curr'}) eq 'HASH') {
17234:                     foreach my $balancer (sort(keys(%{$changes{'curr'}}))) {
17235:                         $toupdate{$balancer} = 1;
17236:                         if (ref($changes{'curr'}{$balancer}) eq 'HASH') {
17237:                             if ($changes{'curr'}{$balancer}{'targets'}) {
17238:                                 my %offloadstr;
17239:                                 foreach my $sparetype (@sparestypes) {
17240:                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
17241:                                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
17242:                                             $offloadstr{$sparetype} = join(', ',@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
17243:                                         }
17244:                                     }
17245:                                 }
17246:                                 if (keys(%offloadstr) == 0) {
17247:                                     $resulttext .= '<li>'.&mt("Servers to which Load Balance server offloads set to 'None', by default").'</li>';
17248:                                 } else {
17249:                                     my $showoffload;
17250:                                     foreach my $sparetype (@sparestypes) {
17251:                                         $showoffload .= '<i>'.$typetitles{$sparetype}.'</i>:&nbsp;';
17252:                                         if (defined($offloadstr{$sparetype})) {
17253:                                             $showoffload .= $offloadstr{$sparetype};
17254:                                         } else {
17255:                                             $showoffload .= &mt('None');
17256:                                         }
17257:                                         $showoffload .= ('&nbsp;'x3);
17258:                                     }
17259:                                     $resulttext .= '<li>'.&mt('By default, Load Balancer: [_1] set to offload to - [_2]',$balancer,$showoffload).'</li>';
17260:                                 }
17261:                             }
17262:                         }
17263:                         if (ref($changes{'curr'}{$balancer}{'rules'}) eq 'HASH') {
17264:                             if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH')) {
17265:                                 foreach my $type (@{$alltypes}) {
17266:                                     if ($changes{'curr'}{$balancer}{'rules'}{$type}) {
17267:                                         my $rule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
17268:                                         my $balancetext;
17269:                                         if ($rule eq '') {
17270:                                             $balancetext =  $ruletitles{'default'};
17271:                                         } elsif (($rule eq 'homeserver') || ($rule eq 'externalbalancer') ||
17272:                                                  ($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
17273:                                             if (($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
17274:                                                 foreach my $sparetype (@sparestypes) {
17275:                                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
17276:                                                         map { $toupdate{$_} = 1; } (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
17277:                                                     }
17278:                                                 }
17279:                                                 foreach my $item (@{$alltypes}) {
17280:                                                     next if ($item =~  /^_LC_ipchange/);
17281:                                                     my $hasrule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$item};
17282:                                                     if ($hasrule eq 'homeserver') {
17283:                                                         map { $toupdate{$_} = 1; } (keys(%libraryservers));
17284:                                                     } else {
17285:                                                         unless (($hasrule eq 'default') || ($hasrule eq 'none') || ($hasrule eq 'externalbalancer')) {
17286:                                                             if ($servers{$hasrule}) {
17287:                                                                 $toupdate{$hasrule} = 1;
17288:                                                             }
17289:                                                         }
17290:                                                     }
17291:                                                 }
17292:                                                 if (($rule eq 'balancer') || ($rule eq 'offloadedto')) {
17293:                                                     $balancetext =  $ruletitles{$rule};
17294:                                                 } else {
17295:                                                     my $receiver = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
17296:                                                     $balancetext = $ruletitles{'particular'}.' '.$receiver;
17297:                                                     if ($receiver) {
17298:                                                         $toupdate{$receiver};
17299:                                                     }
17300:                                                 }
17301:                                             } else {
17302:                                                 $balancetext =  $ruletitles{$rule};
17303:                                             }
17304:                                         } else {
17305:                                             $balancetext = &mt('offload to [_1]',$defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type});
17306:                                         }
17307:                                         $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- balancing for [_2] set to - "[_3]"',$balancer,$titles->{$type},$balancetext).'</li>';
17308:                                     }
17309:                                 }
17310:                             }
17311:                         }
17312:                         if ($changes{'curr'}{$balancer}{'cookie'}) {
17313:                             if ($currcookies{$balancer}) {
17314:                                 $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- cookie use disabled',
17315:                                                           $balancer).'</li>';
17316:                             } else {
17317:                                 $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- cookie use enabled',
17318:                                                           $balancer).'</li>';
17319:                             }
17320:                         }
17321:                     }
17322:                 }
17323:                 if (keys(%toupdate)) {
17324:                     my %thismachine;
17325:                     my $updatedhere;
17326:                     my $cachetime = 60*60*24;
17327:                     map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
17328:                     foreach my $lonhost (keys(%toupdate)) {
17329:                         if ($thismachine{$lonhost}) {
17330:                             unless ($updatedhere) {
17331:                                 &Apache::lonnet::do_cache_new('loadbalancing',$dom,
17332:                                                               $defaultshash{'loadbalancing'},
17333:                                                               $cachetime);
17334:                                 $updatedhere = 1;
17335:                             }
17336:                         } else {
17337:                             my $cachekey = &escape('loadbalancing').':'.&escape($dom);
17338:                             &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
17339:                         }
17340:                     }
17341:                 }
17342:                 if ($resulttext ne '') {
17343:                     $resulttext = &mt('Changes made:').'<ul>'.$resulttext.'</ul>';
17344:                 } else {
17345:                     $resulttext = $nochgmsg;
17346:                 }
17347:             } else {
17348:                 $resulttext = $nochgmsg;
17349:             }
17350:         } else {
17351:             $resulttext = '<span class="LC_error">'.
17352:                           &mt('An error occurred: [_1]',$putresult).'</span>';
17353:         }
17354:     } else {
17355:         $resulttext = $nochgmsg;
17356:     }
17357:     return $resulttext;
17358: }
17359: 
17360: sub recurse_check {
17361:     my ($chkcats,$categories,$depth,$name) = @_;
17362:     if (ref($chkcats->[$depth]{$name}) eq 'ARRAY') {
17363:         my $chg = 0;
17364:         for (my $j=0; $j<@{$chkcats->[$depth]{$name}}; $j++) {
17365:             my $category = $chkcats->[$depth]{$name}[$j];
17366:             my $item;
17367:             if ($category eq '') {
17368:                 $chg ++;
17369:             } else {
17370:                 my $deeper = $depth + 1;
17371:                 $item = &escape($category).':'.&escape($name).':'.$depth;
17372:                 if ($chg) {
17373:                     $categories->{$item} -= $chg;
17374:                 }
17375:                 &recurse_check($chkcats,$categories,$deeper,$category);
17376:                 $deeper --;
17377:             }
17378:         }
17379:     }
17380:     return;
17381: }
17382: 
17383: sub recurse_cat_deletes {
17384:     my ($item,$coursecategories,$deletions) = @_;
17385:     my ($deleted,$container,$depth) = map { &unescape($_); } split(/:/,$item);
17386:     my $subdepth = $depth + 1;
17387:     if (ref($coursecategories) eq 'HASH') {
17388:         foreach my $subitem (keys(%{$coursecategories})) {
17389:             my ($child,$parent,$itemdepth) = map { &unescape($_); } split(/:/,$subitem);
17390:             if (($parent eq $deleted) && ($itemdepth == $subdepth)) {
17391:                 delete($coursecategories->{$subitem});
17392:                 $deletions->{$subitem} = 1;
17393:                 &recurse_cat_deletes($subitem,$coursecategories,$deletions);
17394:             }
17395:         }
17396:     }
17397:     return;
17398: }
17399: 
17400: sub active_dc_picker {
17401:     my ($dom,$numinrow,$inputtype,$name,%currhash) = @_;
17402:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
17403:     my @domcoord = keys(%domcoords);
17404:     if (keys(%currhash)) {
17405:         foreach my $dc (keys(%currhash)) {
17406:             unless (exists($domcoords{$dc})) {
17407:                 push(@domcoord,$dc);
17408:             }
17409:         }
17410:     }
17411:     @domcoord = sort(@domcoord);
17412:     my $numdcs = scalar(@domcoord);
17413:     my $rows = 0;
17414:     my $table;
17415:     if ($numdcs > 1) {
17416:         $table = '<table>';
17417:         for (my $i=0; $i<@domcoord; $i++) {
17418:             my $rem = $i%($numinrow);
17419:             if ($rem == 0) {
17420:                 if ($i > 0) {
17421:                     $table .= '</tr>';
17422:                 }
17423:                 $table .= '<tr>';
17424:                 $rows ++;
17425:             }
17426:             my $check = '';
17427:             if ($inputtype eq 'radio') {
17428:                 if (keys(%currhash) == 0) {
17429:                     if (!$i) {
17430:                         $check = ' checked="checked"';
17431:                     }
17432:                 } elsif (exists($currhash{$domcoord[$i]})) {
17433:                     $check = ' checked="checked"';
17434:                 }
17435:             } else {
17436:                 if (exists($currhash{$domcoord[$i]})) {
17437:                     $check = ' checked="checked"';
17438:                 }
17439:             }
17440:             if ($i == @domcoord - 1) {
17441:                 my $colsleft = $numinrow - $rem;
17442:                 if ($colsleft > 1) {
17443:                     $table .= '<td class="LC_left_item" colspan="'.$colsleft.'">';
17444:                 } else {
17445:                     $table .= '<td class="LC_left_item">';
17446:                 }
17447:             } else {
17448:                 $table .= '<td class="LC_left_item">';
17449:             }
17450:             my ($dcname,$dcdom) = split(':',$domcoord[$i]);
17451:             my $user = &Apache::loncommon::plainname($dcname,$dcdom);
17452:             $table .= '<span class="LC_nobreak"><label>'.
17453:                       '<input type="'.$inputtype.'" name="'.$name.'"'.
17454:                       ' value="'.$domcoord[$i].'"'.$check.' />'.$user;
17455:             if ($user ne $dcname.':'.$dcdom) {
17456:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
17457:             }
17458:             $table .= '</label></span></td>';
17459:         }
17460:         $table .= '</tr></table>';
17461:     } elsif ($numdcs == 1) {
17462:         my ($dcname,$dcdom) = split(':',$domcoord[0]);
17463:         my $user = &Apache::loncommon::plainname($dcname,$dcdom);
17464:         if ($inputtype eq 'radio') {
17465:             $table = '<input type="hidden" name="'.$name.'" value="'.$domcoord[0].'" />'.$user;
17466:             if ($user ne $dcname.':'.$dcdom) {
17467:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
17468:             }
17469:         } else {
17470:             my $check;
17471:             if (exists($currhash{$domcoord[0]})) {
17472:                 $check = ' checked="checked"';
17473:             }
17474:             $table = '<span class="LC_nobreak"><label>'.
17475:                      '<input type="checkbox" name="'.$name.'" '.
17476:                      'value="'.$domcoord[0].'"'.$check.' />'.$user;
17477:             if ($user ne $dcname.':'.$dcdom) {
17478:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
17479:             }
17480:             $table .= '</label></span>';
17481:             $rows ++;
17482:         }
17483:     }
17484:     return ($numdcs,$table,$rows);
17485: }
17486: 
17487: sub usersession_titles {
17488:     return &Apache::lonlocal::texthash(
17489:                hosted => 'Hosting of sessions for users from other domains on servers in this domain',
17490:                remote => 'Hosting of sessions for users in this domain on servers in other domains',
17491:                spares => 'Servers offloaded to, when busy',
17492:                version => 'LON-CAPA version requirement',
17493:                excludedomain => 'Allow all, but exclude specific domains',
17494:                includedomain => 'Deny all, but include specific domains',
17495:                primary => 'Primary (checked first)',
17496:                default => 'Default',
17497:            );
17498: }
17499: 
17500: sub id_for_thisdom {
17501:     my (%servers) = @_;
17502:     my %altids;
17503:     foreach my $server (keys(%servers)) {
17504:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
17505:         if ($serverhome ne $server) {
17506:             $altids{$serverhome} = $server;
17507:         }
17508:     }
17509:     return %altids;
17510: }
17511: 
17512: sub count_servers {
17513:     my ($currbalancer,%servers) = @_;
17514:     my (@spares,$numspares);
17515:     foreach my $lonhost (sort(keys(%servers))) {
17516:         next if ($currbalancer eq $lonhost);
17517:         push(@spares,$lonhost);
17518:     }
17519:     if ($currbalancer) {
17520:         $numspares = scalar(@spares);
17521:     } else {
17522:         $numspares = scalar(@spares) - 1;
17523:     }
17524:     return ($numspares,@spares);
17525: }
17526: 
17527: sub lonbalance_targets_js {
17528:     my ($dom,$types,$servers,$settings) = @_;
17529:     my $select = &mt('Select');
17530:     my ($alltargets,$allishome,$allinsttypes,@alltypes);
17531:     if (ref($servers) eq 'HASH') {
17532:         $alltargets = join("','",sort(keys(%{$servers})));
17533:         my @homedoms;
17534:         foreach my $server (sort(keys(%{$servers}))) {
17535:             if (&Apache::lonnet::host_domain($server) eq $dom) {
17536:                 push(@homedoms,'1');
17537:             } else {
17538:                 push(@homedoms,'0');
17539:             }
17540:         }
17541:         $allishome = join("','",@homedoms);
17542:     }
17543:     if (ref($types) eq 'ARRAY') {
17544:         if (@{$types} > 0) {
17545:             @alltypes = @{$types};
17546:         }
17547:     }
17548:     push(@alltypes,'default','_LC_adv','_LC_author','_LC_internetdom','_LC_external');
17549:     $allinsttypes = join("','",@alltypes);
17550:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
17551:     if (ref($settings) eq 'HASH') {
17552:         %existing = %{$settings};
17553:     }
17554:     &get_loadbalancers_config($servers,\%existing,\%currbalancer,
17555:                               \%currtargets,\%currrules,\%currcookies);
17556:     my $balancers = join("','",sort(keys(%currbalancer)));
17557:     return <<"END";
17558: 
17559: <script type="text/javascript">
17560: // <![CDATA[
17561: 
17562: currBalancers = new Array('$balancers');
17563: 
17564: function toggleTargets(balnum) {
17565:     var lonhostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
17566:     var prevhostitem = document.getElementById('loadbalancing_prevlonhost_'+balnum);
17567:     var balancer = lonhostitem.options[lonhostitem.selectedIndex].value;
17568:     var prevbalancer = prevhostitem.value;
17569:     var baltotal = document.getElementById('loadbalancing_total').value;
17570:     prevhostitem.value = balancer;
17571:     if (prevbalancer != '') {
17572:         var prevIdx = currBalancers.indexOf(prevbalancer);
17573:         if (prevIdx != -1) {
17574:             currBalancers.splice(prevIdx,1);
17575:         }
17576:     }
17577:     if (balancer == '') {
17578:         hideSpares(balnum);
17579:     } else {
17580:         var currIdx = currBalancers.indexOf(balancer);
17581:         if (currIdx == -1) {
17582:             currBalancers.push(balancer);
17583:         }
17584:         var homedoms = new Array('$allishome');
17585:         var ishomedom = homedoms[lonhostitem.selectedIndex];
17586:         showSpares(balancer,ishomedom,balnum);
17587:     }
17588:     balancerChange(balnum,baltotal,'change',prevbalancer,balancer);
17589:     return;
17590: }
17591: 
17592: function showSpares(balancer,ishomedom,balnum) {
17593:     var alltargets = new Array('$alltargets');
17594:     var insttypes = new Array('$allinsttypes');
17595:     var offloadtypes = new Array('primary','default');
17596: 
17597:     document.getElementById('loadbalancing_targets_'+balnum).style.display='block';
17598:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='none';
17599:  
17600:     for (var i=0; i<offloadtypes.length; i++) {
17601:         var count = 0;
17602:         for (var j=0; j<alltargets.length; j++) {
17603:             if (alltargets[j] != balancer) {
17604:                 var item = document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+count);
17605:                 item.value = alltargets[j];
17606:                 item.style.textAlign='left';
17607:                 item.style.textFace='normal';
17608:                 document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+count).innerHTML = alltargets[j];
17609:                 if (currBalancers.indexOf(alltargets[j]) == -1) {
17610:                     item.disabled = '';
17611:                 } else {
17612:                     item.disabled = 'disabled';
17613:                     item.checked = false;
17614:                 }
17615:                 count ++;
17616:             }
17617:         }
17618:     }
17619:     for (var k=0; k<insttypes.length; k++) {
17620:         if ((insttypes[k] == '_LC_external') || (insttypes[k] == '_LC_internetdom')) {
17621:             if (ishomedom == 1) {
17622:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
17623:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
17624:             } else {
17625:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
17626:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
17627:             }
17628:         } else {
17629:             document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
17630:             document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
17631:         }
17632:         if ((insttypes[k] != '_LC_external') && 
17633:             ((insttypes[k] != '_LC_internetdom') ||
17634:              ((insttypes[k] == '_LC_internetdom') && (ishomedom == 1)))) {
17635:             var item = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]);
17636:             item.options.length = 0;
17637:             item.options[0] = new Option("","",true,true);
17638:             var idx = 0;
17639:             for (var m=0; m<alltargets.length; m++) {
17640:                 if ((currBalancers.indexOf(alltargets[m]) == -1) && (alltargets[m] != balancer)) {
17641:                     idx ++;
17642:                     item.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
17643:                 }
17644:             }
17645:         }
17646:     }
17647:     return;
17648: }
17649: 
17650: function hideSpares(balnum) {
17651:     var alltargets = new Array('$alltargets');
17652:     var insttypes = new Array('$allinsttypes');
17653:     var offloadtypes = new Array('primary','default');
17654: 
17655:     document.getElementById('loadbalancing_targets_'+balnum).style.display='none';
17656:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='block';
17657: 
17658:     var total = alltargets.length - 1;
17659:     for (var i=0; i<offloadtypes; i++) {
17660:         for (var j=0; j<total; j++) {
17661:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).checked = false;
17662:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).value = '';
17663:            document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+j).innerHTML = '';
17664:         }
17665:     }
17666:     for (var k=0; k<insttypes.length; k++) {
17667:         document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
17668:         document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
17669:         if (insttypes[k] != '_LC_external') {
17670:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).length = 0;
17671:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).options[0] = new Option("","",true,true);
17672:         }
17673:     }
17674:     return;
17675: }
17676: 
17677: function checkOffloads(item,balnum,type) {
17678:     var alltargets = new Array('$alltargets');
17679:     var offloadtypes = new Array('primary','default');
17680:     if (item.checked) {
17681:         var total = alltargets.length - 1;
17682:         var other;
17683:         if (type == offloadtypes[0]) {
17684:             other = offloadtypes[1];
17685:         } else {
17686:             other = offloadtypes[0];
17687:         }
17688:         for (var i=0; i<total; i++) {
17689:             var server = document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).value;
17690:             if (server == item.value) {
17691:                 if (document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked) {
17692:                     document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked = false;
17693:                 }
17694:             }
17695:         }
17696:     }
17697:     return;
17698: }
17699: 
17700: function singleServerToggle(balnum,type) {
17701:     var offloadtoSelIdx = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex;
17702:     if (offloadtoSelIdx == 0) {
17703:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_0').checked = true;
17704:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
17705: 
17706:     } else {
17707:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_2').checked = true;
17708:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
17709:     }
17710:     return;
17711: }
17712: 
17713: function balanceruleChange(formname,balnum,type) {
17714:     if (type == '_LC_external') {
17715:         return;
17716:     }
17717:     var typesRules = getIndicesByName(formname,'loadbalancing_rules_'+balnum+'_'+type);
17718:     for (var i=0; i<typesRules.length; i++) {
17719:         if (formname.elements[typesRules[i]].checked) {
17720:             if (formname.elements[typesRules[i]].value != 'specific') {
17721:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex = 0;
17722:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
17723:             } else {
17724:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
17725:             }
17726:         }
17727:     }
17728:     return;
17729: }
17730: 
17731: function balancerDeleteChange(balnum) {
17732:     var hostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
17733:     var baltotal = document.getElementById('loadbalancing_total').value;
17734:     var addtarget;
17735:     var removetarget;
17736:     var action = 'delete';
17737:     if (document.getElementById('loadbalancing_delete_'+balnum)) {
17738:         var lonhost = hostitem.value;
17739:         var currIdx = currBalancers.indexOf(lonhost);
17740:         if (document.getElementById('loadbalancing_delete_'+balnum).checked) {
17741:             if (currIdx != -1) {
17742:                 currBalancers.splice(currIdx,1);
17743:             }
17744:             addtarget = lonhost;
17745:         } else {
17746:             if (currIdx == -1) {
17747:                 currBalancers.push(lonhost);
17748:             }
17749:             removetarget = lonhost;
17750:             action = 'undelete';
17751:         }
17752:         balancerChange(balnum,baltotal,action,addtarget,removetarget);
17753:     }
17754:     return;
17755: }
17756: 
17757: function balancerChange(balnum,baltotal,action,addtarget,removetarget) {
17758:     if (baltotal > 1) {
17759:         var offloadtypes = new Array('primary','default');
17760:         var alltargets = new Array('$alltargets');
17761:         var insttypes = new Array('$allinsttypes');
17762:         for (var i=0; i<baltotal; i++) {
17763:             if (i != balnum) {
17764:                 for (var j=0; j<offloadtypes.length; j++) {
17765:                     var total = alltargets.length - 1;
17766:                     for (var k=0; k<total; k++) {
17767:                         var serveritem = document.getElementById('loadbalancing_target_'+i+'_'+offloadtypes[j]+'_'+k);
17768:                         var server = serveritem.value;
17769:                         if ((action == 'delete') || (action == 'change' && addtarget != ''))  {
17770:                             if (server == addtarget) {
17771:                                 serveritem.disabled = '';
17772:                             }
17773:                         }
17774:                         if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
17775:                             if (server == removetarget) {
17776:                                 serveritem.disabled = 'disabled';
17777:                                 serveritem.checked = false;
17778:                             }
17779:                         }
17780:                     }
17781:                 }
17782:                 for (var j=0; j<insttypes.length; j++) {
17783:                     if (insttypes[j] != '_LC_external') {
17784:                         if (document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j])) {
17785:                             var singleserver = document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j]);
17786:                             var currSel = singleserver.selectedIndex;
17787:                             var currVal = singleserver.options[currSel].value;
17788:                             if ((action == 'delete') || (action == 'change' && addtarget != '')) {
17789:                                 var numoptions = singleserver.options.length;
17790:                                 var needsnew = 1;
17791:                                 for (var k=0; k<numoptions; k++) {
17792:                                     if (singleserver.options[k] == addtarget) {
17793:                                         needsnew = 0;
17794:                                         break;
17795:                                     }
17796:                                 }
17797:                                 if (needsnew == 1) {
17798:                                     singleserver.options[numoptions] = new Option(addtarget,addtarget,false,false);
17799:                                 }
17800:                             }
17801:                             if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
17802:                                 singleserver.options.length = 0;
17803:                                 if ((currVal) && (currVal != removetarget)) {
17804:                                     singleserver.options[0] = new Option("","",false,false);
17805:                                 } else {
17806:                                     singleserver.options[0] = new Option("","",true,true);
17807:                                 }
17808:                                 var idx = 0;
17809:                                 for (var m=0; m<alltargets.length; m++) {
17810:                                     if (currBalancers.indexOf(alltargets[m]) == -1) {
17811:                                         idx ++;
17812:                                         if (currVal == alltargets[m]) {
17813:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],true,true);
17814:                                         } else {
17815:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
17816:                                         }
17817:                                     }
17818:                                 }
17819:                             }
17820:                         }
17821:                     }
17822:                 }
17823:             }
17824:         }
17825:     }
17826:     return;
17827: }
17828: 
17829: // ]]>
17830: </script>
17831: 
17832: END
17833: }
17834: 
17835: sub new_spares_js {
17836:     my @sparestypes = ('primary','default');
17837:     my $types = join("','",@sparestypes);
17838:     my $select = &mt('Select');
17839:     return <<"END";
17840: 
17841: <script type="text/javascript">
17842: // <![CDATA[
17843: 
17844: function updateNewSpares(formname,lonhost) {
17845:     var types = new Array('$types');
17846:     var include = new Array();
17847:     var exclude = new Array();
17848:     for (var i=0; i<types.length; i++) {
17849:         var spareboxes = getIndicesByName(formname,'spare_'+types[i]+'_'+lonhost);
17850:         for (var j=0; j<spareboxes.length; j++) {
17851:             if (formname.elements[spareboxes[j]].checked) {
17852:                 exclude.push(formname.elements[spareboxes[j]].value);
17853:             } else {
17854:                 include.push(formname.elements[spareboxes[j]].value);
17855:             }
17856:         }
17857:     }
17858:     for (var i=0; i<types.length; i++) {
17859:         var newSpare = document.getElementById('newspare_'+types[i]+'_'+lonhost);
17860:         var selIdx = newSpare.selectedIndex;
17861:         var currnew = newSpare.options[selIdx].value;
17862:         var okSpares = new Array();
17863:         for (var j=0; j<newSpare.options.length; j++) {
17864:             var possible = newSpare.options[j].value;
17865:             if (possible != '') {
17866:                 if (exclude.indexOf(possible) == -1) {
17867:                     okSpares.push(possible);
17868:                 } else {
17869:                     if (currnew == possible) {
17870:                         selIdx = 0;
17871:                     }
17872:                 }
17873:             }
17874:         }
17875:         for (var k=0; k<include.length; k++) {
17876:             if (okSpares.indexOf(include[k]) == -1) {
17877:                 okSpares.push(include[k]);
17878:             }
17879:         }
17880:         okSpares.sort();
17881:         newSpare.options.length = 0;
17882:         if (selIdx == 0) {
17883:             newSpare.options[0] = new Option("$select","",true,true);
17884:         } else {
17885:             newSpare.options[0] = new Option("$select","",false,false);
17886:         }
17887:         for (var m=0; m<okSpares.length; m++) {
17888:             var idx = m+1;
17889:             var selThis = 0;
17890:             if (selIdx != 0) {
17891:                 if (okSpares[m] == currnew) {
17892:                     selThis = 1;
17893:                 }
17894:             }
17895:             if (selThis == 1) {
17896:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],true,true);
17897:             } else {
17898:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],false,false);
17899:             }
17900:         }
17901:     }
17902:     return;
17903: }
17904: 
17905: function checkNewSpares(lonhost,type) {
17906:     var newSpare = document.getElementById('newspare_'+type+'_'+lonhost);
17907:     var chosen =  newSpare.options[newSpare.selectedIndex].value;
17908:     if (chosen != '') { 
17909:         var othertype;
17910:         var othernewSpare;
17911:         if (type == 'primary') {
17912:             othernewSpare = document.getElementById('newspare_default_'+lonhost);
17913:         }
17914:         if (type == 'default') {
17915:             othernewSpare = document.getElementById('newspare_primary_'+lonhost);
17916:         }
17917:         if (othernewSpare.options[othernewSpare.selectedIndex].value == chosen) {
17918:             othernewSpare.selectedIndex = 0;
17919:         }
17920:     }
17921:     return;
17922: }
17923: 
17924: // ]]>
17925: </script>
17926: 
17927: END
17928: 
17929: }
17930: 
17931: sub common_domprefs_js {
17932:     return <<"END";
17933: 
17934: <script type="text/javascript">
17935: // <![CDATA[
17936: 
17937: function getIndicesByName(formname,item) {
17938:     var group = new Array();
17939:     for (var i=0;i<formname.elements.length;i++) {
17940:         if (formname.elements[i].name == item) {
17941:             group.push(formname.elements[i].id);
17942:         }
17943:     }
17944:     return group;
17945: }
17946: 
17947: // ]]>
17948: </script>
17949: 
17950: END
17951: 
17952: }
17953: 
17954: sub recaptcha_js {
17955:     my %lt = &captcha_phrases();
17956:     return <<"END";
17957: 
17958: <script type="text/javascript">
17959: // <![CDATA[
17960: 
17961: function updateCaptcha(caller,context) {
17962:     var privitem;
17963:     var pubitem;
17964:     var privtext;
17965:     var pubtext;
17966:     var versionitem;
17967:     var versiontext;
17968:     if (document.getElementById(context+'_recaptchapub')) {
17969:         pubitem = document.getElementById(context+'_recaptchapub');
17970:     } else {
17971:         return;
17972:     }
17973:     if (document.getElementById(context+'_recaptchapriv')) {
17974:         privitem = document.getElementById(context+'_recaptchapriv');
17975:     } else {
17976:         return;
17977:     }
17978:     if (document.getElementById(context+'_recaptchapubtxt')) {
17979:         pubtext = document.getElementById(context+'_recaptchapubtxt');
17980:     } else {
17981:         return;
17982:     }
17983:     if (document.getElementById(context+'_recaptchaprivtxt')) {
17984:         privtext = document.getElementById(context+'_recaptchaprivtxt');
17985:     } else {
17986:         return;
17987:     }
17988:     if (document.getElementById(context+'_recaptchaversion')) {
17989:         versionitem = document.getElementById(context+'_recaptchaversion');
17990:     } else {
17991:         return;
17992:     }
17993:     if (document.getElementById(context+'_recaptchavertxt')) {
17994:         versiontext = document.getElementById(context+'_recaptchavertxt');
17995:     } else {
17996:         return;
17997:     }
17998:     if (caller.checked) {
17999:         if (caller.value == 'recaptcha') {
18000:             pubitem.type = 'text';
18001:             privitem.type = 'text';
18002:             pubitem.size = '40';
18003:             privitem.size = '40';
18004:             pubtext.innerHTML = "$lt{'pub'}";
18005:             privtext.innerHTML = "$lt{'priv'}";
18006:             versionitem.type = 'text';
18007:             versionitem.size = '3';
18008:             versiontext.innerHTML = "$lt{'ver'}";
18009:         } else {
18010:             pubitem.type = 'hidden';
18011:             privitem.type = 'hidden';
18012:             versionitem.type = 'hidden';
18013:             pubtext.innerHTML = '';
18014:             privtext.innerHTML = '';
18015:             versiontext.innerHTML = '';
18016:         }
18017:     }
18018:     return;
18019: }
18020: 
18021: // ]]>
18022: </script>
18023: 
18024: END
18025: 
18026: }
18027: 
18028: sub toggle_display_js {
18029:     return <<"END";
18030: 
18031: <script type="text/javascript">
18032: // <![CDATA[
18033: 
18034: function toggleDisplay(domForm,caller) {
18035:     if (document.getElementById(caller)) {
18036:         var divitem = document.getElementById(caller);
18037:         var optionsElement = domForm.coursecredits;
18038:         var checkval = 1;
18039:         var dispval = 'block';
18040:         var selfcreateRegExp = /^cancreate_emailverified/;
18041:         if (caller == 'emailoptions') {
18042:             optionsElement = domForm.cancreate_email; 
18043:         }
18044:         if (caller == 'studentsubmission') {
18045:             optionsElement = domForm.postsubmit;
18046:         }
18047:         if (caller == 'cloneinstcode') {
18048:             optionsElement = domForm.canclone;
18049:             checkval = 'instcode';
18050:         }
18051:         if (selfcreateRegExp.test(caller)) {
18052:             optionsElement = domForm.elements[caller];
18053:             checkval = 'other';
18054:             dispval = 'inline'
18055:         }
18056:         if (optionsElement.length) {
18057:             var currval;
18058:             for (var i=0; i<optionsElement.length; i++) {
18059:                 if (optionsElement[i].checked) {
18060:                    currval = optionsElement[i].value;
18061:                 }
18062:             }
18063:             if (currval == checkval) {
18064:                 divitem.style.display = dispval;
18065:             } else {
18066:                 divitem.style.display = 'none';
18067:             }
18068:         }
18069:     }
18070:     return;
18071: }
18072: 
18073: // ]]>
18074: </script>
18075: 
18076: END
18077: 
18078: }
18079: 
18080: sub captcha_phrases {
18081:     return &Apache::lonlocal::texthash (
18082:                  priv => 'Private key',
18083:                  pub  => 'Public key',
18084:                  original  => 'original (CAPTCHA)',
18085:                  recaptcha => 'successor (ReCAPTCHA)',
18086:                  notused   => 'unused',
18087:                  ver => 'ReCAPTCHA version (1 or 2)',
18088:     );
18089: }
18090: 
18091: sub devalidate_remote_domconfs {
18092:     my ($dom,$cachekeys) = @_;
18093:     return unless (ref($cachekeys) eq 'HASH');
18094:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
18095:     my %thismachine;
18096:     map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
18097:     my @posscached = ('domainconfig','domdefaults','usersessions',
18098:                       'directorysrch','passwdconf','cats','proxyalias','proxysaml',
18099:                       'ipaccess');
18100:     my %cache_by_lonhost;
18101:     if (exists($cachekeys->{'samllanding'})) {
18102:         if (ref($cachekeys->{'samllanding'}) eq 'HASH') {
18103:             my %landing = %{$cachekeys->{'samllanding'}};
18104:             my %domservers = &Apache::lonnet::get_servers($dom);
18105:             if (keys(%domservers)) {
18106:                 foreach my $server (keys(%domservers)) {
18107:                     my @cached;
18108:                     next if ($thismachine{$server});
18109:                     if ($landing{$server}) {
18110:                         push(@cached,&escape('samllanding').':'.&escape($server));
18111:                     }
18112:                     if (@cached) {
18113:                         $cache_by_lonhost{$server} = \@cached;
18114:                     }
18115:                 }
18116:             }
18117:         }
18118:     }
18119:     if (keys(%servers)) {
18120:         foreach my $server (keys(%servers)) {
18121:             next if ($thismachine{$server});
18122:             my @cached;
18123:             foreach my $name (@posscached) {
18124:                 if ($cachekeys->{$name}) {
18125:                     if (($name eq 'proxyalias') || ($name eq 'proxysaml')) {
18126:                         if (ref($cachekeys->{$name}) eq 'HASH') {
18127:                             foreach my $key (keys(%{$cachekeys->{$name}})) {
18128:                                 push(@cached,&escape($name).':'.&escape($key));
18129:                             }
18130:                         }
18131:                     } else {
18132:                         push(@cached,&escape($name).':'.&escape($dom));
18133:                     }
18134:                 }
18135:             }
18136:             if ((exists($cache_by_lonhost{$server})) &&
18137:                 (ref($cache_by_lonhost{$server}) eq 'ARRAY')) {
18138:                 push(@cached,@{$cache_by_lonhost{$server}});
18139:             }
18140:             if (@cached) {
18141:                 &Apache::lonnet::remote_devalidate_cache($server,\@cached);
18142:             }
18143:         }
18144:     }
18145:     return;
18146: }
18147: 
18148: 1;

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