File:  [LON-CAPA] / loncom / interface / domainprefs.pm
Revision 1.160.6.121: download - view: text, annotated - select for diffs
Wed Jan 19 20:56:06 2022 UTC (2 years, 4 months ago) by raeburn
Branches: version_2_11_X
Diff to branchpoint 1.160: preferred, unified
- For 2.11
  - Fix typo in 1.160.6.119 backport of 1.402

    1: # The LearningOnline Network with CAPA
    2: # Handler to set domain-wide configuration settings
    3: #
    4: # $Id: domainprefs.pm,v 1.160.6.121 2022/01/19 20:56:06 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:                       print => \&print_defaults,
  273:                       modify => \&modify_defaults,
  274:                     },
  275:         'wafproxy' =>
  276:                     { text => 'Web Application Firewall/Reverse Proxy',
  277:                       help => 'Domain_Configuration_WAF_Proxy',
  278:                       header => [{col1 => 'Domain(s)',
  279:                                   col2 => 'Servers and WAF/Reverse Proxy alias(es)',
  280:                                  },
  281:                                  {col1 => 'Domain(s)',
  282:                                   col2 => 'WAF Configuration',}],
  283:                       print => \&print_wafproxy,
  284:                       modify => \&modify_wafproxy,
  285:                     },
  286:         'passwords' =>
  287:                     { text => 'Passwords (Internal authentication)',
  288:                       help => 'Domain_Configuration_Passwords',
  289:                       header => [{col1 => 'Resetting Forgotten Password',
  290:                                   col2 => 'Settings'},
  291:                                  {col1 => 'Encryption of Stored Passwords (Internal Auth)',
  292:                                   col2 => 'Settings'},
  293:                                  {col1 => 'Rules for LON-CAPA Passwords',
  294:                                   col2 => 'Settings'},
  295:                                  {col1 => 'Course Owner Changing Student Passwords',
  296:                                   col2 => 'Settings'}],
  297:                       print => \&print_passwords,
  298:                       modify => \&modify_passwords,
  299:                     },
  300:         'quotas' => 
  301:                     { text => 'Blogs, personal web pages, webDAV/quotas, portfolios',
  302:                       help => 'Domain_Configuration_Quotas',
  303:                       header => [{col1 => 'User affiliation',
  304:                                   col2 => 'Available tools',
  305:                                   col3 => 'Quotas, MB; (Authoring requires role)',}],
  306:                       print => \&print_quotas,
  307:                       modify => \&modify_quotas,
  308:                     },
  309:         'autoenroll' =>
  310:                    { text => 'Auto-enrollment settings',
  311:                      help => 'Domain_Configuration_Auto_Enrollment',
  312:                      header => [{col1 => 'Configuration setting',
  313:                                  col2 => 'Value(s)'}],
  314:                      print => \&print_autoenroll,
  315:                      modify => \&modify_autoenroll,
  316:                    },
  317:         'autoupdate' => 
  318:                    { text => 'Auto-update settings',
  319:                      help => 'Domain_Configuration_Auto_Updates',
  320:                      header => [{col1 => 'Setting',
  321:                                  col2 => 'Value',},
  322:                                 {col1 => 'Setting',
  323:                                  col2 => 'Affiliation'},
  324:                                 {col1 => 'User population',
  325:                                  col2 => 'Updatable user data'}],
  326:                      print => \&print_autoupdate,
  327:                      modify => \&modify_autoupdate,
  328:                   },
  329:         'autocreate' => 
  330:                   { text => 'Auto-course creation settings',
  331:                      help => 'Domain_Configuration_Auto_Creation',
  332:                      header => [{col1 => 'Configuration Setting',
  333:                                  col2 => 'Value',}],
  334:                      print => \&print_autocreate,
  335:                      modify => \&modify_autocreate,
  336:                   },
  337:         'directorysrch' => 
  338:                   { text => 'Directory searches',
  339:                     help => 'Domain_Configuration_InstDirectory_Search',
  340:                     header => [{col1 => 'Institutional Directory Setting',
  341:                                 col2 => 'Value',},
  342:                                {col1 => 'LON-CAPA Directory Setting',
  343:                                 col2 => 'Value',}],
  344:                     print => \&print_directorysrch,
  345:                     modify => \&modify_directorysrch,
  346:                   },
  347:         'contacts' =>
  348:                   { text => 'E-mail addresses and helpform',
  349:                     help => 'Domain_Configuration_Contact_Info',
  350:                     header => [{col1 => 'Default e-mail addresses',
  351:                                 col2 => 'Value',},
  352:                                {col1 => 'Recipient(s) for notifications',
  353:                                 col2 => 'Value',},
  354:                                {col1 => 'Nightly status check e-mail',
  355:                                 col2 => 'Settings',},
  356:                                {col1 => 'Ask helpdesk form settings',
  357:                                 col2 => 'Value',},],
  358:                     print => \&print_contacts,
  359:                     modify => \&modify_contacts,
  360:                   },
  361:         'usercreation' => 
  362:                   { text => 'User creation',
  363:                     help => 'Domain_Configuration_User_Creation',
  364:                     header => [{col1 => 'Format rule type',
  365:                                 col2 => 'Format rules in force'},
  366:                                {col1 => 'User account creation',
  367:                                 col2 => 'Usernames which may be created',},
  368:                                {col1 => 'Context',
  369:                                 col2 => 'Assignable authentication types'}],
  370:                     print => \&print_usercreation,
  371:                     modify => \&modify_usercreation,
  372:                   },
  373:         'selfcreation' => 
  374:                   { text => 'Users self-creating accounts',
  375:                     help => 'Domain_Configuration_Self_Creation', 
  376:                     header => [{col1 => 'Self-creation with institutional username',
  377:                                 col2 => 'Enabled?'},
  378:                                {col1 => 'Institutional user type (login/SSO self-creation)',
  379:                                 col2 => 'Information user can enter'},
  380:                                {col1 => 'Self-creation with e-mail verification',
  381:                                 col2 => 'Settings'}],
  382:                     print => \&print_selfcreation,
  383:                     modify => \&modify_selfcreation,
  384:                   },
  385:         'usermodification' =>
  386:                   { text => 'User modification',
  387:                     help => 'Domain_Configuration_User_Modification',
  388:                     header => [{col1 => 'Target user has role',
  389:                                 col2 => 'User information updatable in author context'},
  390:                                {col1 => 'Target user has role',
  391:                                 col2 => 'User information updatable in course context'}],
  392:                     print => \&print_usermodification,
  393:                     modify => \&modify_usermodification,
  394:                   },
  395:         'scantron' =>
  396:                   { text => 'Bubblesheet format',
  397:                     help => 'Domain_Configuration_Scantron_Format',
  398:                     header => [ {col1 => 'Bubblesheet format file',
  399:                                  col2 => ''},
  400:                                 {col1 => 'Bubblesheet data upload formats',
  401:                                  col2 => 'Settings'}],
  402:                     print => \&print_scantron,
  403:                     modify => \&modify_scantron,
  404:                   },
  405:         'requestcourses' => 
  406:                  {text => 'Request creation of courses',
  407:                   help => 'Domain_Configuration_Request_Courses',
  408:                   header => [{col1 => 'User affiliation',
  409:                               col2 => 'Availability/Processing of requests',},
  410:                              {col1 => 'Setting',
  411:                               col2 => 'Value'},
  412:                              {col1 => 'Available textbooks',
  413:                               col2 => ''},
  414:                              {col1 => 'Available templates',
  415:                               col2 => ''},
  416:                              {col1 => 'Validation (not official courses)',
  417:                               col2 => 'Value'},],
  418:                   print => \&print_quotas,
  419:                   modify => \&modify_quotas,
  420:                  },
  421:         'requestauthor' =>
  422:                  {text => 'Request Authoring Space',
  423:                   help => 'Domain_Configuration_Request_Author',
  424:                   header => [{col1 => 'User affiliation',
  425:                               col2 => 'Availability/Processing of requests',},
  426:                              {col1 => 'Setting',
  427:                               col2 => 'Value'}],
  428:                   print => \&print_quotas,
  429:                   modify => \&modify_quotas,
  430:                  },
  431:         'coursecategories' =>
  432:                   { text => 'Cataloging of courses/communities',
  433:                     help => 'Domain_Configuration_Cataloging_Courses',
  434:                     header => [{col1 => 'Catalog type/availability',
  435:                                 col2 => '',},
  436:                                {col1 => 'Category settings for standard catalog',
  437:                                 col2 => '',},
  438:                                {col1 => 'Categories',
  439:                                 col2 => '',
  440:                                }],
  441:                     print => \&print_coursecategories,
  442:                     modify => \&modify_coursecategories,
  443:                   },
  444:         'serverstatuses' =>
  445:                  {text   => 'Access to server status pages',
  446:                   help   => 'Domain_Configuration_Server_Status',
  447:                   header => [{col1 => 'Status Page',
  448:                               col2 => 'Other named users',
  449:                               col3 => 'Specific IPs',
  450:                             }],
  451:                   print => \&print_serverstatuses,
  452:                   modify => \&modify_serverstatuses,
  453:                  },
  454:         'helpsettings' =>
  455:                  {text   => 'Support settings',
  456:                   help   => 'Domain_Configuration_Help_Settings',
  457:                   header => [{col1 => 'Help Page Settings (logged-in users)',
  458:                               col2 => 'Value'},
  459:                              {col1 => 'Helpdesk Roles',
  460:                               col2 => 'Settings'},],
  461:                   print  => \&print_helpsettings,
  462:                   modify => \&modify_helpsettings,
  463:                  },
  464:         'coursedefaults' => 
  465:                  {text => 'Course/Community defaults',
  466:                   help => 'Domain_Configuration_Course_Defaults',
  467:                   header => [{col1 => 'Defaults which can be overridden in each course by a CC',
  468:                               col2 => 'Value',},
  469:                              {col1 => 'Defaults which can be overridden for each course by a DC',
  470:                               col2 => 'Value',},],
  471:                   print => \&print_coursedefaults,
  472:                   modify => \&modify_coursedefaults,
  473:                  },
  474:         'selfenrollment' => 
  475:                  {text   => 'Self-enrollment in Course/Community',
  476:                   help   => 'Domain_Configuration_Selfenrollment',
  477:                   header => [{col1 => 'Configuration Rights',
  478:                               col2 => 'Configured by Course Personnel or Domain Coordinator?'},
  479:                              {col1 => 'Defaults',
  480:                               col2 => 'Value'},
  481:                              {col1 => 'Self-enrollment validation (optional)',
  482:                               col2 => 'Value'},],
  483:                   print => \&print_selfenrollment,
  484:                   modify => \&modify_selfenrollment,
  485:                  },
  486:         'usersessions' =>
  487:                  {text  => 'User session hosting/offloading',
  488:                   help  => 'Domain_Configuration_User_Sessions',
  489:                   header => [{col1 => 'Domain server',
  490:                               col2 => 'Servers to offload sessions to when busy'},
  491:                              {col1 => 'Hosting of users from other domains',
  492:                               col2 => 'Rules'},
  493:                              {col1 => "Hosting domain's own users elsewhere",
  494:                               col2 => 'Rules'}],
  495:                   print => \&print_usersessions,
  496:                   modify => \&modify_usersessions,
  497:                  },
  498:         'loadbalancing' =>
  499:                  {text  => 'Dedicated Load Balancer(s)',
  500:                   help  => 'Domain_Configuration_Load_Balancing',
  501:                   header => [{col1 => 'Balancers',
  502:                               col2 => 'Default destinations',
  503:                               col3 => 'User affiliation',
  504:                               col4 => 'Overrides'},
  505:                             ],
  506:                   print => \&print_loadbalancing,
  507:                   modify => \&modify_loadbalancing,
  508:                  },
  509:          'ipaccess' =>
  510:                        {text => 'IP-based access control',
  511:                         help => 'Domain_Configuration_IP_Access',
  512:                         header => [{col1 => 'Setting',
  513:                                     col2 => 'Value'},],
  514:                         print  => \&print_ipaccess,
  515:                         modify => \&modify_ipaccess,
  516:                        },
  517:     );
  518:     if (keys(%servers) > 1) {
  519:         $prefs{'login'}  = { text   => 'Log-in page options',
  520:                              help   => 'Domain_Configuration_Login_Page',
  521:                             header => [{col1 => 'Log-in Service',
  522:                                         col2 => 'Server Setting',},
  523:                                        {col1 => 'Log-in Page Items',
  524:                                         col2 => ''},
  525:                                        {col1 => 'Log-in Help',
  526:                                         col2 => 'Value'},
  527:                                        {col1 => 'Custom HTML in document head',
  528:                                         col2 => 'Value'},
  529:                                        {col1 => 'SSO',
  530:                                         col2 => 'Dual login: SSO and non-SSO options'},
  531:                                       ],
  532:                             print => \&print_login,
  533:                             modify => \&modify_login,
  534:                            };
  535:     }
  536: 
  537:     my @roles = ('student','coordinator','author','admin');
  538:     my @actions = &Apache::loncommon::get_env_multiple('form.actions');
  539:     &Apache::lonhtmlcommon::add_breadcrumb
  540:     ({href=>"javascript:changePage(document.$phase,'pickactions')",
  541:       text=>"Settings to display/modify"});
  542:     my $confname = $dom.'-domainconfig';
  543: 
  544:     if ($phase eq 'process') {
  545:         my $result = &Apache::lonconfigsettings::make_changes($r,$dom,$phase,$context,\@prefs_order,
  546:                                                               \%prefs,\%domconfig,$confname,\@roles);
  547:         if ((ref($result) eq 'HASH') && (keys(%{$result}))) {
  548:             $r->rflush();
  549:             &devalidate_remote_domconfs($dom,$result);
  550:         }
  551:     } elsif ($phase eq 'display') {
  552:         my $js = &recaptcha_js().
  553:                  &toggle_display_js();
  554:         if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
  555:             my ($othertitle,$usertypes,$types) =
  556:                 &Apache::loncommon::sorted_inst_types($dom);
  557:             $js .= &lonbalance_targets_js($dom,$types,\%servers,
  558:                                           $domconfig{'loadbalancing'}).
  559:                    &new_spares_js().
  560:                    &common_domprefs_js().
  561:                    &Apache::loncommon::javascript_array_indexof();
  562:         }
  563:         if (grep(/^requestcourses$/,@actions)) {
  564:             my $javascript_validations;
  565:             my $coursebrowserjs=&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}); 
  566:             $js .= <<END;
  567: <script type="text/javascript">
  568: $javascript_validations
  569: </script>
  570: $coursebrowserjs
  571: END
  572:         } elsif (grep(/^ipaccess$/,@actions)) {
  573:             $js .= &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
  574:         }
  575:         if (grep(/^selfcreation$/,@actions)) {
  576:             $js .= &selfcreate_javascript();
  577:         }
  578:         if (grep(/^contacts$/,@actions)) {
  579:             $js .= &contacts_javascript();
  580:         }
  581:         if (grep(/^scantron$/,@actions)) {
  582:             $js .= &scantron_javascript();
  583:         }
  584:         &Apache::lonconfigsettings::display_settings($r,$dom,$phase,$context,\@prefs_order,\%prefs,\%domconfig,$confname,$js);
  585:     } else {
  586: # check if domconfig user exists for the domain.
  587:         my $servadm = $r->dir_config('lonAdmEMail');
  588:         my ($configuserok,$author_ok,$switchserver) =
  589:             &config_check($dom,$confname,$servadm);
  590:         unless ($configuserok eq 'ok') {
  591:             &Apache::lonconfigsettings::print_header($r,$phase,$context);
  592:             $r->print(&mt('The domain configuration user "[_1]" has yet to be created.',
  593:                           $confname).
  594:                       '<br />'
  595:             );
  596:             if ($switchserver) {
  597:                 $r->print(&mt('Ordinarily, that domain configuration user is created when the ./UPDATE script is run to install LON-CAPA for the first time.').
  598:                           '<br />'.
  599:                           &mt('However, that does not apply when new domains are added to a multi-domain server, and ./UPDATE has not been run recently.').
  600:                           '<br />'.
  601:                           &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).
  602:                           '<br />'.
  603:                           &mt('To do that now, use the following link: [_1]',$switchserver)
  604:                 );
  605:             } else {
  606:                 $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.').
  607:                           '<br />'.
  608:                           &mt('Once that is done, you will be able to use the web-based "Set domain configuration" to configure the domain')
  609:                 );
  610:             }
  611:             $r->print(&Apache::loncommon::end_page());
  612:             return OK;
  613:         }
  614:         if (keys(%domconfig) == 0) {
  615:             my $primarylibserv = &Apache::lonnet::domain($dom,'primary');
  616:             my @ids=&Apache::lonnet::current_machine_ids();
  617:             if (!grep(/^\Q$primarylibserv\E$/,@ids)) {
  618:                 my %designhash = &Apache::loncommon::get_domainconf($dom);
  619:                 my @loginimages = ('img','logo','domlogo','login');
  620:                 my $custom_img_count = 0;
  621:                 foreach my $img (@loginimages) {
  622:                     if ($designhash{$dom.'.login.'.$img} ne '') {
  623:                         $custom_img_count ++;
  624:                     }
  625:                 }
  626:                 foreach my $role (@roles) {
  627:                     if ($designhash{$dom.'.'.$role.'.img'} ne '') {
  628:                         $custom_img_count ++;
  629:                     }
  630:                 }
  631:                 if ($custom_img_count > 0) {
  632:                     &Apache::lonconfigsettings::print_header($r,$phase,$context);
  633:                     my $switch_server = &check_switchserver($dom,$confname);
  634:                     $r->print(
  635:     &mt('Domain configuration settings have yet to be saved for this domain via the web-based domain preferences interface.').'<br />'.
  636:     &mt("While this remains so, you must switch to the domain's primary library server in order to update settings.").'<br /><br />'.
  637:     &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 />'.
  638:     &mt("However, you will still need to switch to the domain's primary library server to upload new images or logos.").'<br /><br />');
  639:                     if ($switch_server) {
  640:                         $r->print($switch_server.' '.&mt('to primary library server for domain: [_1]',$dom));
  641:                     }
  642:                     $r->print(&Apache::loncommon::end_page());
  643:                     return OK;
  644:                 }
  645:             }
  646:         }
  647:         &Apache::lonconfigsettings::display_choices($r,$phase,$context,\@prefs_order,\%prefs);
  648:     }
  649:     return OK;
  650: }
  651: 
  652: sub process_changes {
  653:     my ($r,$dom,$confname,$action,$roles,$values,$lastactref) = @_;
  654:     my %domconfig;
  655:     if (ref($values) eq 'HASH') {
  656:         %domconfig = %{$values};
  657:     }
  658:     my $output;
  659:     if ($action eq 'login') {
  660:         $output = &modify_login($r,$dom,$confname,$lastactref,%domconfig);
  661:     } elsif ($action eq 'rolecolors') {
  662:         $output = &modify_rolecolors($r,$dom,$confname,$roles,
  663:                                      $lastactref,%domconfig);
  664:     } elsif ($action eq 'quotas') {
  665:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  666:     } elsif ($action eq 'autoenroll') {
  667:         $output = &modify_autoenroll($dom,$lastactref,%domconfig);
  668:     } elsif ($action eq 'autoupdate') {
  669:         $output = &modify_autoupdate($dom,%domconfig);
  670:     } elsif ($action eq 'autocreate') {
  671:         $output = &modify_autocreate($dom,%domconfig);
  672:     } elsif ($action eq 'directorysrch') {
  673:         $output = &modify_directorysrch($dom,$lastactref,%domconfig);
  674:     } elsif ($action eq 'usercreation') {
  675:         $output = &modify_usercreation($dom,%domconfig);
  676:     } elsif ($action eq 'selfcreation') {
  677:         $output = &modify_selfcreation($dom,$lastactref,%domconfig);
  678:     } elsif ($action eq 'usermodification') {
  679:         $output = &modify_usermodification($dom,%domconfig);
  680:     } elsif ($action eq 'contacts') {
  681:         $output = &modify_contacts($dom,$lastactref,%domconfig);
  682:     } elsif ($action eq 'defaults') {
  683:         $output = &modify_defaults($dom,$lastactref,%domconfig);
  684:     } elsif ($action eq 'scantron') {
  685:         $output = &modify_scantron($r,$dom,$confname,$lastactref,%domconfig);
  686:     } elsif ($action eq 'coursecategories') {
  687:         $output = &modify_coursecategories($dom,$lastactref,%domconfig);
  688:     } elsif ($action eq 'serverstatuses') {
  689:         $output = &modify_serverstatuses($dom,%domconfig);
  690:     } elsif ($action eq 'requestcourses') {
  691:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  692:     } elsif ($action eq 'requestauthor') {
  693:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  694:     } elsif ($action eq 'helpsettings') {
  695:         $output = &modify_helpsettings($r,$dom,$confname,$lastactref,%domconfig);
  696:     } elsif ($action eq 'coursedefaults') {
  697:         $output = &modify_coursedefaults($dom,$lastactref,%domconfig);
  698:     } elsif ($action eq 'selfenrollment') {
  699:         $output = &modify_selfenrollment($dom,$lastactref,%domconfig)
  700:     } elsif ($action eq 'usersessions') {
  701:         $output = &modify_usersessions($dom,$lastactref,%domconfig);
  702:     } elsif ($action eq 'loadbalancing') {
  703:         $output = &modify_loadbalancing($dom,%domconfig);
  704:     } elsif ($action eq 'passwords') {
  705:         $output = &modify_passwords($r,$dom,$confname,$lastactref,%domconfig);
  706:     } elsif ($action eq 'wafproxy') {
  707:         $output = &modify_wafproxy($dom,$action,$lastactref,%domconfig);
  708:     } elsif ($action eq 'ipaccess') {
  709:         $output = &modify_ipaccess($dom,$lastactref,%domconfig);
  710:     }
  711:     return $output;
  712: }
  713: 
  714: sub print_config_box {
  715:     my ($r,$dom,$confname,$phase,$action,$item,$settings) = @_;
  716:     my $rowtotal = 0;
  717:     my $output;
  718:     if ($action eq 'coursecategories') {
  719:         $output = &coursecategories_javascript($settings);
  720:     } elsif ($action eq 'defaults') {
  721:         $output = &defaults_javascript($settings); 
  722:     } elsif ($action eq 'passwords') {
  723:         $output = &passwords_javascript();
  724:     } elsif ($action eq 'helpsettings') {
  725:         my (%privs,%levelscurrent);
  726:         my %full=();
  727:         my %levels=(
  728:                      course => {},
  729:                      domain => {},
  730:                      system => {},
  731:                    );
  732:         my $context = 'domain';
  733:         my $crstype = 'Course';
  734:         my $formname = 'display';
  735:         &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
  736:         my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
  737:         $output =
  738:             &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,\%full,
  739:                                                       \@templateroles);
  740:     } elsif ($action eq 'wafproxy') {
  741:         $output .= &wafproxy_javascript($dom);
  742:     } elsif ($action eq 'autoupdate') {
  743:         $output .= &autoupdate_javascript();
  744:     } elsif ($action eq 'autoenroll') {
  745:         $output .= &autoenroll_javascript();
  746:     } elsif ($action eq 'login') {
  747:         $output .= &saml_javascript();
  748:     } elsif ($action eq 'ipaccess') {
  749:         $output .= &ipaccess_javascript($settings);
  750:     }
  751:     $output .=
  752:          '<table class="LC_nested_outer">
  753:           <tr>
  754:            <th class="LC_left_item LC_middle"><span class="LC_nobreak">'.
  755:            &mt($item->{text}).'&nbsp;'.
  756:            &Apache::loncommon::help_open_topic($item->{'help'}).'</span></th>'."\n".
  757:           '</tr>';
  758:     $rowtotal ++;
  759:     my $numheaders = 1;
  760:     if (ref($item->{'header'}) eq 'ARRAY') {
  761:         $numheaders = scalar(@{$item->{'header'}});
  762:     }
  763:     if ($numheaders > 1) {
  764:         my $colspan = '';
  765:         my $rightcolspan = '';
  766:         my $leftnobr = '';  
  767:         if (($action eq 'rolecolors') || ($action eq 'defaults') ||
  768:             ($action eq 'directorysrch') ||
  769:             (($action eq 'login') && ($numheaders < 5))) {
  770:             $colspan = ' colspan="2"';
  771:         }
  772:         if ($action eq 'usersessions') {
  773:             $rightcolspan = ' colspan="3"'; 
  774:         }
  775:         if ($action eq 'passwords') {
  776:             $leftnobr = ' LC_nobreak';
  777:         }
  778:         $output .= '
  779:           <tr>
  780:            <td>
  781:             <table class="LC_nested">
  782:              <tr class="LC_info_row">
  783:               <td class="LC_left_item'.$leftnobr.'"'.$colspan.'>'.&mt($item->{'header'}->[0]->{'col1'}).'</td>
  784:               <td class="LC_right_item"'.$rightcolspan.'>'.&mt($item->{'header'}->[0]->{'col2'}).'</td>
  785:              </tr>';
  786:         $rowtotal ++;
  787:         if (($action eq 'autoupdate') || ($action eq 'usercreation') || ($action eq 'selfcreation') ||
  788:             ($action eq 'usermodification') || ($action eq 'defaults') || ($action eq 'coursedefaults') ||
  789:             ($action eq 'selfenrollment') || ($action eq 'usersessions') || ($action eq 'directorysrch') ||
  790:             ($action eq 'helpsettings') || ($action eq 'contacts') || ($action eq 'wafproxy')) {
  791:             $output .= $item->{'print'}->('top',$dom,$settings,\$rowtotal);
  792:         } elsif ($action eq 'passwords') {
  793:             $output .= $item->{'print'}->('top',$dom,$confname,$settings,\$rowtotal);
  794:         } elsif ($action eq 'coursecategories') {
  795:             $output .= $item->{'print'}->('top',$dom,$item,$settings,\$rowtotal);
  796:         } elsif ($action eq 'scantron') {
  797:             $output .= $item->{'print'}->($r,'top',$dom,$confname,$settings,\$rowtotal);
  798:         } elsif ($action eq 'login') {
  799:             if ($numheaders == 5) {
  800:                 $colspan = ' colspan="2"';
  801:                 $output .= &print_login('service',$dom,$confname,$phase,$settings,\$rowtotal);
  802:             } else {
  803:                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal);
  804:             }
  805:         } elsif (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
  806:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
  807:         } elsif ($action eq 'rolecolors') {
  808:             $output .= &print_rolecolors($phase,'student',$dom,$confname,$settings,\$rowtotal);
  809:         }
  810:         $output .= '
  811:            </table>
  812:           </td>
  813:          </tr>
  814:          <tr>
  815:            <td>
  816:             <table class="LC_nested">
  817:              <tr class="LC_info_row">
  818:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col1'}).'</td>
  819:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col2'}).'</td>
  820:              </tr>';
  821:             $rowtotal ++;
  822:         if (($action eq 'autoupdate') || ($action eq 'usercreation') ||
  823:             ($action eq 'selfcreation') || ($action eq 'selfenrollment') ||
  824:             ($action eq 'usersessions') || ($action eq 'coursecategories') ||
  825:             ($action eq 'contacts') || ($action eq 'passwords')) {
  826:             if ($action eq 'coursecategories') {
  827:                 $output .= &print_coursecategories('middle',$dom,$item,$settings,\$rowtotal);
  828:                 $colspan = ' colspan="2"';
  829:             } elsif ($action eq 'passwords') {
  830:                 $output .= $item->{'print'}->('middle',$dom,$confname,$settings,\$rowtotal);
  831:             } else {
  832:                 $output .= $item->{'print'}->('middle',$dom,$settings,\$rowtotal);
  833:             }
  834:             $output .= '
  835:            </table>
  836:           </td>
  837:          </tr>
  838:          <tr>
  839:            <td>
  840:             <table class="LC_nested">
  841:              <tr class="LC_info_row">
  842:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
  843:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
  844:              </tr>'."\n";
  845:             if ($action eq 'coursecategories') {
  846:                 $output .= &print_coursecategories('bottom',$dom,$item,$settings,\$rowtotal);
  847:             } elsif (($action eq 'contacts') || ($action eq 'passwords')) {
  848:                 if ($action eq 'passwords') {
  849:                     $output .= $item->{'print'}->('lower',$dom,$confname,$settings,\$rowtotal);
  850:                 } else {
  851:                     $output .= $item->{'print'}->('lower',$dom,$settings,\$rowtotal);
  852:                 }
  853:                 $output .= '
  854:              </tr>
  855:             </table>
  856:            </td>
  857:           </tr>
  858:           <tr>
  859:            <td>
  860:             <table class="LC_nested">
  861:              <tr class="LC_info_row">
  862:               <td class="LC_left_item'.$leftnobr.'"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
  863:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td></tr>'."\n";
  864:                 if ($action eq 'passwords') {
  865:                     $output .= $item->{'print'}->('bottom',$dom,$confname,$settings,\$rowtotal);
  866:                 } else {
  867:                     $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
  868:                 }
  869:                 $output .= '
  870:             </table>
  871:           </td>
  872:          </tr>
  873:          <tr>';
  874:             } else {
  875:                 $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
  876:             }
  877:             $rowtotal ++;
  878:         } elsif (($action eq 'usermodification') || ($action eq 'coursedefaults') ||
  879:                  ($action eq 'defaults') || ($action eq 'directorysrch') ||
  880:                  ($action eq 'helpsettings') || ($action eq 'wafproxy')) {
  881:             $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
  882:         } elsif ($action eq 'scantron') {
  883:             $output .= $item->{'print'}->($r,'bottom',$dom,$confname,$settings,\$rowtotal);
  884:         } elsif ($action eq 'login') {
  885:             if ($numheaders == 5) {
  886:                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal).'
  887:            </table>
  888:           </td>
  889:          </tr>
  890:          <tr>
  891:            <td>
  892:             <table class="LC_nested">
  893:              <tr class="LC_info_row">
  894:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
  895:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td></tr>'.
  896:                        &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
  897:                 $rowtotal ++;
  898:             } else {
  899:                 $output .= &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
  900:             }
  901:             $output .= '
  902:            </table>
  903:           </td>
  904:          </tr>
  905:          <tr>
  906:            <td>
  907:             <table class="LC_nested">
  908:              <tr class="LC_info_row">';
  909:             if ($numheaders == 5) {
  910:                 $output .= '
  911:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
  912:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
  913:              </tr>';
  914:             } else {
  915:                 $output .= '
  916:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
  917:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
  918:              </tr>';
  919:             }
  920:             $rowtotal ++;
  921:             $output .= &print_login('headtag',$dom,$confname,$phase,$settings,\$rowtotal).'
  922:            </table>
  923:           </td>
  924:          </tr>
  925:          <tr>
  926:            <td>
  927:             <table class="LC_nested">
  928:              <tr class="LC_info_row">';
  929:             if ($numheaders == 5) {
  930:                 $output .= '
  931:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[4]->{'col1'}).'</td>
  932:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[4]->{'col2'}).'</td>
  933:              </tr>';
  934:             } else {
  935:                 $output .= '
  936:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
  937:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
  938:              </tr>';
  939:             }
  940:             $rowtotal ++;
  941:             $output .= &print_login('saml',$dom,$confname,$phase,$settings,\$rowtotal);
  942:         } elsif ($action eq 'requestcourses') {
  943:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
  944:             $rowtotal ++;
  945:             $output .= &print_studentcode($settings,\$rowtotal).'
  946:            </table>
  947:           </td>
  948:          </tr>
  949:          <tr>
  950:            <td>
  951:             <table class="LC_nested">
  952:              <tr class="LC_info_row">
  953:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
  954:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td> </tr>'.
  955:                        &textbookcourses_javascript($settings).
  956:                        &print_textbookcourses($dom,'textbooks',$settings,\$rowtotal).'
  957:             </table>
  958:            </td>
  959:           </tr>
  960:          <tr>
  961:            <td>
  962:             <table class="LC_nested">
  963:              <tr class="LC_info_row">
  964:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
  965:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td> </tr>'.
  966:                        &print_textbookcourses($dom,'templates',$settings,\$rowtotal).'
  967:             </table>
  968:            </td>
  969:           </tr>
  970:           <tr>
  971:            <td>
  972:             <table class="LC_nested">
  973:              <tr class="LC_info_row">
  974:               <td class="LC_left_item"'.$colspan.' valign="top">'.&mt($item->{'header'}->[4]->{'col1'}).'</td>
  975:               <td class="LC_right_item" valign="top">'.&mt($item->{'header'}->[4]->{'col2'}).'</td>
  976:              </tr>'.
  977:             &print_validation_rows('requestcourses',$dom,$settings,\$rowtotal);
  978:         } elsif ($action eq 'requestauthor') {
  979:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
  980:             $rowtotal ++;
  981:         } elsif ($action eq 'rolecolors') {
  982:             $output .= &print_rolecolors($phase,'coordinator',$dom,$confname,$settings,\$rowtotal).'
  983:            </table>
  984:           </td>
  985:          </tr>
  986:          <tr>
  987:            <td>
  988:             <table class="LC_nested">
  989:              <tr class="LC_info_row">
  990:               <td class="LC_left_item"'.$colspan.' valign="top">'.
  991:                &mt($item->{'header'}->[2]->{'col1'}).'</td>
  992:               <td class="LC_right_item" valign="top">'.
  993:                &mt($item->{'header'}->[2]->{'col2'}).'</td>
  994:              </tr>'.
  995:             &print_rolecolors($phase,'author',$dom,$confname,$settings,\$rowtotal).'
  996:            </table>
  997:           </td>
  998:          </tr>
  999:          <tr>
 1000:            <td>
 1001:             <table class="LC_nested">
 1002:              <tr class="LC_info_row">
 1003:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1004:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
 1005:              </tr>'.
 1006:             &print_rolecolors($phase,'admin',$dom,$confname,$settings,\$rowtotal);
 1007:             $rowtotal += 2;
 1008:         }
 1009:     } else {
 1010:         $output .= '
 1011:           <tr>
 1012:            <td>
 1013:             <table class="LC_nested">
 1014:              <tr class="LC_info_row">';
 1015:         if ($action eq 'login') {
 1016:             $output .= '  
 1017:               <td class="LC_left_item" colspan="2">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
 1018:         } elsif ($action eq 'serverstatuses') {
 1019:             $output .= '
 1020:               <td class="LC_left_item" valign="top">'.&mt($item->{'header'}->[0]->{'col1'}).
 1021:               '<br />('.&mt('Automatic access for Dom. Coords.').')</td>';
 1022: 
 1023:         } else {
 1024:             $output .= '
 1025:               <td class="LC_left_item" valign="top">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
 1026:         }
 1027:         if (defined($item->{'header'}->[0]->{'col3'})) {
 1028:             $output .= '<td class="LC_left_item" valign="top">'.
 1029:                        &mt($item->{'header'}->[0]->{'col2'});
 1030:             if ($action eq 'serverstatuses') {
 1031:                 $output .= '<br />(<tt>'.&mt('user1:domain1,user2:domain2 etc.').'</tt>)';
 1032:             } 
 1033:         } else {
 1034:             $output .= '<td class="LC_right_item" valign="top">'.
 1035:                        &mt($item->{'header'}->[0]->{'col2'});
 1036:         }
 1037:         $output .= '</td>';
 1038:         if ($item->{'header'}->[0]->{'col3'}) {
 1039:             if (defined($item->{'header'}->[0]->{'col4'})) {
 1040:                 $output .= '<td class="LC_left_item" valign="top">'.
 1041:                             &mt($item->{'header'}->[0]->{'col3'});
 1042:             } else {
 1043:                 $output .= '<td class="LC_right_item" valign="top">'.
 1044:                            &mt($item->{'header'}->[0]->{'col3'});
 1045:             }
 1046:             if ($action eq 'serverstatuses') {
 1047:                 $output .= '<br />(<tt>'.&mt('IP1,IP2 etc.').'</tt>)';
 1048:             }
 1049:             $output .= '</td>';
 1050:         }
 1051:         if ($item->{'header'}->[0]->{'col4'}) {
 1052:             $output .= '<td class="LC_right_item" valign="top">'.
 1053:                        &mt($item->{'header'}->[0]->{'col4'});
 1054:         }
 1055:         $output .= '</tr>';
 1056:         $rowtotal ++;
 1057:         if ($action eq 'quotas') {
 1058:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
 1059:         } elsif (($action eq 'autoenroll') || ($action eq 'autocreate') || 
 1060:                  ($action eq 'serverstatuses') || ($action eq 'loadbalancing') ||
 1061:                  ($action eq 'ipaccess')) {
 1062:             $output .= $item->{'print'}->($dom,$settings,\$rowtotal);
 1063:         }
 1064:     }
 1065:     $output .= '
 1066:    </table>
 1067:   </td>
 1068:  </tr>
 1069: </table><br />';
 1070:     return ($output,$rowtotal);
 1071: }
 1072: 
 1073: sub print_login {
 1074:     my ($caller,$dom,$confname,$phase,$settings,$rowtotal) = @_;
 1075:     my ($css_class,$datatable,$switchserver,%lt);
 1076:     my %choices = &login_choices();
 1077:     if (($caller eq 'help') || ($caller eq 'headtag') || ($caller eq 'saml')) {
 1078:         %lt = &login_file_options();
 1079:         $switchserver = &check_switchserver($dom,$confname);
 1080:     }
 1081: 
 1082:     if ($caller eq 'service') {
 1083:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 1084:         my $choice = $choices{'disallowlogin'};
 1085:         $css_class = ' class="LC_odd_row"';
 1086:         $datatable .= '<tr'.$css_class.'><td>'.$choice.'</td>'.
 1087:                       '<td align="right"><table><tr><th>'.$choices{'hostid'}.'</th>'.
 1088:                       '<th>'.$choices{'server'}.'</th>'.
 1089:                       '<th>'.$choices{'serverpath'}.'</th>'.
 1090:                       '<th>'.$choices{'custompath'}.'</th>'.
 1091:                       '<th><span class="LC_nobreak">'.$choices{'exempt'}.'</span></th></tr>'."\n";
 1092:         my %disallowed;
 1093:         if (ref($settings) eq 'HASH') {
 1094:             if (ref($settings->{'loginvia'}) eq 'HASH') {
 1095:                %disallowed = %{$settings->{'loginvia'}};
 1096:             }
 1097:         }
 1098:         foreach my $lonhost (sort(keys(%servers))) {
 1099:             my $direct = 'selected="selected"';
 1100:             if (ref($disallowed{$lonhost}) eq 'HASH') {
 1101:                 if ($disallowed{$lonhost}{'server'} ne '') {
 1102:                     $direct = '';
 1103:                 }
 1104:             }
 1105:             $datatable .= '<tr><td>'.$servers{$lonhost}.'</td>'.
 1106:                           '<td><select name="'.$lonhost.'_server">'.
 1107:                           '<option value=""'.$direct.'>'.$choices{'directlogin'}.
 1108:                           '</option>';
 1109:             foreach my $hostid (sort(keys(%servers))) {
 1110:                 next if ($servers{$hostid} eq $servers{$lonhost});
 1111:                 my $selected = '';
 1112:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
 1113:                     if ($hostid eq $disallowed{$lonhost}{'server'}) {
 1114:                         $selected = 'selected="selected"';
 1115:                     }
 1116:                 }
 1117:                 $datatable .= '<option value="'.$hostid.'"'.$selected.'>'.
 1118:                               $servers{$hostid}.'</option>';
 1119:             }
 1120:             $datatable .= '</select></td>'.
 1121:                           '<td><select name="'.$lonhost.'_serverpath">';
 1122:             foreach my $path ('','/','/adm/login','/adm/roles','custom') {
 1123:                 my $pathname = $path;
 1124:                 if ($path eq 'custom') {
 1125:                     $pathname = &mt('Custom Path').' ->';
 1126:                 }
 1127:                 my $selected = '';
 1128:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
 1129:                     if ($path eq $disallowed{$lonhost}{'serverpath'}) {
 1130:                         $selected = 'selected="selected"';
 1131:                     }
 1132:                 } elsif ($path eq '') {
 1133:                     $selected = 'selected="selected"';
 1134:                 }
 1135:                 $datatable .= '<option value="'.$path.'"'.$selected.'>'.$pathname.'</option>';
 1136:             }
 1137:             $datatable .= '</select></td>';
 1138:             my ($custom,$exempt);
 1139:             if (ref($disallowed{$lonhost}) eq 'HASH') {
 1140:                 $custom = $disallowed{$lonhost}{'custompath'};
 1141:                 $exempt = $disallowed{$lonhost}{'exempt'};
 1142:             }
 1143:             $datatable .= '<td><input type="text" name="'.$lonhost.'_custompath" size="6" value="'.$custom.'" /></td>'.
 1144:                           '<td><input type="text" name="'.$lonhost.'_exempt" size="8" value="'.$exempt.'" /></td>'.
 1145:                           '</tr>';
 1146:         }
 1147:         $datatable .= '</table></td></tr>';
 1148:         return $datatable;
 1149:     } elsif ($caller eq 'page') {
 1150:         my %defaultchecked = ( 
 1151:                                'coursecatalog' => 'on',
 1152:                                'helpdesk'      => 'on',
 1153:                                'adminmail'     => 'off',
 1154:                                'newuser'       => 'off',
 1155:                              );
 1156:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
 1157:         my (%checkedon,%checkedoff);
 1158:         foreach my $item (@toggles) {
 1159:             if ($defaultchecked{$item} eq 'on') { 
 1160:                 $checkedon{$item} = ' checked="checked" ';
 1161:                 $checkedoff{$item} = ' ';
 1162:             } elsif ($defaultchecked{$item} eq 'off') {
 1163:                 $checkedoff{$item} = ' checked="checked" ';
 1164:                 $checkedon{$item} = ' ';
 1165:             }
 1166:         }
 1167:         my @images = ('img','logo','domlogo','login');
 1168:         my @alttext = ('img','logo','domlogo');
 1169:         my @logintext = ('textcol','bgcol');
 1170:         my @bgs = ('pgbg','mainbg','sidebg');
 1171:         my @links = ('link','alink','vlink');
 1172:         my %designhash = &Apache::loncommon::get_domainconf($dom);
 1173:         my %defaultdesign = %Apache::loncommon::defaultdesign;
 1174:         my (%is_custom,%designs);
 1175:         my %defaults = (
 1176:                        font => $defaultdesign{'login.font'},
 1177:                        );
 1178:         foreach my $item (@images) {
 1179:             $defaults{$item} = $defaultdesign{'login.'.$item};
 1180:             $defaults{'showlogo'}{$item} = 1;
 1181:         }
 1182:         foreach my $item (@bgs) {
 1183:             $defaults{'bgs'}{$item} = $defaultdesign{'login.'.$item};
 1184:         }
 1185:         foreach my $item (@logintext) {
 1186:             $defaults{'logintext'}{$item} = $defaultdesign{'login.'.$item};
 1187:         }
 1188:         foreach my $item (@links) {
 1189:             $defaults{'links'}{$item} = $defaultdesign{'login.'.$item};
 1190:         }
 1191:         if (ref($settings) eq 'HASH') {
 1192:             foreach my $item (@toggles) {
 1193:                 if ($settings->{$item} eq '1') {
 1194:                     $checkedon{$item} =  ' checked="checked" ';
 1195:                     $checkedoff{$item} = ' ';
 1196:                 } elsif ($settings->{$item} eq '0') {
 1197:                     $checkedoff{$item} =  ' checked="checked" ';
 1198:                     $checkedon{$item} = ' ';
 1199:                 }
 1200:             }
 1201:             foreach my $item (@images) {
 1202:                 if (defined($settings->{$item})) {
 1203:                     $designs{$item} = $settings->{$item};
 1204:                     $is_custom{$item} = 1;
 1205:                 }
 1206:                 if (defined($settings->{'showlogo'}{$item})) {
 1207:                     $designs{'showlogo'}{$item} = $settings->{'showlogo'}{$item};
 1208:                 }
 1209:             }
 1210:             foreach my $item (@alttext) {
 1211:                 if (ref($settings->{'alttext'}) eq 'HASH') {
 1212:                     if ($settings->{'alttext'}->{$item} ne '') {
 1213:                         $designs{'alttext'}{$item} = $settings->{'alttext'}{$item};
 1214:                     }
 1215:                 }
 1216:             }
 1217:             foreach my $item (@logintext) {
 1218:                 if ($settings->{$item} ne '') {
 1219:                     $designs{'logintext'}{$item} = $settings->{$item};
 1220:                     $is_custom{$item} = 1;
 1221:                 }
 1222:             }
 1223:             if ($settings->{'font'} ne '') {
 1224:                 $designs{'font'} = $settings->{'font'};
 1225:                 $is_custom{'font'} = 1;
 1226:             }
 1227:             foreach my $item (@bgs) {
 1228:                 if ($settings->{$item} ne '') {
 1229:                     $designs{'bgs'}{$item} = $settings->{$item};
 1230:                     $is_custom{$item} = 1;
 1231:                 }
 1232:             }
 1233:             foreach my $item (@links) {
 1234:                 if ($settings->{$item} ne '') {
 1235:                     $designs{'links'}{$item} = $settings->{$item};
 1236:                     $is_custom{$item} = 1;
 1237:                 }
 1238:             }
 1239:         } else {
 1240:             if ($designhash{$dom.'.login.font'} ne '') {
 1241:                 $designs{'font'} = $designhash{$dom.'.login.font'};
 1242:                 $is_custom{'font'} = 1;
 1243:             }
 1244:             foreach my $item (@images) {
 1245:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1246:                     $designs{$item} = $designhash{$dom.'.login.'.$item};
 1247:                     $is_custom{$item} = 1;
 1248:                 }
 1249:             }
 1250:             foreach my $item (@bgs) {
 1251:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1252:                     $designs{'bgs'}{$item} = $designhash{$dom.'.login.'.$item};
 1253:                     $is_custom{$item} = 1;
 1254:                 }
 1255:             }
 1256:             foreach my $item (@links) {
 1257:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1258:                     $designs{'links'}{$item} = $designhash{$dom.'.login.'.$item};
 1259:                     $is_custom{$item} = 1;
 1260:                 }
 1261:             }
 1262:         }
 1263:         my %alt_text = &Apache::lonlocal::texthash  ( img => 'Log-in banner',
 1264:                                                       logo => 'Institution Logo',
 1265:                                                       domlogo => 'Domain Logo',
 1266:                                                       login => 'Login box');
 1267:         my $itemcount = 1;
 1268:         foreach my $item (@toggles) {
 1269:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1270:             $datatable .=  
 1271:                 '<tr'.$css_class.'><td colspan="2">'.$choices{$item}.
 1272:                 '</td><td>'.
 1273:                 '<span class="LC_nobreak"><label><input type="radio" name="'.
 1274:                 $item.'"'.$checkedon{$item}.' value="1" />'.&mt('Yes').
 1275:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'"'.
 1276:                 $checkedoff{$item}.' value="0" />'.&mt('No').'</label></span></td>'.
 1277:                 '</tr>';
 1278:             $itemcount ++;
 1279:         }
 1280:         $datatable .= &display_color_options($dom,$confname,$phase,'login',$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal,\@logintext);
 1281:         $datatable .= '</tr></table></td></tr>';
 1282:     } elsif ($caller eq 'help') {
 1283:         my ($defaulturl,$defaulttype,%url,%type,%langchoices);
 1284:         my $itemcount = 1;
 1285:         $defaulturl = '/adm/loginproblems.html';
 1286:         $defaulttype = 'default';
 1287:         %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
 1288:         my @currlangs;
 1289:         if (ref($settings) eq 'HASH') {
 1290:             if (ref($settings->{'helpurl'}) eq 'HASH') {
 1291:                 foreach my $key (sort(keys(%{$settings->{'helpurl'}}))) {
 1292:                     next if ($settings->{'helpurl'}{$key} eq '');
 1293:                     $url{$key} = $settings->{'helpurl'}{$key}.'?inhibitmenu=yes';
 1294:                     $type{$key} = 'custom';
 1295:                     unless ($key eq 'nolang') {
 1296:                         push(@currlangs,$key);
 1297:                     }
 1298:                 }
 1299:             } elsif ($settings->{'helpurl'} ne '') {
 1300:                 $type{'nolang'} = 'custom';
 1301:                 $url{'nolang'} = $settings->{'helpurl'}.'?inhibitmenu=yes';
 1302:             }
 1303:         }
 1304:         foreach my $lang ('nolang',sort(@currlangs)) {
 1305:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1306:             $datatable .= '<tr'.$css_class.'>';
 1307:             if ($url{$lang} eq '') {
 1308:                 $url{$lang} = $defaulturl;
 1309:             }
 1310:             if ($type{$lang} eq '') {
 1311:                 $type{$lang} = $defaulttype;
 1312:             }
 1313:             $datatable .= '<td colspan="2"><span class="LC_nobreak">';
 1314:             if ($lang eq 'nolang') {
 1315:                 $datatable .= &mt('Log-in help page if no specific language file: [_1]',
 1316:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1317:             } else {
 1318:                 $datatable .= &mt('Log-in help page for language: [_1] is [_2]',
 1319:                                   $langchoices{$lang},
 1320:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1321:             }
 1322:             $datatable .= '</span></td>'."\n".
 1323:                           '<td class="LC_left_item">';
 1324:             if ($type{$lang} eq 'custom') {
 1325:                 $datatable .= '<span class="LC_nobreak"><label>'.
 1326:                               '<input type="checkbox" name="loginhelpurl_del" value="'.$lang.'" />'.
 1327:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1328:             } else {
 1329:                 $datatable .= $lt{'upl'};
 1330:             }
 1331:             $datatable .='<br />';
 1332:             if ($switchserver) {
 1333:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1334:             } else {
 1335:                 $datatable .= '<input type="file" name="loginhelpurl_'.$lang.'" />';
 1336:             }
 1337:             $datatable .= '</td></tr>';
 1338:             $itemcount ++;
 1339:         }
 1340:         my @addlangs;
 1341:         foreach my $lang (sort(keys(%langchoices))) {
 1342:             next if ((grep(/^\Q$lang\E$/,@currlangs)) || ($lang eq 'x_chef'));
 1343:             push(@addlangs,$lang);
 1344:         }
 1345:         if (@addlangs > 0) {
 1346:             my %toadd;
 1347:             map { $toadd{$_} = $langchoices{$_} ; } @addlangs;
 1348:             $toadd{''} = &mt('Select');
 1349:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1350:             $datatable .= '<tr'.$css_class.'><td class="LC_left_item" colspan="2">'.
 1351:                           &mt('Add log-in help page for a specific language:').'&nbsp;'.
 1352:                           &Apache::loncommon::select_form('','loginhelpurl_add_lang',\%toadd).
 1353:                           '</td><td class="LC_left_item">'.$lt{'upl'}.'<br />';
 1354:             if ($switchserver) {
 1355:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1356:             } else {
 1357:                 $datatable .= '<input type="file" name="loginhelpurl_add_file" />';
 1358:             }
 1359:             $datatable .= '</td></tr>';
 1360:             $itemcount ++;
 1361:         }
 1362:         $datatable .= &captcha_choice('login',$settings,$itemcount);
 1363:     } elsif ($caller eq 'headtag') {
 1364:         my %domservers = &Apache::lonnet::get_servers($dom);
 1365:         my $choice = $choices{'headtag'};
 1366:         $css_class = ' class="LC_odd_row"';
 1367:         $datatable .= '<tr'.$css_class.'><td colspan="2">'.$choice.'</td>'.
 1368:                       '<td align="left"><table><tr><th>'.$choices{'hostid'}.'</th>'.
 1369:                       '<th>'.$choices{'current'}.'</th>'.
 1370:                       '<th>'.$choices{'action'}.'</th>'.
 1371:                       '<th>'.$choices{'exempt'}.'</th></tr>'."\n";
 1372:         my (%currurls,%currexempt);
 1373:         if (ref($settings) eq 'HASH') {
 1374:             if (ref($settings->{'headtag'}) eq 'HASH') {
 1375:                 foreach my $lonhost (keys(%{$settings->{'headtag'}})) {
 1376:                     if (ref($settings->{'headtag'}{$lonhost}) eq 'HASH') {
 1377:                         $currurls{$lonhost} = $settings->{'headtag'}{$lonhost}{'url'};
 1378:                         $currexempt{$lonhost} = $settings->{'headtag'}{$lonhost}{'exempt'};
 1379:                     }
 1380:                 }
 1381:             }
 1382:         }
 1383:         foreach my $lonhost (sort(keys(%domservers))) {
 1384:             my $exempt = &check_exempt_addresses($currexempt{$lonhost});
 1385:             $datatable .= '<tr><td>'.$domservers{$lonhost}.'</td>';
 1386:             if ($currurls{$lonhost}) {
 1387:                 $datatable .= '<td class="LC_right_item"><a href="'.
 1388:                               "javascript:void(open('$currurls{$lonhost}?inhibitmenu=yes','Custom_HeadTag',
 1389:                               'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
 1390:                               '">'.$lt{'curr'}.'</a></td>'.
 1391:                               '<td><span class="LC_nobreak"><label>'.
 1392:                               '<input type="checkbox" name="loginheadtag_del" value="'.$lonhost.'" />'.
 1393:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1394:             } else {
 1395:                 $datatable .= '<td class="LC_right_item">'.$lt{'none'}.'</td><td>'.$lt{'upl'};
 1396:             }
 1397:             $datatable .='<br />';
 1398:             if ($switchserver) {
 1399:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1400:             } else {
 1401:                 $datatable .= '<input type="file" name="loginheadtag_'.$lonhost.'" />';
 1402:             }
 1403:             $datatable .= '</td><td><input type="text" name="loginheadtagexempt_'.$lonhost.'" value="'.$exempt.'" /></td></tr>';
 1404:         }
 1405:         $datatable .= '</table></td></tr>';
 1406:     } elsif ($caller eq 'saml') {
 1407:         my %domservers = &Apache::lonnet::get_servers($dom);
 1408:         $datatable .= '<tr><td colspan="3" style="text-align: left">'.
 1409:                       '<table><tr><th>'.$choices{'hostid'}.'</th>'.
 1410:                       '<th>'.$choices{'samllanding'}.'</th>'.
 1411:                       '<th>'.$choices{'samloptions'}.'</th></tr>'."\n";
 1412:         my (%saml,%samltext,%samlimg,%samlalt,%samlurl,%samltitle,%samlnotsso,%styleon,%styleoff);
 1413:         foreach my $lonhost (keys(%domservers)) {
 1414:             $samlurl{$lonhost} = '/adm/sso';
 1415:             $styleon{$lonhost} = 'display:none';
 1416:             $styleoff{$lonhost} = '';
 1417:         }
 1418:         if (ref($settings->{'saml'}) eq 'HASH') {
 1419:             foreach my $lonhost (keys(%{$settings->{'saml'}})) {
 1420:                 if (ref($settings->{'saml'}{$lonhost}) eq 'HASH') {
 1421:                     $saml{$lonhost} = 1;
 1422:                     $samltext{$lonhost} = $settings->{'saml'}{$lonhost}{'text'};
 1423:                     $samlimg{$lonhost} = $settings->{'saml'}{$lonhost}{'img'};
 1424:                     $samlalt{$lonhost} = $settings->{'saml'}{$lonhost}{'alt'};
 1425:                     $samlurl{$lonhost} = $settings->{'saml'}{$lonhost}{'url'};
 1426:                     $samltitle{$lonhost} = $settings->{'saml'}{$lonhost}{'title'};
 1427:                     $samlnotsso{$lonhost} = $settings->{'saml'}{$lonhost}{'notsso'};
 1428:                     $styleon{$lonhost} = '';
 1429:                     $styleoff{$lonhost} = 'display:none';
 1430:                 } else {
 1431:                     $styleon{$lonhost} = 'display:none';
 1432:                     $styleoff{$lonhost} = '';
 1433:                 }
 1434:             }
 1435:         }
 1436:         my $itemcount = 1;
 1437:         foreach my $lonhost (sort(keys(%domservers))) {
 1438:             my $samlon = ' ';
 1439:             my $samloff = ' checked="checked" ';
 1440:             if ($saml{$lonhost}) {
 1441:                 $samlon = $samloff;
 1442:                 $samloff = ' ';
 1443:             }
 1444:             my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1445:             $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.$domservers{$lonhost}.'</span></td>'.
 1446:                           '<td><span class="LC_nobreak"><label><input type="radio" name="saml_'.$lonhost.'"'.$samloff.
 1447:                           'onclick="toggleSamlOptions(this.form,'."'$lonhost'".');" value="0" />'.
 1448:                           &mt('No').'</label>'.('&nbsp;'x2).
 1449:                           '<label><input type="radio" name="saml_'.$lonhost.'"'.$samlon.
 1450:                           'onclick="toggleSamlOptions(this.form,'."'$lonhost'".');" value="1" />'.
 1451:                           &mt('Yes').'</label></span></td>'.
 1452:                           '<td id="samloptionson_'.$lonhost.'" style="'.$styleon{$lonhost}.'" width="100%">'.
 1453:                           '<table><tr><th colspan="5" align="center">'.&mt('SSO').'</th><th align="center">'.
 1454:                           '<span class="LC_nobreak">'.&mt('Non-SSO').'</span></th></tr>'.
 1455:                           '<tr><th>'.&mt('Text').'</th><th>'.&mt('Image').'</th>'.
 1456:                           '<th>'.&mt('Alt Text').'</th><th>'.&mt('URL').'</th>'.
 1457:                           '<th>'.&mt('Tool Tip').'</th><th>'.&mt('Text').'</th></tr>'.
 1458:                           '<tr'.$css_class.'><td><input type="text" name="saml_text_'.$lonhost.'" size="8" value="'.
 1459:                           $samltext{$lonhost}.'" /></td><td>';
 1460:             if ($samlimg{$lonhost}) {
 1461:                 $datatable .= '<img src="'.$samlimg{$lonhost}.'" /><br />'.
 1462:                               '<span class="LC_nobreak"><label>'.
 1463:                               '<input type="checkbox" name="saml_img_del" value="'.$lonhost.'" />'.
 1464:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1465:             } else {
 1466:                 $datatable .= $lt{'upl'};
 1467:             }
 1468:             $datatable .='<br />';
 1469:             if ($switchserver) {
 1470:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1471:             } else {
 1472:                 $datatable .= '<input type="file" name="saml_img_'.$lonhost.'" />';
 1473:             }
 1474:             $datatable .= '</td>'.
 1475:                           '<td><input type="text" name="saml_alt_'.$lonhost.'" size="20" '.
 1476:                           'value="'.$samlalt{$lonhost}.'" /></td>'.
 1477:                           '<td><input type="text" name="saml_url_'.$lonhost.'" size="8" '.
 1478:                           'value="'.$samlurl{$lonhost}.'" /></td>'.
 1479:                           '<td><textarea name="saml_title_'.$lonhost.'" rows="3" cols="15">'.
 1480:                           $samltitle{$lonhost}.'</textarea></td>'.
 1481:                           '<td><input type="text" name="saml_notsso_'.$lonhost.'" size="8" '.
 1482:                           'value="'.$samlnotsso{$lonhost}.'" /></td></tr>'.
 1483:                           '</table></td>'.
 1484:                           '<td id="samloptionsoff_'.$lonhost.'" style="'.$styleoff{$lonhost}.'" width="100%">&nbsp;</td></tr>';
 1485:            $itemcount ++;
 1486:         }
 1487:         $datatable .= '</table></td></tr>';
 1488:     }
 1489:     return $datatable;
 1490: }
 1491: 
 1492: sub login_choices {
 1493:     my %choices =
 1494:         &Apache::lonlocal::texthash (
 1495:             coursecatalog => 'Display Course/Community Catalog link?',
 1496:             adminmail     => "Display Administrator's E-mail Address?",
 1497:             helpdesk      => 'Display "Contact Helpdesk" link',
 1498:             disallowlogin => "Login page requests redirected",
 1499:             hostid        => "Server",
 1500:             server        => "Redirect to:",
 1501:             serverpath    => "Path",
 1502:             custompath    => "Custom", 
 1503:             exempt        => "Exempt IP(s)",
 1504:             directlogin   => "No redirect",
 1505:             newuser       => "Link to create a user account",
 1506:             img           => "Header",
 1507:             logo          => "Main Logo",
 1508:             domlogo       => "Domain Logo",
 1509:             login         => "Log-in Header", 
 1510:             textcol       => "Text color",
 1511:             bgcol         => "Box color",
 1512:             bgs           => "Background colors",
 1513:             links         => "Link colors",
 1514:             font          => "Font color",
 1515:             pgbg          => "Header",
 1516:             mainbg        => "Page",
 1517:             sidebg        => "Login box",
 1518:             link          => "Link",
 1519:             alink         => "Active link",
 1520:             vlink         => "Visited link",
 1521:             headtag       => "Custom markup",
 1522:             action        => "Action",
 1523:             current       => "Current",
 1524:             samllanding   => "Dual login?",
 1525:             samloptions   => "Options",
 1526:             alttext       => "Alt text",
 1527:         );
 1528:     return %choices;
 1529: }
 1530: 
 1531: sub login_file_options {
 1532:       return &Apache::lonlocal::texthash(
 1533:                                            del     => 'Delete?',
 1534:                                            rep     => 'Replace:',
 1535:                                            upl     => 'Upload:',
 1536:                                            curr    => 'View contents',
 1537:                                            default => 'Default',
 1538:                                            custom  => 'Custom',
 1539:                                            none    => 'None',
 1540:       );
 1541: }
 1542: 
 1543: sub print_ipaccess {
 1544:     my ($dom,$settings,$rowtotal) = @_;
 1545:     my $css_class;
 1546:     my $itemcount = 0;
 1547:     my $datatable;
 1548:     my %ordered;
 1549:     if (ref($settings) eq 'HASH') {
 1550:         foreach my $item (keys(%{$settings})) {
 1551:             if (ref($settings->{$item}) eq 'HASH') {
 1552:                 my $num = $settings->{$item}{'order'};
 1553:                 if ($num eq '') {
 1554:                     $num = scalar(keys(%{$settings}));
 1555:                 }
 1556:                 $ordered{$num} = $item;
 1557:             }
 1558:         }
 1559:     }
 1560:     my $maxnum = scalar(keys(%ordered));
 1561:     if (keys(%ordered)) {
 1562:         my @items = sort { $a <=> $b } keys(%ordered);
 1563:         for (my $i=0; $i<@items; $i++) {
 1564:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1565:             my $item = $ordered{$items[$i]};
 1566:             my ($name,$ipranges,%commblocks,%courses);
 1567:             if (ref($settings->{$item}) eq 'HASH') {
 1568:                 $name = $settings->{$item}->{'name'};
 1569:                 $ipranges = $settings->{$item}->{'ip'};
 1570:                 if (ref($settings->{$item}->{'commblocks'}) eq 'HASH') {
 1571:                     %commblocks = %{$settings->{$item}->{'commblocks'}};
 1572:                 }
 1573:                 if (ref($settings->{$item}->{'courses'}) eq 'HASH') {
 1574:                     %courses = %{$settings->{$item}->{'courses'}};
 1575:                 }
 1576:             }
 1577:             my $chgstr = ' onchange="javascript:reorderIPaccess(this.form,'."'ipaccess_pos_".$item."'".');"';
 1578:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 1579:                          .'<select name="ipaccess_pos_'.$item.'"'.$chgstr.'>';
 1580:             for (my $k=0; $k<=$maxnum; $k++) {
 1581:                 my $vpos = $k+1;
 1582:                 my $selstr;
 1583:                 if ($k == $i) {
 1584:                     $selstr = ' selected="selected" ';
 1585:                 }
 1586:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 1587:             }
 1588:             $datatable .= '</select>'.('&nbsp;'x2).
 1589:                 '<label><input type="checkbox" name="ipaccess_del" value="'.$item.'" />'.
 1590:                 &mt('Delete?').'</label></span></td>'.
 1591:                 '<td colspan="2"><input type="hidden" name="ipaccess_id_'.$i.'" value="'.$item.'" />'.
 1592:                 &ipaccess_options($i,$itemcount,$dom,$name,$ipranges,\%commblocks,\%courses).
 1593:                 '</td></tr>';
 1594:             $itemcount ++;
 1595:         }
 1596:     }
 1597:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1598:     my $chgstr = ' onchange="javascript:reorderIPaccess(this.form,'."'ipaccess_pos_add'".');"';
 1599:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 1600:                   '<input type="hidden" name="ipaccess_maxnum" value="'.$maxnum.'" />'."\n".
 1601:                   '<select name="ipaccess_pos_add"'.$chgstr.'>';
 1602:     for (my $k=0; $k<$maxnum+1; $k++) {
 1603:         my $vpos = $k+1;
 1604:         my $selstr;
 1605:         if ($k == $maxnum) {
 1606:             $selstr = ' selected="selected" ';
 1607:         }
 1608:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 1609:     }
 1610:     $datatable .= '</select>&nbsp;'."\n".
 1611:                   '<input type="checkbox" name="ipaccess_add" value="1" />'.&mt('Add').'</span></td>'."\n".
 1612:                   '<td colspan="2">'.
 1613:                   &ipaccess_options('add',$itemcount,$dom).
 1614:                   '</td>'."\n".
 1615:                   '</tr>'."\n";
 1616:     $$rowtotal ++;
 1617:     return $datatable;
 1618: }
 1619: 
 1620: sub ipaccess_options {
 1621:     my ($num,$itemcount,$dom,$name,$ipranges,$blocksref,$coursesref) = @_;
 1622:     my (%currblocks,%currcourses,$output);
 1623:     if (ref($blocksref) eq 'HASH') {
 1624:         %currblocks = %{$blocksref};
 1625:     }
 1626:     if (ref($coursesref) eq 'HASH') {
 1627:         %currcourses = %{$coursesref};
 1628:     }
 1629:     $output = '<fieldset><legend>'.&mt('Location(s)').'</legend>'.
 1630:               '<span class="LC_nobreak">'.&mt('Name').':&nbsp;'.
 1631:               '<input type="text" name="ipaccess_name_'.$num.'" value="'.$name.'" />'.
 1632:               '</span></fieldset>'.
 1633:               '<fieldset><legend>'.&mt('IP Range(s)').'</legend>'.
 1634:               &mt('Format for each IP range').': '.&mt('A.B.C.D/N or A.B.C.D-E.F.G.H').'<br />'.
 1635:               &mt('Range(s) will be stored as IP netblock(s) in CIDR notation (comma separated)').'<br />'.
 1636:               '<textarea name="ipaccess_range_'.$num.'" rows="3" cols="80">'.
 1637:               $ipranges.'</textarea></fieldset>'.
 1638:               '<fieldset><legend>'.&mt('Functionality Blocked?').'</legend>'.
 1639:               &blocker_checkboxes($num,$blocksref).'</fieldset>'.
 1640:               '<fieldset><legend>'.&mt('Courses/Communities allowed').'</legend>'.
 1641:               '<table>';
 1642:     foreach my $cid (sort(keys(%currcourses))) {
 1643:         my %courseinfo = &Apache::lonnet::coursedescription($cid,{'one_time' => 1});
 1644:         $output .= '<tr><td><span class="LC_nobreak">'.
 1645:                    '<label><input type="checkbox" name="ipaccess_course_delete_'.$num.'" value="'.$cid.'" />'.
 1646:                    &mt('Delete?').'&nbsp;<span class="LC_cusr_emph">'.$courseinfo{'description'}.'</span></label></span>'.
 1647:                    ' <span class="LC_fontsize_medium">('.$cid.')</span></td></tr>';
 1648:     }
 1649:     $output .= '<tr><td><span class="LC_nobreak">'.&mt('Add').':&nbsp;'.
 1650:                '<input type="text" name="ipaccess_cdesc_'.$num.'" value="" onfocus="this.blur();opencrsbrowser('."'display','ipaccess_cnum_$num','ipaccess_cdom_$num','ipaccess_cdesc_$num'".');" />'.
 1651:                 &Apache::loncommon::selectcourse_link('display','ipaccess_cnum_'.$num,'ipaccess_cdom_'.$num,'ipaccess_cdesc_'.$num,$dom,undef,'Course/Community').
 1652:                '<input type="hidden" name="ipaccess_cnum_'.$num.'" value="" />'.
 1653:                '<input type="hidden" name="ipaccess_cdom_'.$num.'" value="" />'.
 1654:                '</span></td></tr></table>'."\n".
 1655:                '</fieldset>';
 1656:     return $output;
 1657: }
 1658: 
 1659: sub blocker_checkboxes {
 1660:     my ($num,$blocks) = @_;
 1661:     my ($typeorder,$types) = &commblocktype_text();
 1662:     my $numinrow = 6;
 1663:     my $output = '<table>';
 1664:     for (my $i=0; $i<@{$typeorder}; $i++) {
 1665:         my $block = $typeorder->[$i];
 1666:         my $blockstatus;
 1667:         if (ref($blocks) eq 'HASH') {
 1668:             if ($blocks->{$block} eq 'on') {
 1669:                 $blockstatus = 'checked="checked"';
 1670:             }
 1671:         }
 1672:         my $rem = $i%($numinrow);
 1673:         if ($rem == 0) {
 1674:             if ($i > 0) {
 1675:                 $output .= '</tr>';
 1676:             }
 1677:             $output .= '<tr>';
 1678:         }
 1679:         if ($i == scalar(@{$typeorder})-1) {
 1680:             my $colsleft = $numinrow-$rem;
 1681:             if ($colsleft > 1) {
 1682:                 $output .= '<td colspan="'.$colsleft.'">';
 1683:             } else {
 1684:                 $output .= '<td>';
 1685:             }
 1686:         } else {
 1687:             $output .= '<td>';
 1688:         }
 1689:         my $item = 'ipaccess_block_'.$num;
 1690:         if ($blockstatus) {
 1691:             $blockstatus = ' '.$blockstatus;
 1692:         }
 1693:         $output .= '<span class="LC_nobreak"><label>'."\n".
 1694:                    '<input type="checkbox" name="'.$item.'"'.
 1695:                    $blockstatus.' value="'.$block.'"'.' />'.
 1696:                    $types->{$block}.'</label></span>'."\n".
 1697:                    '<br /></td>';
 1698:     }
 1699:     $output .= '</tr></table>';
 1700:     return $output;
 1701: }
 1702: 
 1703: sub commblocktype_text {
 1704:     my %types = &Apache::lonlocal::texthash(
 1705:         'com' => 'Messaging',
 1706:         'chat' => 'Chat Room',
 1707:         'boards' => 'Discussion',
 1708:         'port' => 'Portfolio',
 1709:         'groups' => 'Groups',
 1710:         'blogs' => 'Blogs',
 1711:         'about' => 'User Information',
 1712:         'printout' => 'Printouts',
 1713:         'passwd' => 'Change Password',
 1714:         'grades' => 'Gradebook',
 1715:         'search' => 'Course search',
 1716:         'wishlist' => 'Stored links',
 1717:         'annotate' => 'Annotations',
 1718:     );
 1719:     my $typeorder = ['com','chat','boards','port','groups','blogs','about','wishlist','printout','grades','search','annotate','passwd'];
 1720:     return ($typeorder,\%types);
 1721: }
 1722: 
 1723: sub print_rolecolors {
 1724:     my ($phase,$role,$dom,$confname,$settings,$rowtotal) = @_;
 1725:     my %choices = &color_font_choices();
 1726:     my @bgs = ('pgbg','tabbg','sidebg');
 1727:     my @links = ('link','alink','vlink');
 1728:     my @images = ('img');
 1729:     my %alt_text = &Apache::lonlocal::texthash(img => "Banner for $role role");
 1730:     my %designhash = &Apache::loncommon::get_domainconf($dom);
 1731:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 1732:     my (%is_custom,%designs);
 1733:     my %defaults = &role_defaults($role,\@bgs,\@links,\@images);
 1734:     if (ref($settings) eq 'HASH') {
 1735:         if (ref($settings->{$role}) eq 'HASH') {
 1736:             if ($settings->{$role}->{'img'} ne '') {
 1737:                 $designs{'img'} = $settings->{$role}->{'img'};
 1738:                 $is_custom{'img'} = 1;
 1739:             }
 1740:             if ($settings->{$role}->{'font'} ne '') {
 1741:                 $designs{'font'} = $settings->{$role}->{'font'};
 1742:                 $is_custom{'font'} = 1;
 1743:             }
 1744:             if ($settings->{$role}->{'fontmenu'} ne '') {
 1745:                 $designs{'fontmenu'} = $settings->{$role}->{'fontmenu'};
 1746:                 $is_custom{'fontmenu'} = 1;
 1747:             }
 1748:             foreach my $item (@bgs) {
 1749:                 if ($settings->{$role}->{$item} ne '') {
 1750:                     $designs{'bgs'}{$item} = $settings->{$role}->{$item};
 1751:                     $is_custom{$item} = 1;
 1752:                 }
 1753:             }
 1754:             foreach my $item (@links) {
 1755:                 if ($settings->{$role}->{$item} ne '') {
 1756:                     $designs{'links'}{$item} = $settings->{$role}->{$item};
 1757:                     $is_custom{$item} = 1;
 1758:                 }
 1759:             }
 1760:         }
 1761:     } else {
 1762:         if ($designhash{$dom.'.'.$role.'.img'} ne '') {
 1763:             $designs{img} = $designhash{$dom.'.'.$role.'.img'};
 1764:             $is_custom{'img'} = 1;
 1765:         }
 1766:         if ($designhash{$dom.'.'.$role.'.fontmenu'} ne '') {
 1767:             $designs{fontmenu} = $designhash{$dom.'.'.$role.'.fontmenu'};
 1768:             $is_custom{'fontmenu'} = 1; 
 1769:         }
 1770:         if ($designhash{$dom.'.'.$role.'.font'} ne '') {
 1771:             $designs{font} = $designhash{$dom.'.'.$role.'.font'};
 1772:             $is_custom{'font'} = 1;
 1773:         }
 1774:         foreach my $item (@bgs) {
 1775:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 1776:                 $designs{'bgs'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 1777:                 $is_custom{$item} = 1;
 1778:             
 1779:             }
 1780:         }
 1781:         foreach my $item (@links) {
 1782:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 1783:                 $designs{'links'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 1784:                 $is_custom{$item} = 1;
 1785:             }
 1786:         }
 1787:     }
 1788:     my $itemcount = 1;
 1789:     my $datatable = &display_color_options($dom,$confname,$phase,$role,$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal);
 1790:     $datatable .= '</tr></table></td></tr>';
 1791:     return $datatable;
 1792: }
 1793: 
 1794: sub role_defaults {
 1795:     my ($role,$bgs,$links,$images,$logintext) = @_;
 1796:     my %defaults;
 1797:     unless ((ref($bgs) eq 'ARRAY') && (ref($links) eq 'ARRAY') && (ref($images) eq 'ARRAY')) {
 1798:         return %defaults;
 1799:     }
 1800:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 1801:     if ($role eq 'login') {
 1802:         %defaults = (
 1803:                        font => $defaultdesign{$role.'.font'},
 1804:                     );
 1805:         if (ref($logintext) eq 'ARRAY') {
 1806:             foreach my $item (@{$logintext}) {
 1807:                 $defaults{'logintext'}{$item} = $defaultdesign{$role.'.'.$item};
 1808:             }
 1809:         }
 1810:         foreach my $item (@{$images}) {
 1811:             $defaults{'showlogo'}{$item} = 1;
 1812:         }
 1813:     } else {
 1814:         %defaults = (
 1815:                        img => $defaultdesign{$role.'.img'},
 1816:                        font => $defaultdesign{$role.'.font'},
 1817:                        fontmenu => $defaultdesign{$role.'.fontmenu'},
 1818:                     );
 1819:     }
 1820:     foreach my $item (@{$bgs}) {
 1821:         $defaults{'bgs'}{$item} = $defaultdesign{$role.'.'.$item};
 1822:     }
 1823:     foreach my $item (@{$links}) {
 1824:         $defaults{'links'}{$item} = $defaultdesign{$role.'.'.$item};
 1825:     }
 1826:     foreach my $item (@{$images}) {
 1827:         $defaults{$item} = $defaultdesign{$role.'.'.$item};
 1828:     }
 1829:     return %defaults;
 1830: }
 1831: 
 1832: sub display_color_options {
 1833:     my ($dom,$confname,$phase,$role,$itemcount,$choices,$is_custom,$defaults,$designs,
 1834:         $images,$bgs,$links,$alt_text,$rowtotal,$logintext) = @_;
 1835:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 1836:     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1837:     my $datatable = '<tr'.$css_class.'>'.
 1838:         '<td>'.$choices->{'font'}.'</td>';
 1839:     if (!$is_custom->{'font'}) {
 1840:         $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span class="css_default_'.$role.'_font" style="color: '.$defaults->{'font'}.';">'.$defaults->{'font'}.'</span></td>';
 1841:     } else {
 1842:         $datatable .= '<td>&nbsp;</td>';
 1843:     }
 1844:     my $current_color = $designs->{'font'} ? $designs->{'font'} : $defaults->{'font'};
 1845: 
 1846:     $datatable .= '<td><span class="LC_nobreak">'.
 1847:                   '<input type="text" class="colorchooser" size="10" name="'.$role.'_font"'.
 1848:                   ' value="'.$current_color.'" />&nbsp;'.
 1849:                   '&nbsp;</span></td></tr>';
 1850:     unless ($role eq 'login') { 
 1851:         $datatable .= '<tr'.$css_class.'>'.
 1852:                       '<td>'.$choices->{'fontmenu'}.'</td>';
 1853:         if (!$is_custom->{'fontmenu'}) {
 1854:             $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span class="css_default_'.$role.'_font" style="color: '.$defaults->{'fontmenu'}.';">'.$defaults->{'fontmenu'}.'</span></td>';
 1855:         } else {
 1856:             $datatable .= '<td>&nbsp;</td>';
 1857:         }
 1858: 	$current_color = $designs->{'fontmenu'} ?
 1859: 	    $designs->{'fontmenu'} : $defaults->{'fontmenu'};
 1860:         $datatable .= '<td><span class="LC_nobreak">'.
 1861:                       '<input class="colorchooser" type="text" size="10" name="'
 1862: 		      .$role.'_fontmenu"'.
 1863:                       ' value="'.$current_color.'" />&nbsp;'.
 1864:                       '&nbsp;</span></td></tr>';
 1865:     }
 1866:     my $switchserver = &check_switchserver($dom,$confname);
 1867:     foreach my $img (@{$images}) {
 1868: 	$itemcount ++;
 1869:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1870:         $datatable .= '<tr'.$css_class.'>'.
 1871:                       '<td>'.$choices->{$img};
 1872:         my ($imgfile,$img_import,$login_hdr_pick,$logincolors,$alttext);
 1873:         if ($role eq 'login') {
 1874:             if ($img eq 'login') {
 1875:                 $login_hdr_pick =
 1876:                     &login_header_options($img,$role,$defaults,$is_custom,$choices);
 1877:                 $logincolors =
 1878:                     &login_text_colors($img,$role,$logintext,$phase,$choices,
 1879:                                        $designs,$defaults);
 1880:             } else { 
 1881:                 if ($img ne 'domlogo') {
 1882:                     $datatable.= &logo_display_options($img,$defaults,$designs);
 1883:                 }
 1884:                 if (ref($designs->{'alttext'}) eq 'HASH') {
 1885:                     $alttext = $designs->{'alttext'}{$img};
 1886:                 }
 1887:             }
 1888:         }
 1889:         $datatable .= '</td>';
 1890:         if ($designs->{$img} ne '') {
 1891:             $imgfile = $designs->{$img};
 1892: 	    $img_import = ($imgfile =~ m{^/adm/});
 1893:         } else {
 1894:             $imgfile = $defaults->{$img};
 1895:         }
 1896:         if ($imgfile) {
 1897:             my ($showfile,$fullsize);
 1898:             if ($imgfile =~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
 1899:                 my $urldir = $1;
 1900:                 my $filename = $2;
 1901:                 my @info = &Apache::lonnet::stat_file($designs->{$img});
 1902:                 if (@info) {
 1903:                     my $thumbfile = 'tn-'.$filename;
 1904:                     my @thumb=&Apache::lonnet::stat_file($urldir.'/'.$thumbfile);
 1905:                     if (@thumb) {
 1906:                         $showfile = $urldir.'/'.$thumbfile;
 1907:                     } else {
 1908:                         $showfile = $imgfile;
 1909:                     }
 1910:                 } else {
 1911:                     $showfile = '';
 1912:                 }
 1913:             } elsif ($imgfile =~ m-^/(adm/[^/]+)/([^/]+)$-) {
 1914:                 $showfile = $imgfile;
 1915:                 my $imgdir = $1;
 1916:                 my $filename = $2;
 1917:                 if (-e "$londocroot/$imgdir/tn-".$filename) {
 1918:                     $showfile = "/$imgdir/tn-".$filename;
 1919:                 } else {
 1920:                     my $input = $londocroot.$imgfile;
 1921:                     my $output = "$londocroot/$imgdir/tn-".$filename;
 1922:                     if (!-e $output) {
 1923:                         my ($width,$height) = &thumb_dimensions();
 1924:                         my ($fullwidth,$fullheight) = &check_dimensions($input);
 1925:                         if ($fullwidth ne '' && $fullheight ne '') {
 1926:                             if ($fullwidth > $width && $fullheight > $height) { 
 1927:                                 my $size = $width.'x'.$height;
 1928:                                 my @args = ('convert','-sample',$size,$input,$output);
 1929:                                 system({$args[0]} @args);
 1930:                                 $showfile = "/$imgdir/tn-".$filename;
 1931:                             }
 1932:                         }
 1933:                     }
 1934:                 }
 1935:             }
 1936:             if ($showfile) {
 1937:                 if ($showfile =~ m{^/(adm|res)/}) {
 1938:                     if ($showfile =~ m{^/res/}) {
 1939:                         my $local_showfile =
 1940:                             &Apache::lonnet::filelocation('',$showfile);
 1941:                         &Apache::lonnet::repcopy($local_showfile);
 1942:                     }
 1943:                     $showfile = &Apache::loncommon::lonhttpdurl($showfile);
 1944:                 }
 1945:                 if ($imgfile) {
 1946:                     if ($imgfile  =~ m{^/(adm|res)/}) {
 1947:                         if ($imgfile =~ m{^/res/}) {
 1948:                             my $local_imgfile =
 1949:                                 &Apache::lonnet::filelocation('',$imgfile);
 1950:                             &Apache::lonnet::repcopy($local_imgfile);
 1951:                         }
 1952:                         $fullsize = &Apache::loncommon::lonhttpdurl($imgfile);
 1953:                     } else {
 1954:                         $fullsize = $imgfile;
 1955:                     }
 1956:                 }
 1957:                 $datatable .= '<td>';
 1958:                 if ($img eq 'login') {
 1959:                     $datatable .= $login_hdr_pick;
 1960:                 } 
 1961:                 $datatable .= &image_changes($is_custom->{$img},$alt_text->{$img},$img_import,
 1962:                                              $showfile,$fullsize,$role,$img,$imgfile,$logincolors);
 1963:             } else {
 1964:                 $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 1965:                               &mt('Upload:').'<br />';
 1966:             }
 1967:         } else {
 1968:             $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 1969:                           &mt('Upload:').'<br />';
 1970:         }
 1971:         if ($switchserver) {
 1972:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1973:         } else {
 1974:             if ($img ne 'login') { # suppress file selection for Log-in header
 1975:                 $datatable .='&nbsp;<input type="file" name="'.$role.'_'.$img.'" />';
 1976:             }
 1977:         }
 1978:         if (($role eq 'login') && ($img ne 'login')) {
 1979:             $datatable .= ('&nbsp;' x2).' <span class="LC_nobreak"><label>'.$choices->{'alttext'}.':'.
 1980:                           '<input type="text" name="'.$role.'_alt_'.$img.'" size="10" value="'.$alttext.'" />'.
 1981:                           '</label></span>';
 1982:         }
 1983:         $datatable .= '</td></tr>';
 1984:     }
 1985:     $itemcount ++;
 1986:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1987:     $datatable .= '<tr'.$css_class.'>'.
 1988:                   '<td>'.$choices->{'bgs'}.'</td>';
 1989:     my $bgs_def;
 1990:     foreach my $item (@{$bgs}) {
 1991:         if (!$is_custom->{$item}) {
 1992:             $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>';
 1993:         }
 1994:     }
 1995:     if ($bgs_def) {
 1996:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$bgs_def.'</tr></table></td>';
 1997:     } else {
 1998:         $datatable .= '<td>&nbsp;</td>';
 1999:     }
 2000:     $datatable .= '<td class="LC_right_item">'.
 2001:                   '<table border="0"><tr>';
 2002: 
 2003:     foreach my $item (@{$bgs}) {
 2004:         $datatable .= '<td align="center">'.$choices->{$item};
 2005: 	my $color = $designs->{'bgs'}{$item} ? $designs->{'bgs'}{$item} : $defaults->{'bgs'}{$item};
 2006:         if ($designs->{'bgs'}{$item}) {
 2007:             $datatable .= '&nbsp;';
 2008:         }
 2009:         $datatable .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 2010:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 2011:     }
 2012:     $datatable .= '</tr></table></td></tr>';
 2013:     $itemcount ++;
 2014:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2015:     $datatable .= '<tr'.$css_class.'>'.
 2016:                   '<td>'.$choices->{'links'}.'</td>';
 2017:     my $links_def;
 2018:     foreach my $item (@{$links}) {
 2019:         if (!$is_custom->{$item}) {
 2020:             $links_def .= '<td>'.$choices->{$item}.'<br /><span class="css_default_'.$role.'_'.$item.'" style="color: '.$defaults->{'links'}{$item}.';">'.$defaults->{'links'}{$item}.'</span></td>';
 2021:         }
 2022:     }
 2023:     if ($links_def) {
 2024:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$links_def.'</tr></table></td>';
 2025:     } else {
 2026:         $datatable .= '<td>&nbsp;</td>';
 2027:     }
 2028:     $datatable .= '<td class="LC_right_item">'.
 2029:                   '<table border="0"><tr>';
 2030:     foreach my $item (@{$links}) {
 2031: 	my $color = $designs->{'links'}{$item} ? $designs->{'links'}{$item} : $defaults->{'links'}{$item};
 2032:         $datatable .= '<td align="center">'.$choices->{$item}."\n";
 2033:         if ($designs->{'links'}{$item}) {
 2034:             $datatable.='&nbsp;';
 2035:         }
 2036:         $datatable .= '<br /><input type="text" size="8" class="colorchooser" name="'.$role.'_'.$item.'" value="'.$color.
 2037:                       '" /></td>';
 2038:     }
 2039:     $$rowtotal += $itemcount;
 2040:     return $datatable;
 2041: }
 2042: 
 2043: sub logo_display_options {
 2044:     my ($img,$defaults,$designs) = @_;
 2045:     my $checkedon;
 2046:     if (ref($defaults) eq 'HASH') {
 2047:         if (ref($defaults->{'showlogo'}) eq 'HASH') {
 2048:             if ($defaults->{'showlogo'}{$img}) {
 2049:                 $checkedon = 'checked="checked" ';     
 2050:             }
 2051:         } 
 2052:     }
 2053:     if (ref($designs) eq 'HASH') {
 2054:         if (ref($designs->{'showlogo'}) eq 'HASH') {
 2055:             if (defined($designs->{'showlogo'}{$img})) {
 2056:                 if ($designs->{'showlogo'}{$img} == 0) {
 2057:                     $checkedon = '';
 2058:                 } elsif ($designs->{'showlogo'}{$img} == 1) {
 2059:                     $checkedon = 'checked="checked" ';
 2060:                 }
 2061:             }
 2062:         }
 2063:     }
 2064:     return '<br /><label>&nbsp;&nbsp;<input type="checkbox" name="'.
 2065:            'login_showlogo_'.$img.'" value="1" '.$checkedon.'/>'.
 2066:            &mt('show').'</label>'."\n";
 2067: }
 2068: 
 2069: sub login_header_options  {
 2070:     my ($img,$role,$defaults,$is_custom,$choices) = @_;
 2071:     my $output = '';
 2072:     if ((!$is_custom->{'textcol'}) || (!$is_custom->{'bgcol'})) {
 2073:         $output .= &mt('Text default(s):').'<br />';
 2074:         if (!$is_custom->{'textcol'}) {
 2075:             $output .= $choices->{'textcol'}.':&nbsp;'.$defaults->{'logintext'}{'textcol'}.
 2076:                        '&nbsp;&nbsp;&nbsp;';
 2077:         }
 2078:         if (!$is_custom->{'bgcol'}) {
 2079:             $output .= $choices->{'bgcol'}.':&nbsp;'.
 2080:                        '<span id="css_'.$role.'_font" style="background-color: '.
 2081:                        $defaults->{'logintext'}{'bgcol'}.';">&nbsp;&nbsp;&nbsp;</span>';
 2082:         }
 2083:         $output .= '<br />';
 2084:     }
 2085:     $output .='<br />';
 2086:     return $output;
 2087: }
 2088: 
 2089: sub login_text_colors {
 2090:     my ($img,$role,$logintext,$phase,$choices,$designs,$defaults) = @_;
 2091:     my $color_menu = '<table border="0"><tr>';
 2092:     foreach my $item (@{$logintext}) {
 2093:         $color_menu .= '<td align="center">'.$choices->{$item};
 2094:         my $color = $designs->{'logintext'}{$item} ? $designs->{'logintext'}{$item} : $defaults->{'logintext'}{$item};
 2095:         $color_menu .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 2096:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 2097:     }
 2098:     $color_menu .= '</tr></table><br />';
 2099:     return $color_menu;
 2100: }
 2101: 
 2102: sub image_changes {
 2103:     my ($is_custom,$alt_text,$img_import,$showfile,$fullsize,$role,$img,$imgfile,$logincolors) = @_;
 2104:     my $output;
 2105:     if ($img eq 'login') {
 2106:         $output = '</td><td>'.$logincolors; # suppress image for Log-in header
 2107:     } elsif (!$is_custom) {
 2108:         if ($img ne 'domlogo') {
 2109:             $output = &mt('Default image:').'<br />';
 2110:         } else {
 2111:             $output = &mt('Default in use:').'<br />';
 2112:         }
 2113:     }
 2114:     if ($img ne 'login') {
 2115:         if ($img_import) {
 2116:             $output .= '<input type="hidden" name="'.$role.'_import_'.$img.'" value="'.$imgfile.'" />';
 2117:         }
 2118:         $output .= '<a href="'.$fullsize.'" target="_blank"><img src="'.
 2119:                    $showfile.'" alt="'.$alt_text.'" border="0" /></a></td>';
 2120:         if ($is_custom) {
 2121:             $output .= '<td>'.$logincolors.'<span class="LC_nobreak"><label>'.
 2122:                        '<input type="checkbox" name="'.
 2123:                        $role.'_del_'.$img.'" value="1" />'.&mt('Delete?').
 2124:                        '</label>&nbsp;'.&mt('Replace:').'</span><br />';
 2125:         } else {
 2126:             $output .= '<td valign="middle">'.$logincolors.&mt('Upload:').'<br />';
 2127:         }
 2128:     }
 2129:     return $output;
 2130: }
 2131: 
 2132: sub print_quotas {
 2133:     my ($dom,$settings,$rowtotal,$action) = @_;
 2134:     my $context;
 2135:     if ($action eq 'quotas') {
 2136:         $context = 'tools';
 2137:     } else {
 2138:         $context = $action;
 2139:     }
 2140:     my ($datatable,$defaultquota,$authorquota,@usertools,@options,%validations);
 2141:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 2142:     my $typecount = 0;
 2143:     my ($css_class,%titles);
 2144:     if ($context eq 'requestcourses') {
 2145:         @usertools = ('official','unofficial','community','textbook');
 2146:         @options =('norequest','approval','validate','autolimit');
 2147:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
 2148:         %titles = &courserequest_titles();
 2149:     } elsif ($context eq 'requestauthor') {
 2150:         @usertools = ('author');
 2151:         @options = ('norequest','approval','automatic');
 2152:         %titles = &authorrequest_titles();
 2153:     } else {
 2154:         @usertools = ('aboutme','blog','webdav','portfolio');
 2155:         %titles = &tool_titles();
 2156:     }
 2157:     if (ref($types) eq 'ARRAY') {
 2158:         foreach my $type (@{$types}) {
 2159:             my ($currdefquota,$currauthorquota);
 2160:             unless (($context eq 'requestcourses') ||
 2161:                     ($context eq 'requestauthor')) {
 2162:                 if (ref($settings) eq 'HASH') {
 2163:                     if (ref($settings->{defaultquota}) eq 'HASH') {
 2164:                         $currdefquota = $settings->{defaultquota}->{$type};
 2165:                     } else {
 2166:                         $currdefquota = $settings->{$type};
 2167:                     }
 2168:                     if (ref($settings->{authorquota}) eq 'HASH') {
 2169:                         $currauthorquota = $settings->{authorquota}->{$type};
 2170:                     }
 2171:                 }
 2172:             }
 2173:             if (defined($usertypes->{$type})) {
 2174:                 $typecount ++;
 2175:                 $css_class = $typecount%2?' class="LC_odd_row"':'';
 2176:                 $datatable .= '<tr'.$css_class.'>'.
 2177:                               '<td>'.$usertypes->{$type}.'</td>'.
 2178:                               '<td class="LC_left_item">';
 2179:                 if ($context eq 'requestcourses') {
 2180:                     $datatable .= '<table><tr>';
 2181:                 }
 2182:                 my %cell;  
 2183:                 foreach my $item (@usertools) {
 2184:                     if ($context eq 'requestcourses') {
 2185:                         my ($curroption,$currlimit);
 2186:                         if (ref($settings) eq 'HASH') {
 2187:                             if (ref($settings->{$item}) eq 'HASH') {
 2188:                                 $curroption = $settings->{$item}->{$type};
 2189:                                 if ($curroption =~ /^autolimit=(\d*)$/) {
 2190:                                     $currlimit = $1; 
 2191:                                 }
 2192:                             }
 2193:                         }
 2194:                         if (!$curroption) {
 2195:                             $curroption = 'norequest';
 2196:                         }
 2197:                         $datatable .= '<th>'.$titles{$item}.'</th>';
 2198:                         foreach my $option (@options) {
 2199:                             my $val = $option;
 2200:                             if ($option eq 'norequest') {
 2201:                                 $val = 0;  
 2202:                             }
 2203:                             if ($option eq 'validate') {
 2204:                                 my $canvalidate = 0;
 2205:                                 if (ref($validations{$item}) eq 'HASH') { 
 2206:                                     if ($validations{$item}{$type}) {
 2207:                                         $canvalidate = 1;
 2208:                                     }
 2209:                                 }
 2210:                                 next if (!$canvalidate);
 2211:                             }
 2212:                             my $checked = '';
 2213:                             if ($option eq $curroption) {
 2214:                                 $checked = ' checked="checked"';
 2215:                             } elsif ($option eq 'autolimit') {
 2216:                                 if ($curroption =~ /^autolimit/) {
 2217:                                     $checked = ' checked="checked"';
 2218:                                 }                       
 2219:                             } 
 2220:                             $cell{$item} .= '<span class="LC_nobreak"><label>'.
 2221:                                   '<input type="radio" name="crsreq_'.$item.
 2222:                                   '_'.$type.'" value="'.$val.'"'.$checked.' />'.
 2223:                                   $titles{$option}.'</label>';
 2224:                             if ($option eq 'autolimit') {
 2225:                                 $cell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2226:                                                 $item.'_limit_'.$type.'" size="1" '.
 2227:                                                 'value="'.$currlimit.'" />';
 2228:                             }
 2229:                             $cell{$item} .= '</span> ';
 2230:                             if ($option eq 'autolimit') {
 2231:                                 $cell{$item} .= $titles{'unlimited'};
 2232:                             }
 2233:                         }
 2234:                     } elsif ($context eq 'requestauthor') {
 2235:                         my $curroption;
 2236:                         if (ref($settings) eq 'HASH') {
 2237:                             $curroption = $settings->{$type};
 2238:                         }
 2239:                         if (!$curroption) {
 2240:                             $curroption = 'norequest';
 2241:                         }
 2242:                         foreach my $option (@options) {
 2243:                             my $val = $option;
 2244:                             if ($option eq 'norequest') {
 2245:                                 $val = 0;
 2246:                             }
 2247:                             my $checked = '';
 2248:                             if ($option eq $curroption) {
 2249:                                 $checked = ' checked="checked"';
 2250:                             }
 2251:                             $datatable .= '<span class="LC_nobreak"><label>'.
 2252:                                   '<input type="radio" name="authorreq_'.$type.
 2253:                                   '" value="'.$val.'"'.$checked.' />'.
 2254:                                   $titles{$option}.'</label></span>&nbsp; ';
 2255:                         }
 2256:                     } else {
 2257:                         my $checked = 'checked="checked" ';
 2258:                         if (ref($settings) eq 'HASH') {
 2259:                             if (ref($settings->{$item}) eq 'HASH') {
 2260:                                 if ($settings->{$item}->{$type} == 0) {
 2261:                                     $checked = '';
 2262:                                 } elsif ($settings->{$item}->{$type} == 1) {
 2263:                                     $checked =  'checked="checked" ';
 2264:                                 }
 2265:                             }
 2266:                         }
 2267:                         $datatable .= '<span class="LC_nobreak"><label>'.
 2268:                                       '<input type="checkbox" name="'.$context.'_'.$item.
 2269:                                       '" value="'.$type.'" '.$checked.'/>'.$titles{$item}.
 2270:                                       '</label></span>&nbsp; ';
 2271:                     }
 2272:                 }
 2273:                 if ($context eq 'requestcourses') {
 2274:                     $datatable .= '</tr><tr>';
 2275:                     foreach my $item (@usertools) {
 2276:                         $datatable .= '<td style="vertical-align: top">'.$cell{$item}.'</td>';  
 2277:                     }
 2278:                     $datatable .= '</tr></table>';
 2279:                 }
 2280:                 $datatable .= '</td>';
 2281:                 unless (($context eq 'requestcourses') ||
 2282:                         ($context eq 'requestauthor')) {
 2283:                     $datatable .= 
 2284:                               '<td class="LC_right_item">'.
 2285:                               '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 2286:                               '<input type="text" name="quota_'.$type.
 2287:                               '" value="'.$currdefquota.
 2288:                               '" size="5" /></span>'.('&nbsp;' x 2).
 2289:                               '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 2290:                               '<input type="text" name="authorquota_'.$type.
 2291:                               '" value="'.$currauthorquota.
 2292:                               '" size="5" /></span></td>';
 2293:                 }
 2294:                 $datatable .= '</tr>';
 2295:             }
 2296:         }
 2297:     }
 2298:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 2299:         $defaultquota = '20';
 2300:         $authorquota = '500';
 2301:         if (ref($settings) eq 'HASH') {
 2302:             if (ref($settings->{'defaultquota'}) eq 'HASH') {
 2303:                 $defaultquota = $settings->{'defaultquota'}->{'default'};
 2304:             } elsif (defined($settings->{'default'})) {
 2305:                 $defaultquota = $settings->{'default'};
 2306:             }
 2307:             if (ref($settings->{'authorquota'}) eq 'HASH') {
 2308:                 $authorquota = $settings->{'authorquota'}->{'default'};
 2309:             }
 2310:         }
 2311:     }
 2312:     $typecount ++;
 2313:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 2314:     $datatable .= '<tr'.$css_class.'>'.
 2315:                   '<td>'.$othertitle.'</td>'.
 2316:                   '<td class="LC_left_item">';
 2317:     if ($context eq 'requestcourses') {
 2318:         $datatable .= '<table><tr>';
 2319:     }
 2320:     my %defcell;
 2321:     foreach my $item (@usertools) {
 2322:         if ($context eq 'requestcourses') {
 2323:             my ($curroption,$currlimit);
 2324:             if (ref($settings) eq 'HASH') {
 2325:                 if (ref($settings->{$item}) eq 'HASH') {
 2326:                     $curroption = $settings->{$item}->{'default'};
 2327:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 2328:                         $currlimit = $1;
 2329:                     }
 2330:                 }
 2331:             }
 2332:             if (!$curroption) {
 2333:                 $curroption = 'norequest';
 2334:             }
 2335:             $datatable .= '<th>'.$titles{$item}.'</th>';
 2336:             foreach my $option (@options) {
 2337:                 my $val = $option;
 2338:                 if ($option eq 'norequest') {
 2339:                     $val = 0;
 2340:                 }
 2341:                 if ($option eq 'validate') {
 2342:                     my $canvalidate = 0;
 2343:                     if (ref($validations{$item}) eq 'HASH') {
 2344:                         if ($validations{$item}{'default'}) {
 2345:                             $canvalidate = 1;
 2346:                         }
 2347:                     }
 2348:                     next if (!$canvalidate);
 2349:                 }
 2350:                 my $checked = '';
 2351:                 if ($option eq $curroption) {
 2352:                     $checked = ' checked="checked"';
 2353:                 } elsif ($option eq 'autolimit') {
 2354:                     if ($curroption =~ /^autolimit/) {
 2355:                         $checked = ' checked="checked"';
 2356:                     }
 2357:                 }
 2358:                 $defcell{$item} .= '<span class="LC_nobreak"><label>'.
 2359:                                   '<input type="radio" name="crsreq_'.$item.
 2360:                                   '_default" value="'.$val.'"'.$checked.' />'.
 2361:                                   $titles{$option}.'</label>';
 2362:                 if ($option eq 'autolimit') {
 2363:                     $defcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2364:                                        $item.'_limit_default" size="1" '.
 2365:                                        'value="'.$currlimit.'" />';
 2366:                 }
 2367:                 $defcell{$item} .= '</span> ';
 2368:                 if ($option eq 'autolimit') {
 2369:                     $defcell{$item} .= $titles{'unlimited'};
 2370:                 }
 2371:             }
 2372:         } elsif ($context eq 'requestauthor') {
 2373:             my $curroption;
 2374:             if (ref($settings) eq 'HASH') {
 2375:                 $curroption = $settings->{'default'};
 2376:             }
 2377:             if (!$curroption) {
 2378:                 $curroption = 'norequest';
 2379:             }
 2380:             foreach my $option (@options) {
 2381:                 my $val = $option;
 2382:                 if ($option eq 'norequest') {
 2383:                     $val = 0;
 2384:                 }
 2385:                 my $checked = '';
 2386:                 if ($option eq $curroption) {
 2387:                     $checked = ' checked="checked"';
 2388:                 }
 2389:                 $datatable .= '<span class="LC_nobreak"><label>'.
 2390:                               '<input type="radio" name="authorreq_default"'.
 2391:                               ' value="'.$val.'"'.$checked.' />'.
 2392:                               $titles{$option}.'</label></span>&nbsp; ';
 2393:             }
 2394:         } else {
 2395:             my $checked = 'checked="checked" ';
 2396:             if (ref($settings) eq 'HASH') {
 2397:                 if (ref($settings->{$item}) eq 'HASH') {
 2398:                     if ($settings->{$item}->{'default'} == 0) {
 2399:                         $checked = '';
 2400:                     } elsif ($settings->{$item}->{'default'} == 1) {
 2401:                         $checked = 'checked="checked" ';
 2402:                     }
 2403:                 }
 2404:             }
 2405:             $datatable .= '<span class="LC_nobreak"><label>'.
 2406:                           '<input type="checkbox" name="'.$context.'_'.$item.
 2407:                           '" value="default" '.$checked.'/>'.$titles{$item}.
 2408:                           '</label></span>&nbsp; ';
 2409:         }
 2410:     }
 2411:     if ($context eq 'requestcourses') {
 2412:         $datatable .= '</tr><tr>';
 2413:         foreach my $item (@usertools) {
 2414:             $datatable .= '<td style="vertical-align: top">'.$defcell{$item}.'</td>';
 2415:         }
 2416:         $datatable .= '</tr></table>';
 2417:     }
 2418:     $datatable .= '</td>';
 2419:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 2420:         $datatable .= '<td class="LC_right_item">'.
 2421:                       '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 2422:                       '<input type="text" name="defaultquota" value="'.
 2423:                       $defaultquota.'" size="5" /></span>'.('&nbsp;' x2).
 2424:                       '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 2425:                       '<input type="text" name="authorquota" value="'.
 2426:                       $authorquota.'" size="5" /></span></td>';
 2427:     }
 2428:     $datatable .= '</tr>';
 2429:     $typecount ++;
 2430:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 2431:     $datatable .= '<tr'.$css_class.'>'.
 2432:                   '<td>'.&mt('LON-CAPA Advanced Users').'<br />';
 2433:     if ($context eq 'requestcourses') {
 2434:         $datatable .= &mt('(overrides affiliation, if set)').
 2435:                       '</td>'.
 2436:                       '<td class="LC_left_item">'.
 2437:                       '<table><tr>';
 2438:     } else {
 2439:         $datatable .= &mt('(overrides affiliation, if checked)').
 2440:                       '</td>'.
 2441:                       '<td class="LC_left_item" colspan="2">'.
 2442:                       '<br />';
 2443:     }
 2444:     my %advcell;
 2445:     foreach my $item (@usertools) {
 2446:         if ($context eq 'requestcourses') {
 2447:             my ($curroption,$currlimit);
 2448:             if (ref($settings) eq 'HASH') {
 2449:                 if (ref($settings->{$item}) eq 'HASH') {
 2450:                     $curroption = $settings->{$item}->{'_LC_adv'};
 2451:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 2452:                         $currlimit = $1;
 2453:                     }
 2454:                 }
 2455:             }
 2456:             $datatable .= '<th>'.$titles{$item}.'</th>';
 2457:             my $checked = '';
 2458:             if ($curroption eq '') {
 2459:                 $checked = ' checked="checked"';
 2460:             }
 2461:             $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2462:                                '<input type="radio" name="crsreq_'.$item.
 2463:                                '__LC_adv" value=""'.$checked.' />'.
 2464:                                &mt('No override set').'</label></span>&nbsp; ';
 2465:             foreach my $option (@options) {
 2466:                 my $val = $option;
 2467:                 if ($option eq 'norequest') {
 2468:                     $val = 0;
 2469:                 }
 2470:                 if ($option eq 'validate') {
 2471:                     my $canvalidate = 0;
 2472:                     if (ref($validations{$item}) eq 'HASH') {
 2473:                         if ($validations{$item}{'_LC_adv'}) {
 2474:                             $canvalidate = 1;
 2475:                         }
 2476:                     }
 2477:                     next if (!$canvalidate);
 2478:                 }
 2479:                 my $checked = '';
 2480:                 if ($val eq $curroption) {
 2481:                     $checked = ' checked="checked"';
 2482:                 } elsif ($option eq 'autolimit') {
 2483:                     if ($curroption =~ /^autolimit/) {
 2484:                         $checked = ' checked="checked"';
 2485:                     }
 2486:                 }
 2487:                 $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2488:                                   '<input type="radio" name="crsreq_'.$item.
 2489:                                   '__LC_adv" value="'.$val.'"'.$checked.' />'.
 2490:                                   $titles{$option}.'</label>';
 2491:                 if ($option eq 'autolimit') {
 2492:                     $advcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2493:                                        $item.'_limit__LC_adv" size="1" '.
 2494:                                        'value="'.$currlimit.'" />';
 2495:                 }
 2496:                 $advcell{$item} .= '</span> ';
 2497:                 if ($option eq 'autolimit') {
 2498:                     $advcell{$item} .= $titles{'unlimited'};
 2499:                 }
 2500:             }
 2501:         } elsif ($context eq 'requestauthor') {
 2502:             my $curroption;
 2503:             if (ref($settings) eq 'HASH') {
 2504:                 $curroption = $settings->{'_LC_adv'};
 2505:             }
 2506:             my $checked = '';
 2507:             if ($curroption eq '') {
 2508:                 $checked = ' checked="checked"';
 2509:             }
 2510:             $datatable .= '<span class="LC_nobreak"><label>'.
 2511:                           '<input type="radio" name="authorreq__LC_adv"'.
 2512:                           ' value=""'.$checked.' />'.
 2513:                           &mt('No override set').'</label></span>&nbsp; ';
 2514:             foreach my $option (@options) {
 2515:                 my $val = $option;
 2516:                 if ($option eq 'norequest') {
 2517:                     $val = 0;
 2518:                 }
 2519:                 my $checked = '';
 2520:                 if ($val eq $curroption) {
 2521:                     $checked = ' checked="checked"';
 2522:                 }
 2523:                 $datatable .= '<span class="LC_nobreak"><label>'.
 2524:                               '<input type="radio" name="authorreq__LC_adv"'.
 2525:                               ' value="'.$val.'"'.$checked.' />'.
 2526:                               $titles{$option}.'</label></span>&nbsp; ';
 2527:             }
 2528:         } else {
 2529:             my $checked = 'checked="checked" ';
 2530:             if (ref($settings) eq 'HASH') {
 2531:                 if (ref($settings->{$item}) eq 'HASH') {
 2532:                     if ($settings->{$item}->{'_LC_adv'} == 0) {
 2533:                         $checked = '';
 2534:                     } elsif ($settings->{$item}->{'_LC_adv'} == 1) {
 2535:                         $checked = 'checked="checked" ';
 2536:                     }
 2537:                 }
 2538:             }
 2539:             $datatable .= '<span class="LC_nobreak"><label>'.
 2540:                           '<input type="checkbox" name="'.$context.'_'.$item.
 2541:                           '" value="_LC_adv" '.$checked.'/>'.$titles{$item}.
 2542:                           '</label></span>&nbsp; ';
 2543:         }
 2544:     }
 2545:     if ($context eq 'requestcourses') {
 2546:         $datatable .= '</tr><tr>';
 2547:         foreach my $item (@usertools) {
 2548:             $datatable .= '<td style="vertical-align: top">'.$advcell{$item}.'</td>';
 2549:         }
 2550:         $datatable .= '</tr></table>';
 2551:     }
 2552:     $datatable .= '</td></tr>';
 2553:     $$rowtotal += $typecount;
 2554:     return $datatable;
 2555: }
 2556: 
 2557: sub print_requestmail {
 2558:     my ($dom,$action,$settings,$rowtotal,$customcss,$rowstyle) = @_;
 2559:     my ($now,$datatable,%currapp);
 2560:     $now = time;
 2561:     if (ref($settings) eq 'HASH') {
 2562:         if (ref($settings->{'notify'}) eq 'HASH') {
 2563:             if ($settings->{'notify'}{'approval'} ne '') {
 2564:                 map {$currapp{$_}=1;} split(/,/,$settings->{'notify'}{'approval'});
 2565:             }
 2566:         }
 2567:     }
 2568:     my $numinrow = 2;
 2569:     my $css_class;
 2570:     if ($$rowtotal%2) {
 2571:         $css_class = 'LC_odd_row';
 2572:     }
 2573:     if ($customcss) {
 2574:         $css_class .= " $customcss";
 2575:     }
 2576:     $css_class =~ s/^\s+//;
 2577:     if ($css_class) {
 2578:         $css_class = ' class="'.$css_class.'"';
 2579:     }
 2580:     if ($rowstyle) {
 2581:         $css_class .= ' style="'.$rowstyle.'"';
 2582:     }
 2583:     my $text;
 2584:     if ($action eq 'requestcourses') {
 2585:         $text = &mt('Receive notification of course requests requiring approval');
 2586:     } elsif ($action eq 'requestauthor') {
 2587:         $text = &mt('Receive notification of Authoring Space requests requiring approval');
 2588:     } else {
 2589:        $text = &mt('Receive notification of queued requests for self-created user accounts requiring approval');
 2590:     }
 2591:     $datatable = '<tr'.$css_class.'>'.
 2592:                  ' <td>'.$text.'</td>'.
 2593:                  ' <td class="LC_left_item">';
 2594:     my ($numdc,$table,$rows) = &active_dc_picker($dom,$numinrow,'checkbox',
 2595:                                                  $action.'notifyapproval',%currapp);
 2596:     if ($numdc > 0) {
 2597:         $datatable .= $table;
 2598:     } else {
 2599:         $datatable .= &mt('There are no active Domain Coordinators');
 2600:     }
 2601:     $datatable .='</td></tr>';
 2602:     return $datatable;
 2603: }
 2604: 
 2605: sub print_studentcode {
 2606:     my ($settings,$rowtotal) = @_;
 2607:     my $rownum = 0; 
 2608:     my ($output,%current);
 2609:     my @crstypes = ('official','unofficial','community','textbook');
 2610:     if (ref($settings) eq 'HASH') {
 2611:         if (ref($settings->{'uniquecode'}) eq 'HASH') {
 2612:             foreach my $type (@crstypes) {
 2613:                 $current{$type} = $settings->{'uniquecode'}{$type};
 2614:             }
 2615:         }
 2616:     }
 2617:     $output .= '<tr>'.
 2618:                '<td class="LC_left_item">'.&mt('Generate unique six character code as course identifier?').'</td>'.
 2619:                '<td class="LC_left_item">';
 2620:     foreach my $type (@crstypes) {
 2621:         my $check = ' ';
 2622:         if ($current{$type}) {
 2623:             $check = ' checked="checked" ';
 2624:         }
 2625:         $output .= '<span class="LC_nobreak"><label>'.
 2626:                    '<input type="checkbox" name="uniquecode" value="'.$type.'"'.$check.'/>'.
 2627:                    &mt($type).'</label></span>'.('&nbsp;'x2).' ';
 2628:     }
 2629:     $output .= '</td></tr>';
 2630:     $$rowtotal ++;
 2631:     return $output;
 2632: }
 2633: 
 2634: sub print_textbookcourses {
 2635:     my ($dom,$type,$settings,$rowtotal) = @_;
 2636:     my $rownum = 0;
 2637:     my $css_class;
 2638:     my $itemcount = 1;
 2639:     my $maxnum = 0;
 2640:     my $bookshash;
 2641:     if (ref($settings) eq 'HASH') {
 2642:         $bookshash = $settings->{$type};
 2643:     }
 2644:     my %ordered;
 2645:     if (ref($bookshash) eq 'HASH') {
 2646:         foreach my $item (keys(%{$bookshash})) {
 2647:             if (ref($bookshash->{$item}) eq 'HASH') {
 2648:                 my $num = $bookshash->{$item}{'order'};
 2649:                 $ordered{$num} = $item;
 2650:             }
 2651:         }
 2652:     }
 2653:     my $confname = $dom.'-domainconfig';
 2654:     my $switchserver = &check_switchserver($dom,$confname);
 2655:     my $maxnum = scalar(keys(%ordered));
 2656:     my $datatable;
 2657:     if (keys(%ordered)) {
 2658:         my @items = sort { $a <=> $b } keys(%ordered);
 2659:         for (my $i=0; $i<@items; $i++) {
 2660:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2661:             my $key = $ordered{$items[$i]};
 2662:             my %coursehash=&Apache::lonnet::coursedescription($key);
 2663:             my $coursetitle = $coursehash{'description'};
 2664:             my ($subject,$title,$author,$publisher,$image,$imgsrc,$cdom,$cnum);
 2665:             if (ref($bookshash->{$key}) eq 'HASH') {
 2666:                 $subject = $bookshash->{$key}->{'subject'};
 2667:                 $title = $bookshash->{$key}->{'title'};
 2668:                 if ($type eq 'textbooks') {
 2669:                     $publisher = $bookshash->{$key}->{'publisher'};
 2670:                     $author = $bookshash->{$key}->{'author'};
 2671:                     $image = $bookshash->{$key}->{'image'};
 2672:                     if ($image ne '') {
 2673:                         my ($path,$imagefile) = ($image =~ m{^(.+)/([^/]+)$});
 2674:                         my $imagethumb = "$path/tn-".$imagefile;
 2675:                         $imgsrc = '<img src="'.$imagethumb.'" alt="'.&mt('Textbook image').'" />';
 2676:                     }
 2677:                 }
 2678:             }
 2679:             my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type".'_'."$key','$type'".');"';
 2680:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 2681:                          .'<select name="'.$type.'_'.$key.'"'.$chgstr.'>';
 2682:             for (my $k=0; $k<=$maxnum; $k++) {
 2683:                 my $vpos = $k+1;
 2684:                 my $selstr;
 2685:                 if ($k == $i) {
 2686:                     $selstr = ' selected="selected" ';
 2687:                 }
 2688:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2689:             }
 2690:             $datatable .= '</select>'.('&nbsp;'x2).
 2691:                 '<label><input type="checkbox" name="'.$type.'_del" value="'.$key.'" />'.
 2692:                 &mt('Delete?').'</label></span></td>'.
 2693:                 '<td colspan="2">'.
 2694:                 '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_subject_'.$i.'" value="'.$subject.'" /></span> '.
 2695:                 ('&nbsp;'x2).
 2696:                 '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_title_'.$i.'" value="'.$title.'" /></span> ';
 2697:             if ($type eq 'textbooks') {
 2698:                 $datatable .= ('&nbsp;'x2).
 2699:                               '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_publisher_'.$i.'" value="'.$publisher.'" /></span> '.
 2700:                               ('&nbsp;'x2).
 2701:                               '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_author_'.$i.'" value="'.$author.'" /></span> '.
 2702:                               ('&nbsp;'x2).
 2703:                               '<span class="LC_nobreak">'.&mt('Thumbnail:');
 2704:                 if ($image) {
 2705:                     $datatable .= $imgsrc.
 2706:                                   '<label><input type="checkbox" name="'.$type.'_image_del"'.
 2707:                                   ' value="'.$key.'" />'.&mt('Delete?').'</label></span> '.
 2708:                                   '<span class="LC_nobreak">&nbsp;'.&mt('Replace:').'&nbsp;';
 2709:                 }
 2710:                 if ($switchserver) {
 2711:                     $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2712:                 } else {
 2713:                     $datatable .= '<input type="file" name="'.$type.'_image_'.$i.'" value="" />';
 2714:                 }
 2715:             }
 2716:             $datatable .= '<input type="hidden" name="'.$type.'_id_'.$i.'" value="'.$type.'_'.$key.'" /></span> '.
 2717:                           '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 2718:                           $coursetitle.'</span></td></tr>'."\n";
 2719:             $itemcount ++;
 2720:         }
 2721:     }
 2722:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2723:     my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type"."_addbook_pos','$type'".');"';
 2724:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 2725:                   '<input type="hidden" name="'.$type.'_maxnum" value="'.$maxnum.'" />'."\n".
 2726:                   '<select name="'.$type.'_addbook_pos"'.$chgstr.'>';
 2727:     for (my $k=0; $k<$maxnum+1; $k++) {
 2728:         my $vpos = $k+1;
 2729:         my $selstr;
 2730:         if ($k == $maxnum) {
 2731:             $selstr = ' selected="selected" ';
 2732:         }
 2733:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2734:     }
 2735:     $datatable .= '</select>&nbsp;'."\n".
 2736:                   '<input type="checkbox" name="'.$type.'_addbook" value="1" />'.&mt('Add').'</span></td>'."\n".
 2737:                   '<td colspan="2">'.
 2738:                   '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_addbook_subject" value="" /></span> '."\n".
 2739:                   ('&nbsp;'x2).
 2740:                   '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_addbook_title" value="" /></span> '."\n".
 2741:                   ('&nbsp;'x2);
 2742:     if ($type eq 'textbooks') {
 2743:         $datatable .= '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_addbook_publisher" value="" /></span> '."\n".
 2744:                       ('&nbsp;'x2).
 2745:                       '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_addbook_author" value="" /></span> '."\n".
 2746:                       ('&nbsp;'x2).
 2747:                       '<span class="LC_nobreak">'.&mt('Image:').'&nbsp;';
 2748:         if ($switchserver) {
 2749:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2750:         } else {
 2751:             $datatable .= '<input type="file" name="'.$type.'_addbook_image" value="" />';
 2752:         }
 2753:         $datatable .= '</span>'."\n";
 2754:     }
 2755:     $datatable .= '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 2756:                   &Apache::loncommon::select_dom_form($env{'request.role.domain'},$type.'_addbook_cdom').
 2757:                   '<input type="text" size="25" name="'.$type.'_addbook_cnum" value="" />'.
 2758:                   &Apache::loncommon::selectcourse_link
 2759:                       ('display',$type.'_addbook_cnum',$type.'_addbook_cdom',undef,undef,undef,'Course').
 2760:                   '</span></td>'."\n".
 2761:                   '</tr>'."\n";
 2762:     $itemcount ++;
 2763:     return $datatable;
 2764: }
 2765: 
 2766: sub textbookcourses_javascript {
 2767:     my ($settings) = @_;
 2768:     return unless(ref($settings) eq 'HASH');
 2769:     my (%ordered,%total,%jstext);
 2770:     foreach my $type ('textbooks','templates') {
 2771:         $total{$type} = 0;
 2772:         if (ref($settings->{$type}) eq 'HASH') {
 2773:             foreach my $item (keys(%{$settings->{$type}})) {
 2774:                 if (ref($settings->{$type}->{$item}) eq 'HASH') {
 2775:                     my $num = $settings->{$type}->{$item}{'order'};
 2776:                     $ordered{$type}{$num} = $item;
 2777:                 }
 2778:             }
 2779:             $total{$type} = scalar(keys(%{$settings->{$type}}));
 2780:         }
 2781:         my @jsarray = ();
 2782:         foreach my $item (sort {$a <=> $b } (keys(%{$ordered{$type}}))) {
 2783:             push(@jsarray,$ordered{$type}{$item});
 2784:         }
 2785:         $jstext{$type} = '    var '.$type.' = Array('."'".join("','",@jsarray)."'".');'."\n";
 2786:     }
 2787:     return <<"ENDSCRIPT";
 2788: <script type="text/javascript">
 2789: // <![CDATA[
 2790: function reorderBooks(form,item,caller) {
 2791:     var changedVal;
 2792: $jstext{'textbooks'};
 2793: $jstext{'templates'};
 2794:     var newpos;
 2795:     var maxh;
 2796:     if (caller == 'textbooks') {  
 2797:         newpos = 'textbooks_addbook_pos';
 2798:         maxh = 1 + $total{'textbooks'};
 2799:     } else {
 2800:         newpos = 'templates_addbook_pos';
 2801:         maxh = 1 + $total{'templates'};
 2802:     }
 2803:     var current = new Array;
 2804:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 2805:     if (item == newpos) {
 2806:         changedVal = newitemVal;
 2807:     } else {
 2808:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 2809:         current[newitemVal] = newpos;
 2810:     }
 2811:     if (caller == 'textbooks') {
 2812:         for (var i=0; i<textbooks.length; i++) {
 2813:             var elementName = 'textbooks_'+textbooks[i];
 2814:             if (elementName != item) {
 2815:                 if (form.elements[elementName]) {
 2816:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 2817:                     current[currVal] = elementName;
 2818:                 }
 2819:             }
 2820:         }
 2821:     }
 2822:     if (caller == 'templates') {
 2823:         for (var i=0; i<templates.length; i++) {
 2824:             var elementName = 'templates_'+templates[i];
 2825:             if (elementName != item) {
 2826:                 if (form.elements[elementName]) {
 2827:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 2828:                     current[currVal] = elementName;
 2829:                 }
 2830:             }
 2831:         }
 2832:     }
 2833:     var oldVal;
 2834:     for (var j=0; j<maxh; j++) {
 2835:         if (current[j] == undefined) {
 2836:             oldVal = j;
 2837:         }
 2838:     }
 2839:     if (oldVal < changedVal) {
 2840:         for (var k=oldVal+1; k<=changedVal ; k++) {
 2841:            var elementName = current[k];
 2842:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 2843:         }
 2844:     } else {
 2845:         for (var k=changedVal; k<oldVal; k++) {
 2846:             var elementName = current[k];
 2847:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 2848:         }
 2849:     }
 2850:     return;
 2851: }
 2852: 
 2853: // ]]>
 2854: </script>
 2855: 
 2856: ENDSCRIPT
 2857: }
 2858: 
 2859: sub wafproxy_javascript {
 2860:     my ($dom) = @_;
 2861:     return <<"ENDSCRIPT";
 2862: <script type="text/javascript">
 2863: // <![CDATA[
 2864: function updateWAF() {
 2865:     if (document.getElementById('wafproxy_remoteip')) {
 2866:         var wafremote = 0;
 2867:         if (document.display.wafproxy_remoteip.options[document.display.wafproxy_remoteip.selectedIndex].value == 'h') {
 2868:             wafremote = 1;
 2869:         }
 2870:         var fields = new Array('header','trust');
 2871:         for (var i=0; i<fields.length; i++) {
 2872:             if (document.getElementById('wafproxy_'+fields[i])) {
 2873:                 if (wafremote == 1) {
 2874:                     document.getElementById('wafproxy_'+fields[i]).style.display = 'table-row';
 2875:                 }
 2876:                 else {
 2877:                     document.getElementById('wafproxy_'+fields[i]).style.display = 'none';
 2878:                 }
 2879:             }
 2880:         }
 2881:         if (document.getElementById('wafproxyranges_$dom')) {
 2882:             if (wafremote == 1) {
 2883:                 document.getElementById('wafproxyranges_$dom').style.display = 'inline-block';
 2884:             } else {
 2885:                 for (var i=0; i<document.display.wafproxy_vpnaccess.length; i++) {
 2886:                     if (document.display.wafproxy_vpnaccess[i].checked) {
 2887:                         if (document.display.wafproxy_vpnaccess[i].value == 0) {
 2888:                             document.getElementById('wafproxyranges_$dom').style.display = 'none';
 2889:                         }
 2890:                     }
 2891:                 }
 2892:             }
 2893:         }
 2894:     }
 2895:     return;
 2896: }
 2897: 
 2898: function checkWAF() {
 2899:     if (document.getElementById('wafproxy_remoteip')) {
 2900:         var wafvpn = 0;
 2901:         for (var i=0; i<document.display.wafproxy_vpnaccess.length; i++) {
 2902:             if (document.display.wafproxy_vpnaccess[i].checked) {
 2903:                 if (document.display.wafproxy_vpnaccess[i].value == 1) {
 2904:                     wafvpn = 1;
 2905:                 }
 2906:                 break;
 2907:             }
 2908:         }
 2909:         var vpn = new Array('vpnint','vpnext');
 2910:         for (var i=0; i<vpn.length; i++) {
 2911:             if (document.getElementById('wafproxy_show_'+vpn[i])) {
 2912:                 if (wafvpn == 1) {
 2913:                     document.getElementById('wafproxy_show_'+vpn[i]).style.display = 'table-row';
 2914:                 }
 2915:                 else {
 2916:                     document.getElementById('wafproxy_show_'+vpn[i]).style.display = 'none';
 2917:                 }
 2918:             }
 2919:         }
 2920:         if (document.getElementById('wafproxyranges_$dom')) {
 2921:             if (wafvpn == 1) {
 2922:                 document.getElementById('wafproxyranges_$dom').style.display = 'inline-block';
 2923:             }
 2924:             else if (document.display.wafproxy_remoteip.options[document.display.wafproxy_remoteip.selectedIndex].value != 'h') {
 2925:                 document.getElementById('wafproxyranges_$dom').style.display = 'none';
 2926:             }
 2927:         }
 2928:     }
 2929:     return;
 2930: }
 2931: 
 2932: function toggleWAF() {
 2933:     if (document.getElementById('wafproxy_table')) {
 2934:         var wafproxy = 0;
 2935:         for (var i=0; i<document.display.wafproxy_${dom}.length; i++) {
 2936:              if (document.display.wafproxy_${dom}[i].checked) {
 2937:                  if (document.display.wafproxy_${dom}[i].value == 1) {
 2938:                      wafproxy = 1;
 2939:                      break;
 2940:                 }
 2941:             }
 2942:         }
 2943:         if (wafproxy == 1) {
 2944:             document.getElementById('wafproxy_table').style.display='inline';
 2945:         }
 2946:         else {
 2947:            document.getElementById('wafproxy_table').style.display='none';
 2948:         }
 2949:         if (document.getElementById('wafproxyrow_${dom}')) {
 2950:             if (wafproxy == 1) {
 2951:                 document.getElementById('wafproxyrow_${dom}').style.display = 'table-row';
 2952:             }
 2953:             else {
 2954:                 document.getElementById('wafproxyrow_${dom}').style.display = 'none';
 2955:             }
 2956:         }
 2957:         if (document.getElementById('nowafproxyrow_$dom')) {
 2958:             if (wafproxy == 1) {
 2959:                 document.getElementById('nowafproxyrow_${dom}').style.display = 'none';
 2960:             }
 2961:             else {
 2962:                 document.getElementById('nowafproxyrow_${dom}').style.display = 'table-row';
 2963:             }
 2964:         }
 2965:     }
 2966:     return;
 2967: }
 2968: // ]]>
 2969: </script>
 2970: 
 2971: ENDSCRIPT
 2972: }
 2973: 
 2974: sub autoupdate_javascript {
 2975:     return <<"ENDSCRIPT";
 2976: <script type="text/javascript">
 2977: // <![CDATA[
 2978: function toggleLastActiveDays(form) {
 2979:     var radioname = 'lastactive';
 2980:     var divid = 'lastactive_div';
 2981:     var num = form.elements[radioname].length;
 2982:     if (num) {
 2983:         var setvis = '';
 2984:         for (var i=0; i<num; i++) {
 2985:             if (form.elements[radioname][i].checked) {
 2986:                 if (form.elements[radioname][i].value == '1') {
 2987:                     if (document.getElementById(divid)) {
 2988:                         document.getElementById(divid).style.display = 'inline-block';
 2989:                     }
 2990:                     setvis = 1;
 2991:                 }
 2992:                 break;
 2993:             }
 2994:         }
 2995:         if (!setvis) {
 2996:             if (document.getElementById(divid)) {
 2997:                 document.getElementById(divid).style.display = 'none';
 2998:             }
 2999:         }
 3000:     }
 3001:     return;
 3002: }
 3003: // ]]>
 3004: </script>
 3005: 
 3006: ENDSCRIPT
 3007: }
 3008: 
 3009: sub autoenroll_javascript {
 3010:     return <<"ENDSCRIPT";
 3011: <script type="text/javascript">
 3012: // <![CDATA[
 3013: function toggleFailsafe(form) {
 3014:     var radioname = 'autoenroll_failsafe';
 3015:     var divid = 'autoenroll_failsafe_div';
 3016:     var num = form.elements[radioname].length;
 3017:     if (num) {
 3018:         var setvis = '';
 3019:         for (var i=0; i<num; i++) {
 3020:             if (form.elements[radioname][i].checked) {
 3021:                 if ((form.elements[radioname][i].value == 'zero') || (form.elements[radioname][i].value == 'any')) {
 3022:                     if (document.getElementById(divid)) {
 3023:                         document.getElementById(divid).style.display = 'inline-block';
 3024:                     }
 3025:                     setvis = 1;
 3026:                 }
 3027:                 break;
 3028:             }
 3029:         }
 3030:         if (!setvis) {
 3031:             if (document.getElementById(divid)) {
 3032:                 document.getElementById(divid).style.display = 'none';
 3033:             }
 3034:         }
 3035:     }
 3036:     return;
 3037: }
 3038: // ]]>
 3039: </script>
 3040: 
 3041: ENDSCRIPT
 3042: }
 3043: 
 3044: sub saml_javascript {
 3045:     return <<"ENDSCRIPT";
 3046: <script type="text/javascript">
 3047: // <![CDATA[
 3048: function toggleSamlOptions(form,hostid) {
 3049:     var radioname = 'saml_'+hostid;
 3050:     var tablecellon = 'samloptionson_'+hostid;
 3051:     var tablecelloff = 'samloptionsoff_'+hostid;
 3052:     var num = form.elements[radioname].length;
 3053:     if (num) {
 3054:         var setvis = '';
 3055:         for (var i=0; i<num; i++) {
 3056:             if (form.elements[radioname][i].checked) {
 3057:                 if (form.elements[radioname][i].value == '1') {
 3058:                     if (document.getElementById(tablecellon)) {
 3059:                         document.getElementById(tablecellon).style.display='';
 3060:                     }
 3061:                     if (document.getElementById(tablecelloff)) {
 3062:                         document.getElementById(tablecelloff).style.display='none';
 3063:                     }
 3064:                     setvis = 1;
 3065:                 }
 3066:                 break;
 3067:             }
 3068:         }
 3069:         if (!setvis) {
 3070:             if (document.getElementById(tablecellon)) {
 3071:                 document.getElementById(tablecellon).style.display='none';
 3072:             }
 3073:             if (document.getElementById(tablecelloff)) {
 3074:                 document.getElementById(tablecelloff).style.display='';
 3075:             }
 3076:         }
 3077:     }
 3078:     return;
 3079: }
 3080: // ]]>
 3081: </script>
 3082: 
 3083: ENDSCRIPT
 3084: }
 3085: 
 3086: sub ipaccess_javascript {
 3087:     my ($settings) = @_;
 3088:     my (%ordered,$total,%jstext);
 3089:     $total = 0;
 3090:     if (ref($settings) eq 'HASH') {
 3091:         foreach my $item (keys(%{$settings})) {
 3092:             if (ref($settings->{$item}) eq 'HASH') {
 3093:                 my $num = $settings->{$item}{'order'};
 3094:                 $ordered{$num} = $item;
 3095:             }
 3096:         }
 3097:         $total = scalar(keys(%{$settings}));
 3098:     }
 3099:     my @jsarray = ();
 3100:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3101:         push(@jsarray,$ordered{$item});
 3102:     }
 3103:     my $jstext = '    var ipaccess = Array('."'".join("','",@jsarray)."'".');'."\n";
 3104:     return <<"ENDSCRIPT";
 3105: <script type="text/javascript">
 3106: // <![CDATA[
 3107: function reorderIPaccess(form,item) {
 3108:     var changedVal;
 3109: $jstext
 3110:     var newpos = 'ipaccess_pos_add';
 3111:     var maxh = 1 + $total;
 3112:     var current = new Array;
 3113:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 3114:     if (item == newpos) {
 3115:         changedVal = newitemVal;
 3116:     } else {
 3117:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3118:         current[newitemVal] = newpos;
 3119:     }
 3120:     for (var i=0; i<ipaccess.length; i++) {
 3121:         var elementName = 'ipaccess_pos_'+ipaccess[i];
 3122:         if (elementName != item) {
 3123:             if (form.elements[elementName]) {
 3124:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3125:                 current[currVal] = elementName;
 3126:             }
 3127:         }
 3128:     }
 3129:     var oldVal;
 3130:     for (var j=0; j<maxh; j++) {
 3131:         if (current[j] == undefined) {
 3132:             oldVal = j;
 3133:         }
 3134:     }
 3135:     if (oldVal < changedVal) {
 3136:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3137:            var elementName = current[k];
 3138:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3139:         }
 3140:     } else {
 3141:         for (var k=changedVal; k<oldVal; k++) {
 3142:             var elementName = current[k];
 3143:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3144:         }
 3145:     }
 3146:     return;
 3147: }
 3148: // ]]>
 3149: </script>
 3150: 
 3151: ENDSCRIPT
 3152: }
 3153: 
 3154: sub print_autoenroll {
 3155:     my ($dom,$settings,$rowtotal) = @_;
 3156:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
 3157:     my ($defdom,$runon,$runoff,$coownerson,$coownersoff,
 3158:         $failsafe,$autofailsafe,$failsafesty,%failsafechecked);
 3159:     $failsafesty = 'none';
 3160:     %failsafechecked = (
 3161:         off => ' checked="checked"',
 3162:     );
 3163:     if (ref($settings) eq 'HASH') {
 3164:         if (exists($settings->{'run'})) {
 3165:             if ($settings->{'run'} eq '0') {
 3166:                 $runoff = ' checked="checked" ';
 3167:                 $runon = ' ';
 3168:             } else {
 3169:                 $runon = ' checked="checked" ';
 3170:                 $runoff = ' ';
 3171:             }
 3172:         } else {
 3173:             if ($autorun) {
 3174:                 $runon = ' checked="checked" ';
 3175:                 $runoff = ' ';
 3176:             } else {
 3177:                 $runoff = ' checked="checked" ';
 3178:                 $runon = ' ';
 3179:             }
 3180:         }
 3181:         if (exists($settings->{'co-owners'})) {
 3182:             if ($settings->{'co-owners'} eq '0') {
 3183:                 $coownersoff = ' checked="checked" ';
 3184:                 $coownerson = ' ';
 3185:             } else {
 3186:                 $coownerson = ' checked="checked" ';
 3187:                 $coownersoff = ' ';
 3188:             }
 3189:         } else {
 3190:             $coownersoff = ' checked="checked" ';
 3191:             $coownerson = ' ';
 3192:         }
 3193:         if (exists($settings->{'sender_domain'})) {
 3194:             $defdom = $settings->{'sender_domain'};
 3195:         }
 3196:         if (exists($settings->{'failsafe'})) {
 3197:             $failsafe = $settings->{'failsafe'};
 3198:             if ($failsafe eq 'zero') {
 3199:                 $failsafechecked{'zero'} = ' checked="checked"';
 3200:                 $failsafechecked{'off'} = '';
 3201:                 $failsafesty = 'inline-block';
 3202:             } elsif ($failsafe eq 'any') {
 3203:                 $failsafechecked{'any'} = ' checked="checked"';
 3204:                 $failsafechecked{'off'} = '';
 3205:             }
 3206:             $autofailsafe = $settings->{'autofailsafe'};
 3207:         } elsif (exists($settings->{'autofailsafe'})) {
 3208:             $autofailsafe = $settings->{'autofailsafe'};
 3209:             if ($autofailsafe ne '') {
 3210:                 $failsafechecked{'zero'} = ' checked="checked"';
 3211:                 $failsafe = 'zero';
 3212:                 $failsafechecked{'off'} = '';
 3213:             }
 3214:         }
 3215:     } else {
 3216:         if ($autorun) {
 3217:             $runon = ' checked="checked" ';
 3218:             $runoff = ' ';
 3219:         } else {
 3220:             $runoff = ' checked="checked" ';
 3221:             $runon = ' ';
 3222:         }
 3223:     }
 3224:     my $domform = &Apache::loncommon::select_dom_form($defdom,'sender_domain',1);
 3225:     my $notif_sender;
 3226:     if (ref($settings) eq 'HASH') {
 3227:         $notif_sender = $settings->{'sender_uname'};
 3228:     }
 3229:     my $datatable='<tr class="LC_odd_row">'.
 3230:                   '<td>'.&mt('Auto-enrollment active?').'</td>'.
 3231:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3232:                   '<input type="radio" name="autoenroll_run"'.
 3233:                   $runon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3234:                   '<label><input type="radio" name="autoenroll_run"'.
 3235:                   $runoff.' value="0" />'.&mt('No').'</label></span></td>'.
 3236:                   '</tr><tr>'.
 3237:                   '<td>'.&mt('Notification messages - sender').
 3238:                   '</td><td class="LC_right_item"><span class="LC_nobreak">'.
 3239:                   &mt('username').':&nbsp;'.
 3240:                   '<input type="text" name="sender_uname" value="'.
 3241:                   $notif_sender.'" size="10" />&nbsp;&nbsp;'.&mt('domain').
 3242:                   ':&nbsp;'.$domform.'</span></td></tr>'.
 3243:                   '<tr class="LC_odd_row">'.
 3244:                   '<td>'.&mt('Automatically assign co-ownership').'</td>'.
 3245:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3246:                   '<input type="radio" name="autoassign_coowners"'.
 3247:                   $coownerson.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3248:                   '<label><input type="radio" name="autoassign_coowners"'.
 3249:                   $coownersoff.' value="0" />'.&mt('No').'</label></span></td>'.
 3250:                   '</tr><tr>'.
 3251:                   '<td>'.&mt('Failsafe for no drops when institutional data missing').'</td>'.
 3252:                   '<td class="LC_left_item"><span class="LC_nobreak">'.
 3253:                   '<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; '.
 3254:                   '<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 />'.
 3255:                   '<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>'.
 3256:                   '<div class="LC_floatleft" style="display:'.$failsafesty.';" id="autoenroll_failsafe_div">'.
 3257:                   '<span class="LC_nobreak">'.
 3258:                   &mt('Threshold for number of students in section to drop: [_1]',
 3259:                       '<input type="text" name="autoenroll_autofailsafe" value="'.$autofailsafe.'" size="4" />').
 3260:                   '</span></div></td></tr>';
 3261:     $$rowtotal += 4;
 3262:     return $datatable;
 3263: }
 3264: 
 3265: sub print_autoupdate {
 3266:     my ($position,$dom,$settings,$rowtotal) = @_;
 3267:     my ($enable,$datatable);
 3268:     if ($position eq 'top') {
 3269:         my %choices = &Apache::lonlocal::texthash (
 3270:                           run        => 'Auto-update active?',
 3271:                           classlists => 'Update information in classlists?',
 3272:                           unexpired  => 'Skip updates for users without active or future roles?',
 3273:                           lastactive => 'Skip updates for inactive users?',
 3274:         );
 3275:         my $itemcount = 0;
 3276:         my $updateon = ' ';
 3277:         my $updateoff = ' checked="checked" ';
 3278:         if (ref($settings) eq 'HASH') {
 3279:             if ($settings->{'run'} eq '1') {
 3280:                 $updateon = $updateoff;
 3281:                 $updateoff = ' ';
 3282:             }
 3283:         }
 3284:         $enable = '<tr class="LC_odd_row">'. 
 3285:                   '<td>'.&mt($choices{'run'}).'</td>'.
 3286:                   '<td class="LC_left_item"><span class="LC_nobreak"><label>'.
 3287:                   '<input type="radio" name="autoupdate_run"'.
 3288:                   $updateoff.'value="0" />'.&mt('No').'</label>&nbsp;'.
 3289:                   '<label><input type="radio" name="autoupdate_run"'.
 3290:                   $updateon.'value="1" />'.&mt('Yes').'</label></span></td>'.
 3291:                   '</tr>';
 3292:         my @toggles = ('classlists','unexpired');
 3293:         my %defaultchecked = ('classlists' => 'off',
 3294:                               'unexpired'  => 'off'
 3295:                               );
 3296:         $$rowtotal ++;
 3297:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 3298:                                                      \%choices,$itemcount,'','','left','no');
 3299:         $datatable = $enable.$datatable;
 3300:         $$rowtotal += $itemcount;
 3301:         my $lastactiveon = ' ';
 3302:         my $lastactiveoff = ' checked="checked" ';
 3303:         my $lastactivestyle = 'none';
 3304:         my $lastactivedays;
 3305:         my $onclick = ' onclick="javascript:toggleLastActiveDays(this.form);"';
 3306:         if (ref($settings) eq 'HASH') {
 3307:             if ($settings->{'lastactive'} =~ /^\d+$/) {
 3308:                 $lastactiveon = $lastactiveoff;
 3309:                 $lastactiveoff = ' ';
 3310:                 $lastactivestyle = 'inline-block';
 3311:                 $lastactivedays = $settings->{'lastactive'};
 3312:             }
 3313:         }
 3314:         my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 3315:         $datatable .= '<tr'.$css_class.'>'.
 3316:                       '<td>'.$choices{'lastactive'}.'</td>'.
 3317:                       '<td class="LC_left_item"><span class="LC_nobreak"><label>'.
 3318:                       '<input type="radio" name="lastactive"'.
 3319:                       $lastactiveoff.'value="0"'.$onclick.' />'.&mt('No').'</label>'.
 3320:                       '&nbsp;<label>'.
 3321:                       '<input type="radio" name="lastactive"'.
 3322:                       $lastactiveon.' value="1"'.$onclick.' />'.&mt('Yes').'</label>'.
 3323:                       '<div id="lastactive_div" style="display:'.$lastactivestyle.';">'.
 3324:                       ':&nbsp;'.&mt('inactive = no activity in last [_1] days',
 3325:                           '<input type="text" size="5" name="lastactivedays" value="'.
 3326:                           $lastactivedays.'" />').
 3327:                       '</span></td>'.
 3328:                       '</tr>';
 3329:         $$rowtotal ++;
 3330:     } elsif ($position eq 'middle') {
 3331:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3332:         my $numinrow = 3;
 3333:         my $locknamesettings;
 3334:         $datatable .= &insttypes_row($settings,$types,$usertypes,
 3335:                                      $dom,$numinrow,$othertitle,
 3336:                                     'lockablenames',$rowtotal);
 3337:         $$rowtotal ++;
 3338:     } else {
 3339:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3340:         my @fields = ('lastname','firstname','middlename','generation',
 3341:                       'permanentemail','id');
 3342:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3343:         my $numrows = 0;
 3344:         if (ref($types) eq 'ARRAY') {
 3345:             if (@{$types} > 0) {
 3346:                 $datatable = 
 3347:                     &usertype_update_row($settings,$usertypes,\%fieldtitles,
 3348:                                          \@fields,$types,\$numrows);
 3349:                     $$rowtotal += @{$types}; 
 3350:             }
 3351:         }
 3352:         $datatable .= 
 3353:             &usertype_update_row($settings,{'default' => $othertitle},
 3354:                                  \%fieldtitles,\@fields,['default'],
 3355:                                  \$numrows);
 3356:         $$rowtotal ++;     
 3357:     }
 3358:     return $datatable;
 3359: }
 3360: 
 3361: sub print_autocreate {
 3362:     my ($dom,$settings,$rowtotal) = @_;
 3363:     my (%createon,%createoff,%currhash);
 3364:     my @types = ('xml','req');
 3365:     if (ref($settings) eq 'HASH') {
 3366:         foreach my $item (@types) {
 3367:             $createoff{$item} = ' checked="checked" ';
 3368:             $createon{$item} = ' ';
 3369:             if (exists($settings->{$item})) {
 3370:                 if ($settings->{$item}) {
 3371:                     $createon{$item} = ' checked="checked" ';
 3372:                     $createoff{$item} = ' ';
 3373:                 }
 3374:             }
 3375:         }
 3376:         if ($settings->{'xmldc'} ne '') {
 3377:             $currhash{$settings->{'xmldc'}} = 1;
 3378:         }
 3379:     } else {
 3380:         foreach my $item (@types) {
 3381:             $createoff{$item} = ' checked="checked" ';
 3382:             $createon{$item} = ' ';
 3383:         }
 3384:     }
 3385:     $$rowtotal += 2;
 3386:     my $numinrow = 2;
 3387:     my $datatable='<tr class="LC_odd_row">'.
 3388:                   '<td>'.&mt('Create pending official courses from XML files').'</td>'.
 3389:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3390:                   '<input type="radio" name="autocreate_xml"'.
 3391:                   $createon{'xml'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3392:                   '<label><input type="radio" name="autocreate_xml"'.
 3393:                   $createoff{'xml'}.' value="0" />'.&mt('No').'</label></span>'.
 3394:                   '</td></tr><tr>'.
 3395:                   '<td>'.&mt('Create pending requests for official courses (if validated)').'</td>'.
 3396:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3397:                   '<input type="radio" name="autocreate_req"'.
 3398:                   $createon{'req'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3399:                   '<label><input type="radio" name="autocreate_req"'.
 3400:                   $createoff{'req'}.' value="0" />'.&mt('No').'</label></span>';
 3401:     my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 3402:                                                    'autocreate_xmldc',%currhash);
 3403:     $datatable .= '</td></tr><tr class="LC_odd_row"><td>';
 3404:     if ($numdc > 1) {
 3405:         $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)').
 3406:                       '</td><td class="LC_left_item">';
 3407:     } else {
 3408:         $datatable .= &mt('Course creation processed as:').
 3409:                       '</td><td class="LC_right_item">';
 3410:     }
 3411:     $datatable .= $dctable.'</td></tr>';
 3412:     $$rowtotal += $rows;
 3413:     return $datatable;
 3414: }
 3415: 
 3416: sub print_directorysrch {
 3417:     my ($position,$dom,$settings,$rowtotal) = @_;
 3418:     my $datatable;
 3419:     if ($position eq 'top') {
 3420:         my $instsrchon = ' ';
 3421:         my $instsrchoff = ' checked="checked" ';
 3422:         my ($exacton,$containson,$beginson);
 3423:         my $instlocalon = ' ';
 3424:         my $instlocaloff = ' checked="checked" ';
 3425:         if (ref($settings) eq 'HASH') {
 3426:             if ($settings->{'available'} eq '1') {
 3427:                 $instsrchon = $instsrchoff;
 3428:                 $instsrchoff = ' ';
 3429:             }
 3430:             if ($settings->{'localonly'} eq '1') {
 3431:                 $instlocalon = $instlocaloff;
 3432:                 $instlocaloff = ' ';
 3433:             }
 3434:             if (ref($settings->{'searchtypes'}) eq 'ARRAY') {
 3435:                 foreach my $type (@{$settings->{'searchtypes'}}) {
 3436:                     if ($type eq 'exact') {
 3437:                         $exacton = ' checked="checked" ';
 3438:                     } elsif ($type eq 'contains') {
 3439:                         $containson = ' checked="checked" ';
 3440:                     } elsif ($type eq 'begins') {
 3441:                         $beginson = ' checked="checked" ';
 3442:                     }
 3443:                 }
 3444:             } else {
 3445:                 if ($settings->{'searchtypes'} eq 'exact') {
 3446:                     $exacton = ' checked="checked" ';
 3447:                 } elsif ($settings->{'searchtypes'} eq 'contains') {
 3448:                     $containson = ' checked="checked" ';
 3449:                 } elsif ($settings->{'searchtypes'} eq 'specify') {
 3450:                     $exacton = ' checked="checked" ';
 3451:                     $containson = ' checked="checked" ';
 3452:                 }
 3453:             }
 3454:         }
 3455:         my ($searchtitles,$titleorder) = &sorted_searchtitles();
 3456:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3457: 
 3458:         my $numinrow = 4;
 3459:         my $cansrchrow = 0;
 3460:         $datatable='<tr class="LC_odd_row">'.
 3461:                    '<td colspan="2"><span class ="LC_nobreak">'.&mt('Institutional directory search available?').'</span></td>'.
 3462:                    '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3463:                    '<input type="radio" name="dirsrch_available"'.
 3464:                    $instsrchon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3465:                    '<label><input type="radio" name="dirsrch_available"'.
 3466:                    $instsrchoff.' value="0" />'.&mt('No').'</label></span></td>'.
 3467:                    '</tr><tr>'.
 3468:                    '<td colspan="2"><span class ="LC_nobreak">'.&mt('Other domains can search institution?').'</span></td>'.
 3469:                    '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3470:                    '<input type="radio" name="dirsrch_instlocalonly"'.
 3471:                    $instlocaloff.' value="0" />'.&mt('Yes').'</label>&nbsp;'.
 3472:                    '<label><input type="radio" name="dirsrch_instlocalonly"'.
 3473:                    $instlocalon.' value="1" />'.&mt('No').'</label></span></td>'.
 3474:                    '</tr>';
 3475:         $$rowtotal += 2;
 3476:         if (ref($usertypes) eq 'HASH') {
 3477:             if (keys(%{$usertypes}) > 0) {
 3478:                 $datatable .= &insttypes_row($settings,$types,$usertypes,$dom,
 3479:                                              $numinrow,$othertitle,'cansearch',
 3480:                                              $rowtotal);
 3481:                 $cansrchrow = 1;
 3482:             }
 3483:         }
 3484:         if ($cansrchrow) {
 3485:             $$rowtotal ++;
 3486:             $datatable .= '<tr>';
 3487:         } else {
 3488:             $datatable .= '<tr class="LC_odd_row">';
 3489:         }
 3490:         $datatable .= '<td><span class ="LC_nobreak">'.&mt('Supported search methods').
 3491:                       '</span></td><td class="LC_left_item" colspan="2"><table><tr>';
 3492:         foreach my $title (@{$titleorder}) {
 3493:             if (defined($searchtitles->{$title})) {
 3494:                 my $check = ' ';
 3495:                 if (ref($settings) eq 'HASH') {
 3496:                     if (ref($settings->{'searchby'}) eq 'ARRAY') {
 3497:                         if (grep(/^\Q$title\E$/,@{$settings->{'searchby'}})) {
 3498:                             $check = ' checked="checked" ';
 3499:                         }
 3500:                     }
 3501:                 }
 3502:                 $datatable .= '<td class="LC_left_item">'.
 3503:                               '<span class="LC_nobreak"><label>'.
 3504:                               '<input type="checkbox" name="searchby" '.
 3505:                               'value="'.$title.'"'.$check.'/>'.
 3506:                               $searchtitles->{$title}.'</label></span></td>';
 3507:             }
 3508:         }
 3509:         $datatable .= '</tr></table></td></tr>';
 3510:         $$rowtotal ++;
 3511:         if ($cansrchrow) {
 3512:             $datatable .= '<tr class="LC_odd_row">';
 3513:         } else {
 3514:             $datatable .= '<tr>';
 3515:         }
 3516:         $datatable .= '<td><span class ="LC_nobreak">'.&mt('Search latitude').'</span></td>'.   
 3517:                       '<td class="LC_left_item" colspan="2">'.
 3518:                       '<span class="LC_nobreak"><label>'.
 3519:                       '<input type="checkbox" name="searchtypes" '.
 3520:                       $exacton.' value="exact" />'.&mt('Exact match').
 3521:                       '</label>&nbsp;'.
 3522:                       '<label><input type="checkbox" name="searchtypes" '.
 3523:                       $beginson.' value="begins" />'.&mt('Begins with').
 3524:                       '</label>&nbsp;'.
 3525:                       '<label><input type="checkbox" name="searchtypes" '.
 3526:                       $containson.' value="contains" />'.&mt('Contains').
 3527:                       '</label></span></td></tr>';
 3528:         $$rowtotal ++;
 3529:     } else {
 3530:         my $domsrchon = ' checked="checked" ';
 3531:         my $domsrchoff = ' ';
 3532:         my $domlocalon = ' ';
 3533:         my $domlocaloff = ' checked="checked" ';
 3534:         if (ref($settings) eq 'HASH') {
 3535:             if ($settings->{'lclocalonly'} eq '1') {
 3536:                 $domlocalon = $domlocaloff;
 3537:                 $domlocaloff = ' ';
 3538:             }
 3539:             if ($settings->{'lcavailable'} eq '0') {
 3540:                 $domsrchoff = $domsrchon;
 3541:                 $domsrchon = ' ';
 3542:             }
 3543:         }
 3544:         $datatable='<tr class="LC_odd_row">'.
 3545:                       '<td colspan="2"><span class ="LC_nobreak">'.&mt('LON-CAPA directory search available?').'</span></td>'.
 3546:                       '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3547:                       '<input type="radio" name="dirsrch_domavailable"'.
 3548:                       $domsrchon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3549:                       '<label><input type="radio" name="dirsrch_domavailable"'.
 3550:                       $domsrchoff.' value="0" />'.&mt('No').'</label></span></td>'.
 3551:                       '</tr><tr>'.
 3552:                       '<td colspan="2"><span class ="LC_nobreak">'.&mt('Other domains can search LON-CAPA domain?').'</span></td>'.
 3553:                       '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3554:                       '<input type="radio" name="dirsrch_domlocalonly"'.
 3555:                       $domlocaloff.' value="0" />'.&mt('Yes').'</label>&nbsp;'.
 3556:                       '<label><input type="radio" name="dirsrch_domlocalonly"'.
 3557:                       $domlocalon.' value="1" />'.&mt('No').'</label></span></td>'.
 3558:                       '</tr>';
 3559:         $$rowtotal += 2;
 3560:     }
 3561:     return $datatable;
 3562: }
 3563: 
 3564: sub print_contacts {
 3565:     my ($position,$dom,$settings,$rowtotal) = @_;
 3566:     my $datatable;
 3567:     my @contacts = ('adminemail','supportemail');
 3568:     my (%checked,%to,%otheremails,%bccemails,%includestr,%includeloc,%currfield,
 3569:         $maxsize,$fields,$fieldtitles,$fieldoptions,$possoptions,@mailings,%lonstatus);
 3570:     if ($position eq 'top') {
 3571:         if (ref($settings) eq 'HASH') {
 3572:             foreach my $item (@contacts) {
 3573:                 if (exists($settings->{$item})) {
 3574:                     $to{$item} = $settings->{$item};
 3575:                 }
 3576:             }
 3577:         }
 3578:     } elsif ($position eq 'middle') {
 3579:         @mailings = ('errormail','packagesmail','lonstatusmail','requestsmail',
 3580:                      'updatesmail','idconflictsmail','hostipmail');
 3581:         foreach my $type (@mailings) {
 3582:             $otheremails{$type} = '';
 3583:         }
 3584:     } elsif ($position eq 'lower') {
 3585:         if (ref($settings) eq 'HASH') {
 3586:             if (ref($settings->{'lonstatus'}) eq 'HASH') {
 3587:                 %lonstatus = %{$settings->{'lonstatus'}};
 3588:             }
 3589:         }
 3590:     } else {
 3591:         @mailings = ('helpdeskmail','otherdomsmail');
 3592:         foreach my $type (@mailings) {
 3593:             $otheremails{$type} = '';
 3594:         }
 3595:         $bccemails{'helpdeskmail'} = '';
 3596:         $bccemails{'otherdomsmail'} = '';
 3597:         $includestr{'helpdeskmail'} = '';
 3598:         $includestr{'otherdomsmail'} = '';
 3599:         ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
 3600:     }
 3601:     if (ref($settings) eq 'HASH') {
 3602:         unless (($position eq 'top') || ($position eq 'lower')) {
 3603:             foreach my $type (@mailings) {
 3604:                 if (exists($settings->{$type})) {
 3605:                     if (ref($settings->{$type}) eq 'HASH') {
 3606:                         foreach my $item (@contacts) {
 3607:                             if ($settings->{$type}{$item}) {
 3608:                                 $checked{$type}{$item} = ' checked="checked" ';
 3609:                             }
 3610:                         }
 3611:                         $otheremails{$type} = $settings->{$type}{'others'};
 3612:                         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 3613:                             $bccemails{$type} = $settings->{$type}{'bcc'};
 3614:                             if ($settings->{$type}{'include'} ne '') {
 3615:                                 ($includeloc{$type},$includestr{$type}) = split(/:/,$settings->{$type}{'include'},2);
 3616:                                 $includestr{$type} = &unescape($includestr{$type});
 3617:                             }
 3618:                         }
 3619:                     }
 3620:                 } elsif ($type eq 'lonstatusmail') {
 3621:                     $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" ';
 3622:                 }
 3623:             }
 3624:         }
 3625:         if ($position eq 'bottom') {
 3626:             foreach my $type (@mailings) {
 3627:                 $bccemails{$type} = $settings->{$type}{'bcc'};
 3628:                 if ($settings->{$type}{'include'} ne '') {
 3629:                     ($includeloc{$type},$includestr{$type}) = split(/:/,$settings->{$type}{'include'},2);
 3630:                     $includestr{$type} = &unescape($includestr{$type});
 3631:                 }
 3632:             }
 3633:             if (ref($settings->{'helpform'}) eq 'HASH') {
 3634:                 if (ref($fields) eq 'ARRAY') {
 3635:                     foreach my $field (@{$fields}) {
 3636:                         $currfield{$field} = $settings->{'helpform'}{$field};
 3637:                     }
 3638:                 }
 3639:                 if (exists($settings->{'helpform'}{'maxsize'})) {
 3640:                     $maxsize = $settings->{'helpform'}{'maxsize'};
 3641:                 } else {
 3642:                     $maxsize = '1.0';
 3643:                 }
 3644:             } else {
 3645:                 if (ref($fields) eq 'ARRAY') {
 3646:                     foreach my $field (@{$fields}) {
 3647:                         $currfield{$field} = 'yes';
 3648:                     }
 3649:                 }
 3650:                 $maxsize = '1.0';
 3651:             }
 3652:         }
 3653:     } else {
 3654:         if ($position eq 'top') {
 3655:             $to{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
 3656:             $to{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
 3657:             $checked{'errormail'}{'adminemail'} = ' checked="checked" ';
 3658:             $checked{'packagesmail'}{'adminemail'} = ' checked="checked" ';
 3659:             $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" ';
 3660:             $checked{'requestsmail'}{'adminemail'} = ' checked="checked" ';
 3661:             $checked{'updatesmail'}{'adminemail'} = ' checked="checked" ';
 3662:             $checked{'idconflictsmail'}{'adminemail'} = ' checked="checked" ';
 3663:             $checked{'hostipmail'}{'adminemail'} = ' checked="checked" ';
 3664:         } elsif ($position eq 'bottom') {
 3665:             $checked{'helpdeskmail'}{'supportemail'} = ' checked="checked" ';
 3666:             $checked{'otherdomsmail'}{'supportemail'} = ' checked="checked" ';
 3667:             if (ref($fields) eq 'ARRAY') {
 3668:                 foreach my $field (@{$fields}) {
 3669:                     $currfield{$field} = 'yes';
 3670:                 }
 3671:             }
 3672:             $maxsize = '1.0';
 3673:         }
 3674:     }
 3675:     my ($titles,$short_titles) = &contact_titles();
 3676:     my $rownum = 0;
 3677:     my $css_class;
 3678:     if ($position eq 'top') {
 3679:         foreach my $item (@contacts) {
 3680:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 3681:             $datatable .= '<tr'.$css_class.'>'. 
 3682:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
 3683:                           '</span></td><td class="LC_right_item">'.
 3684:                           '<input type="text" name="'.$item.'" value="'.
 3685:                           $to{$item}.'" /></td></tr>';
 3686:             $rownum ++;
 3687:         }
 3688:     } elsif ($position eq 'bottom') {
 3689:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 3690:         $datatable .= '<tr'.$css_class.'>'.
 3691:                       '<td>'.&mt('Extra helpdesk form fields:').'<br />'.
 3692:                       &mt('(e-mail, subject, and description always shown)').
 3693:                       '</td><td class="LC_left_item">';
 3694:         if ((ref($fields) eq 'ARRAY') && (ref($fieldtitles) eq 'HASH') &&
 3695:             (ref($fieldoptions) eq 'HASH') && (ref($possoptions) eq 'HASH')) {
 3696:             $datatable .= '<table><tr><th>'.&mt('Field').'</th><th>'.&mt('Status').'</th></tr>';
 3697:             foreach my $field (@{$fields}) {
 3698:                 $datatable .= '<tr><td>'.$fieldtitles->{$field};
 3699:                 if (($field eq 'screenshot') || ($field eq 'cc')) {
 3700:                     $datatable .= ' '.&mt('(logged-in users)');
 3701:                 }
 3702:                 $datatable .='</td><td>';
 3703:                 my $clickaction;
 3704:                 if ($field eq 'screenshot') {
 3705:                     $clickaction = ' onclick="screenshotSize(this);"';
 3706:                 }
 3707:                 if (ref($possoptions->{$field}) eq 'ARRAY') {
 3708:                     foreach my $option (@{$possoptions->{$field}}) {
 3709:                         my $checked;
 3710:                         if ($currfield{$field} eq $option) {
 3711:                             $checked = ' checked="checked"';
 3712:                         }
 3713:                         $datatable .= '<span class="LC_nobreak"><label>'.
 3714:                                       '<input type="radio" name="helpform_'.$field.'" '.
 3715:                                       'value="'.$option.'"'.$checked.$clickaction.' />'.$fieldoptions->{$option}.
 3716:                                       '</label></span>'.('&nbsp;'x2);
 3717:                     }
 3718:                 }
 3719:                 if ($field eq 'screenshot') {
 3720:                     my $display;
 3721:                     if ($currfield{$field} eq 'no') {
 3722:                         $display = ' style="display:none"';
 3723:                     }
 3724:                     $datatable .= '</td></tr><tr id="help_screenshotsize"'.$display.'>'.
 3725:                                   '<td>'.&mt('Maximum size for upload (MB)').'</td><td>'.
 3726:                                   '<input type="text" size="5" name="helpform_maxsize" value="'.$maxsize.'" />';
 3727:                 }
 3728:                 $datatable .= '</td></tr>';
 3729:             }
 3730:             $datatable .= '</table>';
 3731:         }
 3732:         $datatable .= '</td></tr>'."\n";
 3733:         $rownum ++;
 3734:     }
 3735:     unless (($position eq 'top') || ($position eq 'lower')) {
 3736:         foreach my $type (@mailings) {
 3737:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 3738:             $datatable .= '<tr'.$css_class.'>'.
 3739:                           '<td><span class="LC_nobreak">'.
 3740:                           $titles->{$type}.': </span></td>'.
 3741:                           '<td class="LC_left_item">';
 3742:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 3743:                 $datatable .= '<fieldset><legend>'.&mt('E-mail recipient(s)').'</legend>';
 3744:             }
 3745:             $datatable .= '<span class="LC_nobreak">';
 3746:             foreach my $item (@contacts) {
 3747:                 $datatable .= '<label>'.
 3748:                               '<input type="checkbox" name="'.$type.'"'.
 3749:                               $checked{$type}{$item}.
 3750:                               ' value="'.$item.'" />'.$short_titles->{$item}.
 3751:                               '</label>&nbsp;';
 3752:             }
 3753:             $datatable .= '</span><br />'.&mt('Others').':&nbsp;&nbsp;'.
 3754:                           '<input type="text" name="'.$type.'_others" '.
 3755:                           'value="'.$otheremails{$type}.'"  />';
 3756:             my %locchecked;
 3757:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 3758:                 foreach my $loc ('s','b') {
 3759:                     if ($includeloc{$type} eq $loc) {
 3760:                         $locchecked{$loc} = ' checked="checked"';
 3761:                         last;
 3762:                     }
 3763:                 }
 3764:                 $datatable .= '<br />'.&mt('Bcc:').('&nbsp;'x6).
 3765:                               '<input type="text" name="'.$type.'_bcc" '.
 3766:                               'value="'.$bccemails{$type}.'"  /></fieldset>'.
 3767:                               '<fieldset><legend>'.&mt('Optional added text').'</legend>'.
 3768:                               &mt('Text automatically added to e-mail:').' '.
 3769:                               '<input type="text" name="'.$type.'_includestr" value="'.$includestr{$type}.'" /><br />'.
 3770:                               '<span class="LC_nobreak">'.&mt('Location:').'&nbsp;'.
 3771:                               '<label><input type="radio" name="'.$type.'_includeloc" value="s"'.$locchecked{'s'}.' />'.&mt('in subject').'</label>'.
 3772:                               ('&nbsp;'x2).
 3773:                               '<label><input type="radio" name="'.$type.'_includeloc" value="b"'.$locchecked{'b'}.' />'.&mt('in body').'</label>'.
 3774:                               '</span></fieldset>';
 3775:             }
 3776:             $datatable .= '</td></tr>'."\n";
 3777:             $rownum ++;
 3778:         }
 3779:     }
 3780:     if ($position eq 'middle') {
 3781:         my %choices;
 3782:         my $corelink = &core_link_msu();
 3783:         $choices{'reporterrors'} = &mt('E-mail error reports to [_1]',$corelink);
 3784:         $choices{'reportupdates'} = &mt('E-mail record of completed LON-CAPA updates to [_1]',
 3785:                                         $corelink);
 3786:         $choices{'reportstatus'} = &mt('E-mail status if errors above threshold to [_1]',$corelink);
 3787:         my @toggles = ('reporterrors','reportupdates','reportstatus');
 3788:         my %defaultchecked = ('reporterrors'  => 'on',
 3789:                               'reportupdates' => 'on',
 3790:                               'reportstatus'  => 'on');
 3791:         (my $reports,$rownum) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 3792:                                                    \%choices,$rownum);
 3793:         $datatable .= $reports;
 3794:     } elsif ($position eq 'lower') {
 3795:         my (%current,%excluded,%weights);
 3796:         my ($defaults,$names) = &Apache::loncommon::lon_status_items();
 3797:         if ($lonstatus{'threshold'} =~ /^\d+$/) {
 3798:             $current{'errorthreshold'} = $lonstatus{'threshold'};
 3799:         } else {
 3800:             $current{'errorthreshold'} = $defaults->{'threshold'};
 3801:         }
 3802:         if ($lonstatus{'sysmail'} =~ /^\d+$/) {
 3803:             $current{'errorsysmail'} = $lonstatus{'sysmail'};
 3804:         } else {
 3805:             $current{'errorsysmail'} = $defaults->{'sysmail'};
 3806:         }
 3807:         if (ref($lonstatus{'weights'}) eq 'HASH') {
 3808:             foreach my $type ('E','W','N','U') {
 3809:                 if ($lonstatus{'weights'}{$type} =~ /^\d+$/) {
 3810:                     $weights{$type} = $lonstatus{'weights'}{$type};
 3811:                 } else {
 3812:                     $weights{$type} = $defaults->{$type};
 3813:                 }
 3814:             }
 3815:         } else {
 3816:             foreach my $type ('E','W','N','U') {
 3817:                 $weights{$type} = $defaults->{$type};
 3818:             }
 3819:         }
 3820:         if (ref($lonstatus{'excluded'}) eq 'ARRAY') {
 3821:             if (@{$lonstatus{'excluded'}} > 0) {
 3822:                 map {$excluded{$_} = 1; } @{$lonstatus{'excluded'}};
 3823:             }
 3824:         }
 3825:         foreach my $item ('errorthreshold','errorsysmail') {
 3826:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 3827:             $datatable .= '<tr'.$css_class.'>'.
 3828:                           '<td class="LC_left_item"><span class="LC_nobreak">'.
 3829:                           $titles->{$item}.
 3830:                           '</span></td><td class="LC_left_item">'.
 3831:                           '<input type="text" name="'.$item.'" value="'.
 3832:                           $current{$item}.'" size="5" /></td></tr>';
 3833:             $rownum ++;
 3834:         }
 3835:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 3836:         $datatable .= '<tr'.$css_class.'>'.
 3837:                       '<td class="LC_left_item">'.
 3838:                       '<span class="LC_nobreak">'.$titles->{'errorweights'}.
 3839:                       '</span></td><td class="LC_left_item"><table><tr>';
 3840:         foreach my $type ('E','W','N','U') {
 3841:             $datatable .= '<td>'.$names->{$type}.'<br />'.
 3842:                           '<input type="text" name="errorweights_'.$type.'" value="'.
 3843:                           $weights{$type}.'" size="5" /></td>';
 3844:         }
 3845:         $datatable .= '</tr></table></tr>';
 3846:         $rownum ++;
 3847:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 3848:         $datatable .= '<tr'.$css_class.'><td class="LC_left_item">'.
 3849:                       $titles->{'errorexcluded'}.'</td>'.
 3850:                       '<td class="LC_left_item"><table>';
 3851:         my $numinrow = 4;
 3852:         my @ids = sort(values(%Apache::lonnet::serverhomeIDs));
 3853:         for (my $i=0; $i<@ids; $i++) {
 3854:             my $rem = $i%($numinrow);
 3855:             if ($rem == 0) {
 3856:                 if ($i > 0) {
 3857:                     $datatable .= '</tr>';
 3858:                 }
 3859:                 $datatable .= '<tr>';
 3860:             }
 3861:             my $check;
 3862:             if ($excluded{$ids[$i]}) {
 3863:                 $check = ' checked="checked" ';
 3864:             }
 3865:             $datatable .= '<td class="LC_left_item">'.
 3866:                           '<span class="LC_nobreak"><label>'.
 3867:                           '<input type="checkbox" name="errorexcluded" '.
 3868:                           'value="'.$ids[$i].'"'.$check.' />'.
 3869:                           $ids[$i].'</label></span></td>';
 3870:         }
 3871:         my $colsleft = $numinrow - @ids%($numinrow);
 3872:         if ($colsleft > 1 ) {
 3873:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 3874:                           '&nbsp;</td>';
 3875:         } elsif ($colsleft == 1) {
 3876:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 3877:         }
 3878:         $datatable .= '</tr></table></td></tr>';
 3879:         $rownum ++;
 3880:     } elsif ($position eq 'bottom') {
 3881:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3882:         my (@posstypes,%usertypeshash);
 3883:         if (ref($types) eq 'ARRAY') {
 3884:             @posstypes = @{$types};
 3885:         }
 3886:         if (@posstypes) {
 3887:             if (ref($usertypes) eq 'HASH') {
 3888:                 %usertypeshash = %{$usertypes};
 3889:             }
 3890:             my @overridden;
 3891:             my $numinrow = 4;
 3892:             if (ref($settings) eq 'HASH') {
 3893:                 if (ref($settings->{'overrides'}) eq 'HASH') {
 3894:                     foreach my $key (sort(keys(%{$settings->{'overrides'}}))) {
 3895:                         if (ref($settings->{'overrides'}{$key}) eq 'HASH') {
 3896:                             push(@overridden,$key);
 3897:                             foreach my $item (@contacts) {
 3898:                                 if ($settings->{'overrides'}{$key}{$item}) {
 3899:                                     $checked{'override_'.$key}{$item} = ' checked="checked" ';
 3900:                                 }
 3901:                             }
 3902:                             $otheremails{'override_'.$key} = $settings->{'overrides'}{$key}{'others'};
 3903:                             $bccemails{'override_'.$key} = $settings->{'overrides'}{$key}{'bcc'};
 3904:                             $includeloc{'override_'.$key} = '';
 3905:                             $includestr{'override_'.$key} = '';
 3906:                             if ($settings->{'overrides'}{$key}{'include'} ne '') {
 3907:                                 ($includeloc{'override_'.$key},$includestr{'override_'.$key}) =
 3908:                                     split(/:/,$settings->{'overrides'}{$key}{'include'},2);
 3909:                                 $includestr{'override_'.$key} = &unescape($includestr{'override_'.$key});
 3910:                             }
 3911:                         }
 3912:                     }
 3913:                 }
 3914:             }
 3915:             my $customclass = 'LC_helpdesk_override';
 3916:             my $optionsprefix = 'LC_options_helpdesk_';
 3917: 
 3918:             my $onclicktypes = "toggleHelpdeskRow(this.form,'overrides','$customclass','$optionsprefix');";
 3919: 
 3920:             $datatable .= &insttypes_row($settings,$types,$usertypes,$dom,
 3921:                                          $numinrow,$othertitle,'overrides',
 3922:                                          \$rownum,$onclicktypes,$customclass);
 3923:             $rownum ++;
 3924:             $usertypeshash{'default'} = $othertitle;
 3925:             foreach my $status (@posstypes) {
 3926:                 my $css_class;
 3927:                 if ($rownum%2) {
 3928:                     $css_class = 'LC_odd_row ';
 3929:                 }
 3930:                 $css_class .= $customclass;
 3931:                 my $rowid = $optionsprefix.$status;
 3932:                 my $hidden = 1;
 3933:                 my $currstyle = 'display:none';
 3934:                 if (grep(/^\Q$status\E$/,@overridden)) {
 3935:                     $currstyle = 'display:table-row';
 3936:                     $hidden = 0;
 3937:                 }
 3938:                 my $key = 'override_'.$status;
 3939:                 $datatable .= &overridden_helpdesk($checked{$key},$otheremails{$key},$bccemails{$key},
 3940:                                                   $includeloc{$key},$includestr{$key},$status,$rowid,
 3941:                                                   $usertypeshash{$status},$css_class,$currstyle,
 3942:                                                   \@contacts,$short_titles);
 3943:                 unless ($hidden) {
 3944:                     $rownum ++;
 3945:                 }
 3946:             }
 3947:         }
 3948:     }
 3949:     $$rowtotal += $rownum;
 3950:     return $datatable;
 3951: }
 3952: 
 3953: sub core_link_msu {
 3954:     return &Apache::loncommon::modal_link('http://loncapa.org/core.html',
 3955:                                           &mt('LON-CAPA core group - MSU'),600,500);
 3956: }
 3957: 
 3958: sub overridden_helpdesk {
 3959:     my ($checked,$otheremails,$bccemails,$includeloc,$includestr,$type,$rowid,
 3960:         $typetitle,$css_class,$rowstyle,$contacts,$short_titles) = @_;
 3961:     my $class = 'LC_left_item';
 3962:     if ($css_class) {
 3963:         $css_class = ' class="'.$css_class.'"';
 3964:     }
 3965:     if ($rowid) {
 3966:         $rowid = ' id="'.$rowid.'"';
 3967:     }
 3968:     if ($rowstyle) {
 3969:         $rowstyle = ' style="'.$rowstyle.'"';
 3970:     }
 3971:     my ($output,$description);
 3972:     $description = &mt('Helpdesk requests from: [_1] in this domain (overrides default)',"<b>$typetitle</b>");
 3973:     $output = '<tr'.$css_class.$rowid.$rowstyle.'>'.
 3974:               "<td>$description</td>\n".
 3975:               '<td class="'.$class.'" colspan="2">'.
 3976:               '<fieldset><legend>'.&mt('E-mail recipient(s)').'</legend>'.
 3977:               '<span class="LC_nobreak">';
 3978:     if (ref($contacts) eq 'ARRAY') {
 3979:         foreach my $item (@{$contacts}) {
 3980:             my $check;
 3981:             if (ref($checked) eq 'HASH') {
 3982:                $check = $checked->{$item};
 3983:             }
 3984:             my $title;
 3985:             if (ref($short_titles) eq 'HASH') {
 3986:                 $title = $short_titles->{$item};
 3987:             }
 3988:             $output .= '<label>'.
 3989:                        '<input type="checkbox" name="override_'.$type.'"'.$check.
 3990:                        ' value="'.$item.'" />'.$title.'</label>&nbsp;';
 3991:         }
 3992:     }
 3993:     $output .= '</span><br />'.&mt('Others').':&nbsp;&nbsp;'.
 3994:                '<input type="text" name="override_'.$type.'_others" '.
 3995:                'value="'.$otheremails.'"  />';
 3996:     my %locchecked;
 3997:     foreach my $loc ('s','b') {
 3998:         if ($includeloc eq $loc) {
 3999:             $locchecked{$loc} = ' checked="checked"';
 4000:             last;
 4001:         }
 4002:     }
 4003:     $output .= '<br />'.&mt('Bcc:').('&nbsp;'x6).
 4004:                '<input type="text" name="override_'.$type.'_bcc" '.
 4005:                'value="'.$bccemails.'"  /></fieldset>'.
 4006:                '<fieldset><legend>'.&mt('Optional added text').'</legend>'.
 4007:                &mt('Text automatically added to e-mail:').' '.
 4008:                '<input type="text" name="override_'.$type.'_includestr" value="'.$includestr.'" /><br />'.
 4009:                '<span class="LC_nobreak">'.&mt('Location:').'&nbsp;'.
 4010:                '<label><input type="radio" name="override_'.$type.'_includeloc" value="s"'.$locchecked{'s'}.' />'.&mt('in subject').'</label>'.
 4011:                ('&nbsp;'x2).
 4012:                '<label><input type="radio" name="override_'.$type.'_includeloc" value="b"'.$locchecked{'b'}.' />'.&mt('in body').'</label>'.
 4013:                '</span></fieldset>'.
 4014:                '</td></tr>'."\n";
 4015:     return $output;
 4016: }
 4017: 
 4018: sub contacts_javascript {
 4019:     return <<"ENDSCRIPT";
 4020: 
 4021: <script type="text/javascript">
 4022: // <![CDATA[
 4023: 
 4024: function screenshotSize(field) {
 4025:     if (document.getElementById('help_screenshotsize')) {
 4026:         if (field.value == 'no') {
 4027:             document.getElementById('help_screenshotsize').style.display="none";
 4028:         } else {
 4029:             document.getElementById('help_screenshotsize').style.display="";
 4030:         }
 4031:     }
 4032:     return;
 4033: }
 4034: 
 4035: function toggleHelpdeskRow(form,checkbox,target,prefix,docount) {
 4036:     if (form.elements[checkbox].length != undefined) {
 4037:         var count = 0;
 4038:         if (docount) {
 4039:             for (var i=0; i<form.elements[checkbox].length; i++) {
 4040:                 if (form.elements[checkbox][i].checked) {
 4041:                     count ++;
 4042:                 }
 4043:             }
 4044:         }
 4045:         for (var i=0; i<form.elements[checkbox].length; i++) {
 4046:             var type = form.elements[checkbox][i].value;
 4047:             if (document.getElementById(prefix+type)) {
 4048:                 if (form.elements[checkbox][i].checked) {
 4049:                     document.getElementById(prefix+type).style.display = 'table-row';
 4050:                     if (count % 2 == 1) {
 4051:                         document.getElementById(prefix+type).className = target+' LC_odd_row';
 4052:                     } else {
 4053:                         document.getElementById(prefix+type).className = target;
 4054:                     }
 4055:                     count ++;
 4056:                 } else {
 4057:                     document.getElementById(prefix+type).style.display = 'none';
 4058:                 }
 4059:             }
 4060:         }
 4061:     }
 4062:     return;
 4063: }
 4064: 
 4065: // ]]>
 4066: </script>
 4067: 
 4068: ENDSCRIPT
 4069: }
 4070: 
 4071: sub print_helpsettings {
 4072:     my ($position,$dom,$settings,$rowtotal) = @_;
 4073:     my $confname = $dom.'-domainconfig';
 4074:     my $formname = 'display';
 4075:     my ($datatable,$itemcount);
 4076:     if ($position eq 'top') {
 4077:         $itemcount = 1;
 4078:         my (%choices,%defaultchecked,@toggles);
 4079:         $choices{'submitbugs'} = &mt('Display link to: [_1]?',
 4080:                                      &Apache::loncommon::modal_link('http://bugs.loncapa.org',
 4081:                                      &mt('LON-CAPA bug tracker'),600,500));
 4082:         %defaultchecked = ('submitbugs' => 'on');
 4083:         @toggles = ('submitbugs');
 4084:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 4085:                                                      \%choices,$itemcount);
 4086:         $$rowtotal ++;
 4087:     } else {
 4088:         my $css_class;
 4089:         my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
 4090:         my (%customroles,%ordered,%current);
 4091:         if (ref($settings) eq 'HASH') {
 4092:             if (ref($settings->{'adhoc'}) eq 'HASH') {
 4093:                 %current = %{$settings->{'adhoc'}};
 4094:             }
 4095:         }
 4096:         my $count = 0;
 4097:         foreach my $key (sort(keys(%existing))) {
 4098:             if ($key=~/^rolesdef\_(\w+)$/) {
 4099:                 my $rolename = $1;
 4100:                 my (%privs,$order);
 4101:                 ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 4102:                 $customroles{$rolename} = \%privs;
 4103:                 if (ref($current{$rolename}) eq 'HASH') {
 4104:                     $order = $current{$rolename}{'order'};
 4105:                 }
 4106:                 if ($order eq '') {
 4107:                     $order = $count;
 4108:                 }
 4109:                 $ordered{$order} = $rolename;
 4110:                 $count++;
 4111:             }
 4112:         }
 4113:         my $maxnum = scalar(keys(%ordered));
 4114:         my @roles_by_num = ();
 4115:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 4116:             push(@roles_by_num,$item);
 4117:         }
 4118:         my $context = 'domprefs';
 4119:         my $crstype = 'Course';
 4120:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4121:         my @accesstypes = ('all','dh','da','none');
 4122:         my ($numstatustypes,@jsarray);
 4123:         if (ref($types) eq 'ARRAY') {
 4124:             if (@{$types} > 0) {
 4125:                 $numstatustypes = scalar(@{$types});
 4126:                 push(@accesstypes,'status');
 4127:                 @jsarray = ('bystatus');
 4128:             }
 4129:         }
 4130:         my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh','da']);
 4131:         if (keys(%domhelpdesk)) {
 4132:             push(@accesstypes,('inc','exc'));
 4133:             push(@jsarray,('notinc','notexc'));
 4134:         }
 4135:         my $hiddenstr = join("','",@jsarray);
 4136:         $datatable .= &helpsettings_javascript(\@roles_by_num,$maxnum,$hiddenstr,$formname);
 4137:         my $context = 'domprefs';
 4138:         my $crstype = 'Course';
 4139:         my $prefix = 'helproles_';
 4140:         my $add_class = 'LC_hidden';
 4141:         foreach my $num (@roles_by_num) {
 4142:             my $role = $ordered{$num};
 4143:             my ($desc,$access,@statuses);
 4144:             if (ref($current{$role}) eq 'HASH') {
 4145:                 $desc = $current{$role}{'desc'};
 4146:                 $access = $current{$role}{'access'};
 4147:                 if (ref($current{$role}{'insttypes'}) eq 'ARRAY') {
 4148:                     @statuses = @{$current{$role}{'insttypes'}};
 4149:                 }
 4150:             }
 4151:             if ($desc eq '') {
 4152:                 $desc = $role;
 4153:             }
 4154:             my $identifier = 'custhelp'.$num;
 4155:             my %full=();
 4156:             my %levels= (
 4157:                          course => {},
 4158:                          domain => {},
 4159:                          system => {},
 4160:                         );
 4161:             my %levelscurrent=(
 4162:                                course => {},
 4163:                                domain => {},
 4164:                                system => {},
 4165:                               );
 4166:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 4167:             my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4168:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4169:             my $chgstr = ' onchange="javascript:reorderHelpRoles(this.form,'."'helproles_".$num."_pos'".');"';
 4170:             $datatable .= '<tr '.$css_class.'><td valign="top"><b>'.$role.'</b><br />'.
 4171:                           '<select name="helproles_'.$num.'_pos"'.$chgstr.'>';
 4172:             for (my $k=0; $k<=$maxnum; $k++) {
 4173:                 my $vpos = $k+1;
 4174:                 my $selstr;
 4175:                 if ($k == $num) {
 4176:                     $selstr = ' selected="selected" ';
 4177:                 }
 4178:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 4179:             }
 4180:             $datatable .= '</select>'.('&nbsp;'x2).
 4181:                           '<input type="hidden" name="helproles_'.$num.'" value="'.$role.'" />'.
 4182:                           '</td>'.
 4183:                           '<td><fieldset><legend>'.&mt('Role name').'</legend>'.
 4184:                           &mt('Name shown to users:').
 4185:                           '<input type="text" name="helproles_'.$num.'_desc" value="'.$desc.'" />'.
 4186:                           '</fieldset>'.
 4187:                           &helpdeskroles_access($dom,$prefix,$num,$add_class,$current{$role},\@accesstypes,
 4188:                                                 $othertitle,$usertypes,$types,\%domhelpdesk).
 4189:                           '<fieldset>'.
 4190:                           '<legend>'.&mt('Role privileges').&adhocbutton($prefix,$num,'privs','show').'</legend>'.
 4191:                           &Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 4192:                                                                    \%levelscurrent,$identifier,
 4193:                                                                    'LC_hidden',$prefix.$num.'_privs').
 4194:                           '</fieldset></td>';
 4195:             $itemcount ++;
 4196:         }
 4197:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4198:         my $newcust = 'custhelp'.$count;
 4199:         my (%privs,%levelscurrent);
 4200:         my %full=();
 4201:         my %levels= (
 4202:                      course => {},
 4203:                      domain => {},
 4204:                      system => {},
 4205:                     );
 4206:         &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 4207:         my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4208:         my $chgstr = ' onchange="javascript:reorderHelpRoles(this.form,'."'helproles_".$count."_pos'".');"';
 4209:         $datatable .= '<tr '.$css_class.'><td valign="top"><span class="LC_nobreak"><label>'.
 4210:                       '<input type="hidden" name="helproles_maxnum" value="'.$maxnum.'" />'."\n".
 4211:                       '<select name="helproles_'.$count.'_pos"'.$chgstr.'>';
 4212:         for (my $k=0; $k<$maxnum+1; $k++) {
 4213:             my $vpos = $k+1;
 4214:             my $selstr;
 4215:             if ($k == $maxnum) {
 4216:                 $selstr = ' selected="selected" ';
 4217:             }
 4218:             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 4219:         }
 4220:         $datatable .= '</select>&nbsp;'."\n".
 4221:                       '<input type="checkbox" name="newcusthelp" value="'.$count.'" />'. &mt('Add').
 4222:                       '</label></span></td>'.
 4223:                       '<td><fieldset><legend>'.&mt('Role name').'</legend>'.
 4224:                       '<span class="LC_nobreak">'.
 4225:                       &mt('Internal name:').
 4226:                       '<input type="text" size="10" name="custhelpname'.$count.'" value="" />'.
 4227:                       '</span>'.('&nbsp;'x4).
 4228:                       '<span class="LC_nobreak">'.
 4229:                       &mt('Name shown to users:').
 4230:                       '<input type="text" size="20" name="helproles_'.$count.'_desc" value="" />'.
 4231:                       '</span></fieldset>'.
 4232:                        &helpdeskroles_access($dom,$prefix,$count,'',undef,\@accesstypes,$othertitle,
 4233:                                              $usertypes,$types,\%domhelpdesk).
 4234:                       '<fieldset><legend>'.&mt('Role privileges').'</legend>'.
 4235:                       &Apache::lonuserutils::custom_role_header($context,$crstype,
 4236:                                                                 \@templateroles,$newcust).
 4237:                       &Apache::lonuserutils::custom_role_table('Course',\%full,\%levels,
 4238:                                                                \%levelscurrent,$newcust).
 4239:                       '</fieldset>'.
 4240:                       &helpsettings_javascript(\@roles_by_num,$maxnum,$hiddenstr,$formname).
 4241:                       '</td></tr>';
 4242:         $count ++;
 4243:         $$rowtotal += $count;
 4244:     }
 4245:     return $datatable;
 4246: }
 4247: 
 4248: sub adhocbutton {
 4249:     my ($prefix,$num,$field,$visibility) = @_;
 4250:     my %lt = &Apache::lonlocal::texthash(
 4251:                                           show => 'Show details',
 4252:                                           hide => 'Hide details',
 4253:                                         );
 4254:     return '<span style="text-decoration:line-through; font-weight: normal;">'.('&nbsp;'x10).
 4255:            '</span>'.('&nbsp;'x2).'<input type="button" id="'.$prefix.$num.'_'.$field.'_vis"'.
 4256:            ' value="'.$lt{$visibility}.'" style="height:20px;" '.
 4257:            'onclick="toggleHelpdeskItem('."'$num','$field'".');" />'.('&nbsp;'x2);
 4258: }
 4259: 
 4260: sub helpsettings_javascript {
 4261:     my ($roles_by_num,$total,$hiddenstr,$formname) = @_;
 4262:     return unless(ref($roles_by_num) eq 'ARRAY');
 4263:     my %html_js_lt = &Apache::lonlocal::texthash(
 4264:                                           show => 'Show details',
 4265:                                           hide => 'Hide details',
 4266:                                         );
 4267:     &html_escape(\%html_js_lt);
 4268:     my $jstext = '    var helproles = Array('."'".join("','",@{$roles_by_num})."'".');'."\n";
 4269:     return <<"ENDSCRIPT";
 4270: <script type="text/javascript">
 4271: // <![CDATA[
 4272: 
 4273: function reorderHelpRoles(form,item) {
 4274:     var changedVal;
 4275: $jstext
 4276:     var newpos = 'helproles_${total}_pos';
 4277:     var maxh = 1 + $total;
 4278:     var current = new Array();
 4279:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 4280:     if (item == newpos) {
 4281:         changedVal = newitemVal;
 4282:     } else {
 4283:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 4284:         current[newitemVal] = newpos;
 4285:     }
 4286:     for (var i=0; i<helproles.length; i++) {
 4287:         var elementName = 'helproles_'+helproles[i]+'_pos';
 4288:         if (elementName != item) {
 4289:             if (form.elements[elementName]) {
 4290:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 4291:                 current[currVal] = elementName;
 4292:             }
 4293:         }
 4294:     }
 4295:     var oldVal;
 4296:     for (var j=0; j<maxh; j++) {
 4297:         if (current[j] == undefined) {
 4298:             oldVal = j;
 4299:         }
 4300:     }
 4301:     if (oldVal < changedVal) {
 4302:         for (var k=oldVal+1; k<=changedVal ; k++) {
 4303:            var elementName = current[k];
 4304:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 4305:         }
 4306:     } else {
 4307:         for (var k=changedVal; k<oldVal; k++) {
 4308:             var elementName = current[k];
 4309:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 4310:         }
 4311:     }
 4312:     return;
 4313: }
 4314: 
 4315: function helpdeskAccess(num) {
 4316:     var curraccess = null;
 4317:     if (document.$formname.elements['helproles_'+num+'_access'].length) {
 4318:         for (var i=0; i<document.$formname.elements['helproles_'+num+'_access'].length; i++) {
 4319:             if (document.$formname.elements['helproles_'+num+'_access'][i].checked) {
 4320:                 curraccess = document.$formname.elements['helproles_'+num+'_access'][i].value;
 4321:             }
 4322:         }
 4323:     }
 4324:     var shown = Array();
 4325:     var hidden = Array();
 4326:     if (curraccess == 'none') {
 4327:         hidden = Array('$hiddenstr');
 4328:     } else {
 4329:         if (curraccess == 'status') {
 4330:             shown = Array('bystatus');
 4331:             hidden = Array('notinc','notexc');
 4332:         } else {
 4333:             if (curraccess == 'exc') {
 4334:                 shown = Array('notexc');
 4335:                 hidden = Array('notinc','bystatus');
 4336:             }
 4337:             if (curraccess == 'inc') {
 4338:                 shown = Array('notinc');
 4339:                 hidden = Array('notexc','bystatus');
 4340:             }
 4341:             if ((curraccess == 'all') || (curraccess == 'dh') || (curraccess == 'da')) {
 4342:                 hidden = Array('notinc','notexc','bystatus');
 4343:             }
 4344:         }
 4345:     }
 4346:     if (hidden.length > 0) {
 4347:         for (var i=0; i<hidden.length; i++) {
 4348:             if (document.getElementById('helproles_'+num+'_'+hidden[i])) {
 4349:                 document.getElementById('helproles_'+num+'_'+hidden[i]).style.display = 'none';
 4350:             }
 4351:         }
 4352:     }
 4353:     if (shown.length > 0) {
 4354:         for (var i=0; i<shown.length; i++) {
 4355:             if (document.getElementById('helproles_'+num+'_'+shown[i])) {
 4356:                 if (shown[i] == 'privs') {
 4357:                     document.getElementById('helproles_'+num+'_'+shown[i]).style.display = 'block';
 4358:                 } else {
 4359:                     document.getElementById('helproles_'+num+'_'+shown[i]).style.display = 'inline-block';
 4360:                 }
 4361:             }
 4362:         }
 4363:     }
 4364:     return;
 4365: }
 4366: 
 4367: function toggleHelpdeskItem(num,field) {
 4368:     if (document.getElementById('helproles_'+num+'_'+field)) {
 4369:         if (document.getElementById('helproles_'+num+'_'+field).className.match(/(?:^|\\s)LC_hidden(?!\\S)/)) {
 4370:             document.getElementById('helproles_'+num+'_'+field).className =
 4371:                 document.getElementById('helproles_'+num+'_'+field).className.replace(/(?:^|\\s)LC_hidden(?!\\S)/g ,'');
 4372:             if (document.getElementById('helproles_'+num+'_'+field+'_vis')) {
 4373:                 document.getElementById('helproles_'+num+'_'+field+'_vis').value = '$html_js_lt{hide}';
 4374:             }
 4375:         } else {
 4376:             document.getElementById('helproles_'+num+'_'+field).className += ' LC_hidden';
 4377:             if (document.getElementById('helproles_'+num+'_'+field+'_vis')) {
 4378:                 document.getElementById('helproles_'+num+'_'+field+'_vis').value = '$html_js_lt{show}';
 4379:             }
 4380:         }
 4381:     }
 4382:     return;
 4383: }
 4384: 
 4385: // ]]>
 4386: </script>
 4387: 
 4388: ENDSCRIPT
 4389: }
 4390: 
 4391: sub helpdeskroles_access {
 4392:     my ($dom,$prefix,$num,$add_class,$current,$accesstypes,$othertitle,
 4393:         $usertypes,$types,$domhelpdesk) = @_;
 4394:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($domhelpdesk) eq 'HASH'));
 4395:     my %lt = &Apache::lonlocal::texthash(
 4396:                     'rou'    => 'Role usage',
 4397:                     'whi'    => 'Which helpdesk personnel may use this role?',
 4398:                     'all'    => 'All with domain helpdesk or helpdesk assistant role',
 4399:                     'dh'     => 'All with domain helpdesk role',
 4400:                     'da'     => 'All with domain helpdesk assistant role',
 4401:                     'none'   => 'None',
 4402:                     'status' => 'Determined based on institutional status',
 4403:                     'inc'    => 'Include all, but exclude specific personnel',
 4404:                     'exc'    => 'Exclude all, but include specific personnel',
 4405:                   );
 4406:     my %usecheck = (
 4407:                      all => ' checked="checked"',
 4408:                    );
 4409:     my %displaydiv = (
 4410:                       status => 'none',
 4411:                       inc    => 'none',
 4412:                       exc    => 'none',
 4413:                       priv   => 'block',
 4414:                      );
 4415:     my $output;
 4416:     if (ref($current) eq 'HASH') {
 4417:         if (($current->{'access'} ne '') && ($current->{'access'} ne 'all')) {
 4418:             if (grep(/^\Q$current->{access}\E$/,@{$accesstypes})) {
 4419:                 $usecheck{$current->{access}} = $usecheck{'all'};
 4420:                 delete($usecheck{'all'});
 4421:                 if ($current->{access} =~ /^(status|inc|exc)$/) {
 4422:                     my $access = $1;
 4423:                     $displaydiv{$access} = 'inline';
 4424:                 } elsif ($current->{access} eq 'none') {
 4425:                     $displaydiv{'priv'} = 'none';
 4426:                 }
 4427:             }
 4428:         }
 4429:     }
 4430:     $output = '<fieldset id="'.$prefix.$num.'_usage"><legend>'.$lt{'rou'}.'</legend>'.
 4431:               '<p>'.$lt{'whi'}.'</p>';
 4432:     foreach my $access (@{$accesstypes}) {
 4433:         $output .= '<p><label><input type="radio" name="'.$prefix.$num.'_access" value="'.$access.'" '.$usecheck{$access}.
 4434:                    ' onclick="helpdeskAccess('."'$num'".');" />'.
 4435:                    $lt{$access}.'</label>';
 4436:         if ($access eq 'status') {
 4437:             $output .= '<div id="'.$prefix.$num.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 4438:                        &Apache::lonuserutils::adhoc_status_types($dom,$prefix,$num,$current->{$access},
 4439:                                                                  $othertitle,$usertypes,$types).
 4440:                        '</div>';
 4441:         } elsif (($access eq 'inc') && (keys(%{$domhelpdesk}) > 0)) {
 4442:             $output .= '<div id="'.$prefix.$num.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 4443:                        &Apache::lonuserutils::adhoc_staff($access,$prefix,$num,$current->{$access},$domhelpdesk).
 4444:                        '</div>';
 4445:         } elsif (($access eq 'exc') && (keys(%{$domhelpdesk}) > 0)) {
 4446:             $output .= '<div id="'.$prefix.$num.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 4447:                        &Apache::lonuserutils::adhoc_staff($access,$prefix,$num,$current->{$access},$domhelpdesk).
 4448:                        '</div>';
 4449:         }
 4450:         $output .= '</p>';
 4451:     }
 4452:     $output .= '</fieldset>';
 4453:     return $output;
 4454: }
 4455: 
 4456: sub radiobutton_prefs {
 4457:     my ($settings,$toggles,$defaultchecked,$choices,$itemcount,$onclick,
 4458:         $additional,$align,$firstval) = @_;
 4459:     return unless ((ref($toggles) eq 'ARRAY') && (ref($defaultchecked) eq 'HASH') &&
 4460:                    (ref($choices) eq 'HASH'));
 4461: 
 4462:     my (%checkedon,%checkedoff,$datatable,$css_class);
 4463: 
 4464:     foreach my $item (@{$toggles}) {
 4465:         if ($defaultchecked->{$item} eq 'on') {
 4466:             $checkedon{$item} = ' checked="checked" ';
 4467:             $checkedoff{$item} = ' ';
 4468:         } elsif ($defaultchecked->{$item} eq 'off') {
 4469:             $checkedoff{$item} = ' checked="checked" ';
 4470:             $checkedon{$item} = ' ';
 4471:         }
 4472:     }
 4473:     if (ref($settings) eq 'HASH') {
 4474:         foreach my $item (@{$toggles}) {
 4475:             if ($settings->{$item} eq '1') {
 4476:                 $checkedon{$item} =  ' checked="checked" ';
 4477:                 $checkedoff{$item} = ' ';
 4478:             } elsif ($settings->{$item} eq '0') {
 4479:                 $checkedoff{$item} =  ' checked="checked" ';
 4480:                 $checkedon{$item} = ' ';
 4481:             }
 4482:         }
 4483:     }
 4484:     if ($onclick) {
 4485:         $onclick = ' onclick="'.$onclick.'"';
 4486:     }
 4487:     foreach my $item (@{$toggles}) {
 4488:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4489:         $datatable .=
 4490:             '<tr'.$css_class.'><td valign="top">'.
 4491:             '<span class="LC_nobreak">'.$choices->{$item}.
 4492:             '</span></td>';
 4493:         if ($align eq 'left') {
 4494:             $datatable .= '<td class="LC_left_item">';
 4495:         } else {
 4496:             $datatable .= '<td class="LC_right_item">';
 4497:         }
 4498:         $datatable .= '<span class="LC_nobreak">';
 4499:         if ($firstval eq 'no') {
 4500:             $datatable .=
 4501:                 '<label><input type="radio" name="'.
 4502:                 $item.'" '.$checkedoff{$item}.' value="0"'.$onclick.' />'.&mt('No').
 4503:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'" '.
 4504:                 $checkedon{$item}.' value="1"'.$onclick.' />'.&mt('Yes').'</label>';
 4505:         } else {
 4506:             $datatable .=
 4507:             '<label><input type="radio" name="'.
 4508:             $item.'" '.$checkedon{$item}.' value="1"'.$onclick.' />'.&mt('Yes').
 4509:             '</label>&nbsp;<label><input type="radio" name="'.$item.'" '.
 4510:             $checkedoff{$item}.' value="0"'.$onclick.' />'.&mt('No').'</label>';
 4511:         }
 4512:         $datatable .= '</span>'.$additional.'</td></tr>';
 4513:         $itemcount ++;
 4514:     }
 4515:     return ($datatable,$itemcount);
 4516: }
 4517: 
 4518: sub print_coursedefaults {
 4519:     my ($position,$dom,$settings,$rowtotal) = @_;
 4520:     my ($css_class,$datatable,%checkedon,%checkedoff,%defaultchecked,@toggles);
 4521:     my $itemcount = 1;
 4522:     my %choices =  &Apache::lonlocal::texthash (
 4523:         uploadquota          => 'Default quota for files uploaded directly to course/community using Course Editor (MB)',
 4524:         anonsurvey_threshold => 'Responder count needed before showing submissions for anonymous surveys',
 4525:         coursecredits        => 'Credits can be specified for courses',
 4526:         uselcmath            => 'Math preview uses LON-CAPA previewer (javascript) in place of DragMath (Java)',
 4527:         usejsme              => 'Molecule editor uses JSME (HTML5) in place of JME (Java)',
 4528:         inline_chem          => 'Use inline previewer for chemical reaction response in place of pop-up',
 4529:         texengine            => 'Default method to display mathematics',
 4530:         postsubmit           => 'Disable submit button/keypress following student submission',
 4531:         canclone             => "People who may clone a course (besides course's owner and coordinators)",
 4532:         mysqltables          => 'Lifetime (s) of "Temporary" MySQL tables (student performance data) on homeserver',
 4533:     );
 4534:     my %staticdefaults = (
 4535:                            anonsurvey_threshold => 10,
 4536:                            uploadquota          => 500,
 4537:                            postsubmit           => 60,
 4538:                            mysqltables          => 172800,
 4539:                          );
 4540:     if ($position eq 'top') {
 4541:         %defaultchecked = (
 4542:                             'uselcmath'       => 'on',
 4543:                             'usejsme'         => 'on',
 4544:                             'inline_chem'     => 'on',
 4545:                             'canclone'        => 'none',
 4546:                           );
 4547:         @toggles = ('uselcmath','usejsme','inline_chem');
 4548:         my $deftex = $Apache::lonnet::deftex;
 4549:         if (ref($settings) eq 'HASH') {
 4550:             if ($settings->{'texengine'}) {
 4551:                 if ($settings->{'texengine'} =~ /^(MathJax|mimetex|tth)$/) {
 4552:                     $deftex = $settings->{'texengine'};
 4553:                 }
 4554:             }
 4555:         }
 4556:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4557:         my $mathdisp = '<tr'.$css_class.'><td style="vertical-align: top">'.
 4558:                        '<span class="LC_nobreak">'.$choices{'texengine'}.
 4559:                        '</span></td><td class="LC_right_item">'.
 4560:                        '<select name="texengine">'."\n";
 4561:         my %texoptions = (
 4562:                             MathJax  => 'MathJax',
 4563:                             mimetex  => &mt('Convert to Images'),
 4564:                             tth      => &mt('TeX to HTML'),
 4565:                          );
 4566:         foreach my $renderer ('MathJax','mimetex','tth') {
 4567:             my $selected = '';
 4568:             if ($renderer eq $deftex) {
 4569:                 $selected = ' selected="selected"';
 4570:             }
 4571:             $mathdisp .= '<option value="'.$renderer.'"'.$selected.'>'.$texoptions{$renderer}.'</option>'."\n";
 4572:         }
 4573:         $mathdisp .= '</select></td></tr>'."\n";
 4574:         $itemcount ++;
 4575:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 4576:                                                      \%choices,$itemcount);
 4577:         $datatable = $mathdisp.$datatable;
 4578:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4579:         $datatable .=
 4580:             '<tr'.$css_class.'><td valign="top">'.
 4581:             '<span class="LC_nobreak">'.$choices{'canclone'}.
 4582:             '</span></td><td class="LC_left_item">';
 4583:         my $currcanclone = 'none';
 4584:         my $onclick;
 4585:         my @cloneoptions = ('none','domain');
 4586:         my %clonetitles = &Apache::lonlocal::texthash (
 4587:                              none     => 'No additional course requesters',
 4588:                              domain   => "Any course requester in course's domain",
 4589:                              instcode => 'Course requests for official courses ...',
 4590:                           );
 4591:         my (%codedefaults,@code_order,@posscodes);
 4592:         if (&Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
 4593:                                                     \@code_order) eq 'ok') {
 4594:             if (@code_order > 0) {
 4595:                 push(@cloneoptions,'instcode');
 4596:                 $onclick = ' onclick="toggleDisplay(this.form,'."'cloneinstcode'".');"';
 4597:             }
 4598:         }
 4599:         if (ref($settings) eq 'HASH') {
 4600:             if ($settings->{'canclone'}) {
 4601:                 if (ref($settings->{'canclone'}) eq 'HASH') {
 4602:                     if (ref($settings->{'canclone'}{'instcode'}) eq 'ARRAY') {
 4603:                         if (@code_order > 0) {
 4604:                             $currcanclone = 'instcode';
 4605:                             @posscodes = @{$settings->{'canclone'}{'instcode'}};
 4606:                         }
 4607:                     }
 4608:                 } elsif ($settings->{'canclone'} eq 'domain') {
 4609:                     $currcanclone = $settings->{'canclone'};
 4610:                 }
 4611:             }
 4612:         }
 4613:         foreach my $option (@cloneoptions) {
 4614:             my ($checked,$additional);
 4615:             if ($currcanclone eq $option) {
 4616:                 $checked = ' checked="checked"';
 4617:             }
 4618:             if ($option eq 'instcode') {
 4619:                 if (@code_order) {
 4620:                     my $show = 'none';
 4621:                     if ($checked) {
 4622:                         $show = 'block';
 4623:                     }
 4624:                     $additional = '<div id="cloneinstcode" style="display:'.$show.'" />'.
 4625:                                   &mt('Institutional codes for new and cloned course have identical:').
 4626:                                   '<br />';
 4627:                     foreach my $item (@code_order) {
 4628:                         my $codechk;
 4629:                         if ($checked) {
 4630:                             if (grep(/^\Q$item\E$/,@posscodes)) {
 4631:                                 $codechk = ' checked="checked"';
 4632:                             }
 4633:                         }
 4634:                         $additional .= '<label>'.
 4635:                                        '<input type="checkbox" name="clonecode" value="'.$item.'"'.$codechk.' />'.
 4636:                                        $item.'</label>';
 4637:                     }
 4638:                     $additional .= ('&nbsp;'x2).'('.&mt('check as many as needed').')</div>';
 4639:                 }
 4640:             }
 4641:             $datatable .=
 4642:                 '<span class="LC_nobreak"><label><input type="radio" name="canclone"'.$checked.
 4643:                 ' value="'.$option.'"'.$onclick.' />'.$clonetitles{$option}.
 4644:                 '</label>&nbsp;'.$additional.'</span><br />';
 4645:         }
 4646:         $datatable .= '</td>'.
 4647:                       '</tr>';
 4648:         $itemcount ++;
 4649:     } else {
 4650:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 4651:         my ($currdefresponder,%defcredits,%curruploadquota,%deftimeout,%currmysql);
 4652:         my $currusecredits = 0;
 4653:         my $postsubmitclient = 1;
 4654:         my @types = ('official','unofficial','community','textbook');
 4655:         if (ref($settings) eq 'HASH') {
 4656:             $currdefresponder = $settings->{'anonsurvey_threshold'};
 4657:             if (ref($settings->{'uploadquota'}) eq 'HASH') {
 4658:                 foreach my $type (keys(%{$settings->{'uploadquota'}})) {
 4659:                     $curruploadquota{$type} = $settings->{'uploadquota'}{$type};
 4660:                 }
 4661:             }
 4662:             if (ref($settings->{'coursecredits'}) eq 'HASH') {
 4663:                 foreach my $type (@types) {
 4664:                     next if ($type eq 'community');
 4665:                     $defcredits{$type} = $settings->{'coursecredits'}->{$type};
 4666:                     if ($defcredits{$type} ne '') {
 4667:                         $currusecredits = 1;
 4668:                     }
 4669:                 }
 4670:             }
 4671:             if (ref($settings->{'postsubmit'}) eq 'HASH') {
 4672:                 if ($settings->{'postsubmit'}->{'client'} eq 'off') {
 4673:                     $postsubmitclient = 0;
 4674:                     foreach my $type (@types) {
 4675:                         $deftimeout{$type} = $staticdefaults{'postsubmit'};
 4676:                     }
 4677:                 } else {
 4678:                     foreach my $type (@types) {
 4679:                         if (ref($settings->{'postsubmit'}->{'timeout'}) eq 'HASH') {
 4680:                             if ($settings->{'postsubmit'}->{'timeout'}->{$type} =~ /^\d+$/) {
 4681:                                 $deftimeout{$type} = $settings->{'postsubmit'}->{'timeout'}->{$type};
 4682:                             } else {
 4683:                                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 4684:                             }
 4685:                         } else {
 4686:                             $deftimeout{$type} = $staticdefaults{'postsubmit'};
 4687:                         }
 4688:                     }
 4689:                 }
 4690:             } else {
 4691:                 foreach my $type (@types) {
 4692:                     $deftimeout{$type} = $staticdefaults{'postsubmit'};
 4693:                 }
 4694:             }
 4695:             if (ref($settings->{'mysqltables'}) eq 'HASH') {
 4696:                 foreach my $type (keys(%{$settings->{'mysqltables'}})) {
 4697:                     $currmysql{$type} = $settings->{'mysqltables'}{$type};
 4698:                 }
 4699:             } else {
 4700:                 foreach my $type (@types) {
 4701:                     $currmysql{$type} = $staticdefaults{'mysqltables'};
 4702:                 }
 4703:             }
 4704:         } else {
 4705:             foreach my $type (@types) {
 4706:                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 4707:             }
 4708:         }
 4709:         if (!$currdefresponder) {
 4710:             $currdefresponder = $staticdefaults{'anonsurvey_threshold'};
 4711:         } elsif ($currdefresponder < 1) {
 4712:             $currdefresponder = 1;
 4713:         }
 4714:         foreach my $type (@types) {
 4715:             if ($curruploadquota{$type} eq '') {
 4716:                 $curruploadquota{$type} = $staticdefaults{'uploadquota'};
 4717:             }
 4718:         }
 4719:         $datatable .=
 4720:                 '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 4721:                 $choices{'anonsurvey_threshold'}.
 4722:                 '</span></td>'.
 4723:                 '<td class="LC_right_item"><span class="LC_nobreak">'.
 4724:                 '<input type="text" name="anonsurvey_threshold"'.
 4725:                 ' value="'.$currdefresponder.'" size="5" /></span>'.
 4726:                 '</td></tr>'."\n";
 4727:         $itemcount ++;
 4728:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 4729:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 4730:                       $choices{'uploadquota'}.
 4731:                       '</span></td>'.
 4732:                       '<td align="right" class="LC_right_item">'.
 4733:                       '<table><tr>';
 4734:         foreach my $type (@types) {
 4735:             $datatable .= '<td align="center">'.&mt($type).'<br />'.
 4736:                            '<input type="text" name="uploadquota_'.$type.'"'.
 4737:                            ' value="'.$curruploadquota{$type}.'" size="5" /></td>';
 4738:         }
 4739:         $datatable .= '</tr></table></td></tr>'."\n";
 4740:         $itemcount ++;
 4741:         my $onclick = "toggleDisplay(this.form,'credits');";
 4742:         my $display = 'none';
 4743:         if ($currusecredits) {
 4744:             $display = 'block';
 4745:         }
 4746:         my $additional = '<div id="credits" style="display: '.$display.'">'.
 4747:                          '<i>'.&mt('Default credits').'</i><br /><table><tr>';
 4748:         foreach my $type (@types) {
 4749:             next if ($type eq 'community');
 4750:             $additional .= '<td align="center">'.&mt($type).'<br />'.
 4751:                            '<input type="text" name="'.$type.'_credits"'.
 4752:                            ' value="'.$defcredits{$type}.'" size="3" /></td>';
 4753:         }
 4754:         $additional .= '</tr></table></div>'."\n";
 4755:         %defaultchecked = ('coursecredits' => 'off');
 4756:         @toggles = ('coursecredits');
 4757:         my $current = {
 4758:                         'coursecredits' => $currusecredits,
 4759:                       };
 4760:         (my $table,$itemcount) =
 4761:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 4762:                                \%choices,$itemcount,$onclick,$additional,'left');
 4763:         $datatable .= $table;
 4764:         $onclick = "toggleDisplay(this.form,'studentsubmission');";
 4765:         my $display = 'none';
 4766:         if ($postsubmitclient) {
 4767:             $display = 'block';
 4768:         }
 4769:         $additional = '<div id="studentsubmission" style="display: '.$display.'">'.
 4770:                       &mt('Number of seconds submit is disabled').'<br />'.
 4771:                       '<i>'.&mt('Enter 0 to remain disabled until page reload.').'</i><br />'.
 4772:                       '<table><tr>';
 4773:         foreach my $type (@types) {
 4774:             $additional .= '<td align="center">'.&mt($type).'<br />'.
 4775:                            '<input type="text" name="'.$type.'_timeout" value="'.
 4776:                            $deftimeout{$type}.'" size="5" /></td>';
 4777:         }
 4778:         $additional .= '</tr></table></div>'."\n";
 4779:         %defaultchecked = ('postsubmit' => 'on');
 4780:         @toggles = ('postsubmit');
 4781:         $current = {
 4782:                        'postsubmit' => $postsubmitclient,
 4783:                    };
 4784:         ($table,$itemcount) =
 4785:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 4786:                                \%choices,$itemcount,$onclick,$additional,'left');
 4787:         $datatable .= $table;
 4788:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 4789:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 4790:                       $choices{'mysqltables'}.
 4791:                       '</span></td>'.
 4792:                       '<td align="right" class="LC_right_item">'.
 4793:                       '<table><tr>';
 4794:         foreach my $type (@types) {
 4795:             $datatable .= '<td align="center">'.&mt($type).'<br />'.
 4796:                            '<input type="text" name="mysqltables_'.$type.'"'.
 4797:                            ' value="'.$currmysql{$type}.'" size="8" /></td>';
 4798:         }
 4799:         $datatable .= '</tr></table></td></tr>'."\n";
 4800:         $itemcount ++;
 4801: 
 4802:     }
 4803:     $$rowtotal += $itemcount;
 4804:     return $datatable;
 4805: }
 4806: 
 4807: sub print_selfenrollment {
 4808:     my ($position,$dom,$settings,$rowtotal) = @_;
 4809:     my ($css_class,$datatable);
 4810:     my $itemcount = 1;
 4811:     my @types = ('official','unofficial','community','textbook');
 4812:     if (($position eq 'top') || ($position eq 'middle')) {
 4813:         my ($rowsref,$titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
 4814:         my %descs = &Apache::lonuserutils::selfenroll_default_descs();
 4815:         my @rows;
 4816:         my $key;
 4817:         if ($position eq 'top') {
 4818:             $key = 'admin'; 
 4819:             if (ref($rowsref) eq 'ARRAY') {
 4820:                 @rows = @{$rowsref};
 4821:             }
 4822:         } elsif ($position eq 'middle') {
 4823:             $key = 'default';
 4824:             @rows = ('types','registered','approval','limit');
 4825:         }
 4826:         foreach my $row (@rows) {
 4827:             if (defined($titlesref->{$row})) {
 4828:                 $itemcount ++;
 4829:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4830:                 $datatable .= '<tr'.$css_class.'>'.
 4831:                               '<td>'.$titlesref->{$row}.'</td>'.
 4832:                               '<td class="LC_left_item">'.
 4833:                               '<table><tr>';
 4834:                 my (%current,%currentcap);
 4835:                 if (ref($settings) eq 'HASH') {
 4836:                     if (ref($settings->{$key}) eq 'HASH') {
 4837:                         foreach my $type (@types) {
 4838:                             if (ref($settings->{$key}->{$type}) eq 'HASH') {
 4839:                                 $current{$type} = $settings->{$key}->{$type}->{$row};
 4840:                             }
 4841:                             if (($row eq 'limit') && ($key eq 'default')) {
 4842:                                 if (ref($settings->{$key}->{$type}) eq 'HASH') {
 4843:                                     $currentcap{$type} = $settings->{$key}->{$type}->{'cap'};
 4844:                                 }
 4845:                             }
 4846:                         }
 4847:                     }
 4848:                 }
 4849:                 my %roles = (
 4850:                              '0' => &Apache::lonnet::plaintext('dc'),
 4851:                             ); 
 4852:             
 4853:                 foreach my $type (@types) {
 4854:                     unless (($row eq 'registered') && ($key eq 'default')) {
 4855:                         $datatable .= '<th>'.&mt($type).'</th>';
 4856:                     }
 4857:                 }
 4858:                 unless (($row eq 'registered') && ($key eq 'default')) {
 4859:                     $datatable .= '</tr><tr>';
 4860:                 }
 4861:                 foreach my $type (@types) {
 4862:                     if ($type eq 'community') {
 4863:                         $roles{'1'} = &mt('Community personnel');
 4864:                     } else {
 4865:                         $roles{'1'} = &mt('Course personnel');
 4866:                     }
 4867:                     $datatable .= '<td style="vertical-align: top">';
 4868:                     if ($position eq 'top') {
 4869:                         my %checked;
 4870:                         if ($current{$type} eq '0') {
 4871:                             $checked{'0'} = ' checked="checked"';
 4872:                         } else {
 4873:                             $checked{'1'} = ' checked="checked"';
 4874:                         }
 4875:                         foreach my $role ('1','0') {
 4876:                             $datatable .= '<span class="LC_nobreak"><label>'.
 4877:                                           '<input type="radio" name="selfenrolladmin_'.$row.'_'.$type.'" '.
 4878:                                           'value="'.$role.'"'.$checked{$role}.' />'.
 4879:                                           $roles{$role}.'</label></span> ';
 4880:                         }
 4881:                     } else {
 4882:                         if ($row eq 'types') {
 4883:                             my %checked;
 4884:                             if ($current{$type} =~ /^(all|dom)$/) {
 4885:                                 $checked{$1} = ' checked="checked"';
 4886:                             } else {
 4887:                                 $checked{''} = ' checked="checked"';
 4888:                             }
 4889:                             foreach my $val ('','dom','all') {
 4890:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 4891:                                               '<input type ="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 4892:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 4893:                             }
 4894:                         } elsif ($row eq 'registered') {
 4895:                             my %checked;
 4896:                             if ($current{$type} eq '1') {
 4897:                                 $checked{'1'} = ' checked="checked"';
 4898:                             } else {
 4899:                                 $checked{'0'} = ' checked="checked"';
 4900:                             }
 4901:                             foreach my $val ('0','1') {
 4902:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 4903:                                               '<input type ="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 4904:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 4905:                             }
 4906:                         } elsif ($row eq 'approval') {
 4907:                             my %checked;
 4908:                             if ($current{$type} =~ /^([12])$/) {
 4909:                                 $checked{$1} = ' checked="checked"';
 4910:                             } else {
 4911:                                 $checked{'0'} = ' checked="checked"';
 4912:                             }
 4913:                             for my $val (0..2) {
 4914:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 4915:                                               '<input type="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 4916:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 4917:                             }
 4918:                         } elsif ($row eq 'limit') {
 4919:                             my %checked;
 4920:                             if ($current{$type} =~ /^(allstudents|selfenrolled)$/) {
 4921:                                 $checked{$1} = ' checked="checked"';
 4922:                             } else {
 4923:                                 $checked{'none'} = ' checked="checked"';
 4924:                             }
 4925:                             my $cap;
 4926:                             if ($currentcap{$type} =~ /^\d+$/) {
 4927:                                 $cap = $currentcap{$type};
 4928:                             }
 4929:                             foreach my $val ('none','allstudents','selfenrolled') {
 4930:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 4931:                                               '<input type="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 4932:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 4933:                             }
 4934:                             $datatable .= '<br />'.
 4935:                                           '<span class="LC_nobreak">'.&mt('Maximum allowed: ').
 4936:                                           '<input type="text" name="selfenrolldefault_cap_'.$type.'" size = "5" value="'.$cap.'" />'.
 4937:                                           '</span>'; 
 4938:                         }
 4939:                     }
 4940:                     $datatable .= '</td>';
 4941:                 }
 4942:                 $datatable .= '</tr>';
 4943:             }
 4944:             $datatable .= '</table></td></tr>';
 4945:         }
 4946:     } elsif ($position eq 'bottom') {
 4947:         $datatable .= &print_validation_rows('selfenroll',$dom,$settings,\$itemcount);
 4948:     }
 4949:     $$rowtotal += $itemcount;
 4950:     return $datatable;
 4951: }
 4952: 
 4953: sub print_validation_rows {
 4954:     my ($caller,$dom,$settings,$rowtotal) = @_;
 4955:     my ($itemsref,$namesref,$fieldsref);
 4956:     if ($caller eq 'selfenroll') { 
 4957:         ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
 4958:     } elsif ($caller eq 'requestcourses') {
 4959:         ($itemsref,$namesref,$fieldsref) = &Apache::loncoursequeueadmin::requestcourses_validation_types();
 4960:     }
 4961:     my %currvalidation;
 4962:     if (ref($settings) eq 'HASH') {
 4963:         if (ref($settings->{'validation'}) eq 'HASH') {
 4964:             %currvalidation = %{$settings->{'validation'}};
 4965:         }
 4966:     }
 4967:     my $datatable;
 4968:     my $itemcount = 0;
 4969:     foreach my $item (@{$itemsref}) {
 4970:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 4971:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 4972:                       $namesref->{$item}.
 4973:                       '</span></td>'.
 4974:                       '<td class="LC_left_item">';
 4975:         if (($item eq 'url') || ($item eq 'button')) {
 4976:             $datatable .= '<span class="LC_nobreak">'.
 4977:                           '<input type="text" name="'.$caller.'_validation_'.$item.'"'.
 4978:                           ' value="'.$currvalidation{$item}.'" size="50" /></span>';
 4979:         } elsif ($item eq 'fields') {
 4980:             my @currfields;
 4981:             if (ref($currvalidation{$item}) eq 'ARRAY') {
 4982:                 @currfields = @{$currvalidation{$item}};
 4983:             }
 4984:             foreach my $field (@{$fieldsref}) {
 4985:                 my $check = '';
 4986:                 if (grep(/^\Q$field\E$/,@currfields)) {
 4987:                     $check = ' checked="checked"';
 4988:                 }
 4989:                 $datatable .= '<span class="LC_nobreak"><label>'.
 4990:                               '<input type="checkbox" name="'.$caller.'_validation_fields"'.
 4991:                               ' value="'.$field.'"'.$check.' />'.$field.
 4992:                               '</label></span> ';
 4993:             }
 4994:         } elsif ($item eq 'markup') {
 4995:             $datatable .= '<textarea name="'.$caller.'_validation_markup" cols="50" rows="5">'.
 4996:                            $currvalidation{$item}.
 4997:                               '</textarea>';
 4998:         }
 4999:         $datatable .= '</td></tr>'."\n";
 5000:         if (ref($rowtotal)) {
 5001:             $itemcount ++;
 5002:         }
 5003:     }
 5004:     if ($caller eq 'requestcourses') {
 5005:         my %currhash;
 5006:         if (ref($settings) eq 'HASH') {
 5007:             if (ref($settings->{'validation'}) eq 'HASH') {
 5008:                 if ($settings->{'validation'}{'dc'} ne '') {
 5009:                     $currhash{$settings->{'validation'}{'dc'}} = 1;
 5010:                 }
 5011:             }
 5012:         }
 5013:         my $numinrow = 2;
 5014:         my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 5015:                                                        'validationdc',%currhash);
 5016:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 5017:         $datatable .= '<tr'.$css_class.'><td>';
 5018:         if ($numdc > 1) {
 5019:             $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)');
 5020:         } else {
 5021:             $datatable .=  &mt('Course creation processed as: ');
 5022:         }
 5023:         $datatable .= '</td><td class="LC_left_item">'.$dctable.'</td></tr>';
 5024:         $itemcount ++;
 5025:     }
 5026:     if (ref($rowtotal)) {
 5027:         $$rowtotal += $itemcount;
 5028:     }
 5029:     return $datatable;
 5030: }
 5031: 
 5032: sub print_passwords {
 5033:     my ($position,$dom,$confname,$settings,$rowtotal) = @_;
 5034:     my ($datatable,$css_class);
 5035:     my $itemcount = 0;
 5036:     my %titles = &Apache::lonlocal::texthash (
 5037:         captcha        => '"Forgot Password" CAPTCHA validation',
 5038:         link           => 'Reset link expiration (hours)',
 5039:         case           => 'Case-sensitive usernames/e-mail',
 5040:         prelink        => 'Information required (form 1)',
 5041:         postlink       => 'Information required (form 2)',
 5042:         emailsrc       => 'LON-CAPA e-mail address type(s)',
 5043:         customtext     => 'Domain specific text (HTML)',
 5044:         intauth_cost   => 'Encryption cost for bcrypt (positive integer)',
 5045:         intauth_check  => 'Check bcrypt cost if authenticated',
 5046:         intauth_switch => 'Existing crypt-based switched to bcrypt on authentication',
 5047:         permanent      => 'Permanent e-mail address',
 5048:         critical       => 'Critical notification address',
 5049:         notify         => 'Notification address',
 5050:         min            => 'Minimum password length',
 5051:         max            => 'Maximum password length',
 5052:         chars          => 'Required characters',
 5053:         numsaved       => 'Number of previous passwords to save and disallow reuse',
 5054:     );
 5055:     if ($position eq 'top') {
 5056:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 5057:         my $shownlinklife = 2;
 5058:         my $prelink = 'both';
 5059:         my (%casesens,%postlink,%emailsrc,$nostdtext,$customurl);
 5060:         if (ref($settings) eq 'HASH') {
 5061:             if ($settings->{resetlink} =~ /^\d+(|\.\d*)$/) {
 5062:                 $shownlinklife = $settings->{resetlink};
 5063:             }
 5064:             if (ref($settings->{resetcase}) eq 'ARRAY') {
 5065:                 map { $casesens{$_} = 1; } (@{$settings->{resetcase}});
 5066:             }
 5067:             if ($settings->{resetprelink} =~ /^(both|either)$/) {
 5068:                 $prelink = $settings->{resetprelink};
 5069:             }
 5070:             if (ref($settings->{resetpostlink}) eq 'HASH') {
 5071:                 %postlink = %{$settings->{resetpostlink}};
 5072:             }
 5073:             if (ref($settings->{resetemail}) eq 'ARRAY') {
 5074:                 map { $emailsrc{$_} = 1; } (@{$settings->{resetemail}});
 5075:             }
 5076:             if ($settings->{resetremove}) {
 5077:                 $nostdtext = 1;
 5078:             }
 5079:             if ($settings->{resetcustom}) {
 5080:                 $customurl = $settings->{resetcustom};
 5081:             }
 5082:         } else {
 5083:             if (ref($types) eq 'ARRAY') {
 5084:                 foreach my $item (@{$types}) {
 5085:                     $casesens{$item} = 1;
 5086:                     $postlink{$item} = ['username','email'];
 5087:                 }
 5088:             }
 5089:             $casesens{'default'} = 1;
 5090:             $postlink{'default'} = ['username','email'];
 5091:             $prelink = 'both';
 5092:             %emailsrc = (
 5093:                           permanent => 1,
 5094:                           critical  => 1,
 5095:                           notify    => 1,
 5096:             );
 5097:         }
 5098:         $datatable = &captcha_choice('passwords',$settings,$$rowtotal);
 5099:         $itemcount ++;
 5100:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5101:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'link'}.'</td>'.
 5102:                       '<td class="LC_left_item">'.
 5103:                       '<input type="textbox" value="'.$shownlinklife.'" '.
 5104:                       'name="passwords_link" size="3" /></td></tr>';
 5105:         $itemcount ++;
 5106:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5107:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'case'}.'</td>'.
 5108:                       '<td class="LC_left_item">';
 5109:         if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 5110:             foreach my $item (@{$types}) {
 5111:                 my $checkedcase;
 5112:                 if ($casesens{$item}) {
 5113:                     $checkedcase = ' checked="checked"';
 5114:                 }
 5115:                 $datatable .= '<span class="LC_nobreak"><label>'.
 5116:                               '<input type="checkbox" name="passwords_case_sensitive" value="'.
 5117:                               $item.'"'.$checkedcase.' />'.$usertypes->{$item}.'</label>'.
 5118:                               '</span>&nbsp;&nbsp; ';
 5119:             }
 5120:         }
 5121:         my $checkedcase;
 5122:         if ($casesens{'default'}) {
 5123:             $checkedcase = ' checked="checked"';
 5124:         }
 5125:         $datatable .= '<span class="LC_nobreak"><label><input type="checkbox" '.
 5126:                       'name="passwords_case_sensitive" value="default"'.$checkedcase.' />'.
 5127:                       $othertitle.'</label></span></td>';
 5128:         $itemcount ++;
 5129:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5130:         my %checkedpre = (
 5131:                              both => ' checked="checked"',
 5132:                              either => '',
 5133:                          );
 5134:         if ($prelink eq 'either') {
 5135:             $checkedpre{either} = ' checked="checked"';
 5136:             $checkedpre{both} = '';
 5137:         }
 5138:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'prelink'}.'</td>'.
 5139:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 5140:                       '<label><input type="radio" name="passwords_prelink" value="both"'.$checkedpre{'both'}.' />'.
 5141:                       &mt('Both username and e-mail address').'</label></span>&nbsp;&nbsp; '.
 5142:                       '<span class="LC_nobreak"><label>'.
 5143:                       '<input type="radio" name="passwords_prelink" value="either"'.$checkedpre{'either'}.' />'.
 5144:                       &mt('Either username or e-mail address').'</label></span></td></tr>';
 5145:         $itemcount ++;
 5146:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5147:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'postlink'}.'</td>'.
 5148:                       '<td class="LC_left_item">';
 5149:         my %postlinked;
 5150:         if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 5151:             foreach my $item (@{$types}) {
 5152:                 undef(%postlinked);
 5153:                 $datatable .= '<fieldset style="display: inline-block;">'.
 5154:                               '<legend>'.$usertypes->{$item}.'</legend>';
 5155:                 if (ref($postlink{$item}) eq 'ARRAY') {
 5156:                     map { $postlinked{$_} = 1; } (@{$postlink{$item}});
 5157:                 }
 5158:                 foreach my $field ('email','username') {
 5159:                     my $checked;
 5160:                     if ($postlinked{$field}) {
 5161:                         $checked = ' checked="checked"';
 5162:                     }
 5163:                     $datatable .= '<span class="LC_nobreak"><label>'.
 5164:                                   '<input type="checkbox" name="passwords_postlink_'.$item.'" value="'.
 5165:                                   $field.'"'.$checked.' />'.$field.'</label>'.
 5166:                                   '<span>&nbsp;&nbsp; ';
 5167:                 }
 5168:                 $datatable .= '</fieldset>';
 5169:             }
 5170:         }
 5171:         if (ref($postlink{'default'}) eq 'ARRAY') {
 5172:             map { $postlinked{$_} = 1; } (@{$postlink{'default'}});
 5173:         }
 5174:         $datatable .= '<fieldset style="display: inline-block;">'.
 5175:                       '<legend>'.$othertitle.'</legend>';
 5176:         foreach my $field ('email','username') {
 5177:             my $checked;
 5178:             if ($postlinked{$field}) {
 5179:                 $checked = ' checked="checked"';
 5180:             }
 5181:             $datatable .= '<span class="LC_nobreak"><label>'.
 5182:                           '<input type="checkbox" name="passwords_postlink_default" value="'.
 5183:                           $field.'"'.$checked.' />'.$field.'</label>'.
 5184:                           '<span>&nbsp;&nbsp; ';
 5185:         }
 5186:         $datatable .= '</fieldset></td></tr>';
 5187:         $itemcount ++;
 5188:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5189:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'emailsrc'}.'</td>'.
 5190:                       '<td class="LC_left_item">';
 5191:         foreach my $type ('permanent','critical','notify') {
 5192:             my $checkedemail;
 5193:             if ($emailsrc{$type}) {
 5194:                 $checkedemail = ' checked="checked"';
 5195:             }
 5196:             $datatable .= '<span class="LC_nobreak"><label>'.
 5197:                           '<input type="checkbox" name="passwords_emailsrc" value="'.
 5198:                           $type.'"'.$checkedemail.' />'.$titles{$type}.'</label>'.
 5199:                           '<span>&nbsp;&nbsp; ';
 5200:         }
 5201:         $datatable .= '</td></tr>';
 5202:         $itemcount ++;
 5203:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5204:         my $switchserver = &check_switchserver($dom,$confname);
 5205:         my ($showstd,$noshowstd);
 5206:         if ($nostdtext) {
 5207:             $noshowstd = ' checked="checked"';
 5208:         } else {
 5209:             $showstd = ' checked="checked"';
 5210:         }
 5211:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'customtext'}.'</td>'.
 5212:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 5213:                       &mt('Retain standard text:').
 5214:                       '<label><input type="radio" name="passwords_stdtext" value="1"'.$showstd.' />'.
 5215:                       &mt('Yes').'</label>'.'&nbsp;'.
 5216:                       '<label><input type="radio" name="passwords_stdtext" value="0"'.$noshowstd.' />'.
 5217:                       &mt('No').'</label></span><br />'.
 5218:                       '<span class="LC_fontsize_small">'.
 5219:                       &mt('(If you use the same account ...  reset a password from this page.)').'</span><br /><br />'.
 5220:                       &mt('Include custom text:');
 5221:         if ($customurl) {
 5222:             my $link =  &Apache::loncommon::modal_link($customurl,&mt('custom text'),600,500,
 5223:                                                        undef,undef,undef,undef,'background-color:#ffffff');
 5224:             $datatable .= '<span class="LC_nobreak">&nbsp;'.$link.
 5225:                           '<label><input type="checkbox" name="passwords_custom_del"'.
 5226:                           ' value="1" />'.&mt('Delete?').'</label></span>'.
 5227:                           ' <span class="LC_nobreak">&nbsp;'.&mt('Replace:').'</span>';
 5228:         }
 5229:         if ($switchserver) {
 5230:             $datatable .= '<span class="LC_nobreak">&nbsp;'.&mt('Upload to library server: [_1]',$switchserver).'</span>';
 5231:         } else {
 5232:             $datatable .='<span class="LC_nobreak">&nbsp;'.
 5233:                          '<input type="file" name="passwords_customfile" /></span>';
 5234:         }
 5235:         $datatable .= '</td></tr>';
 5236:     } elsif ($position eq 'middle') {
 5237:         my %domconf = &Apache::lonnet::get_dom('configuration',['defaults'],$dom);
 5238:         my @items = ('intauth_cost','intauth_check','intauth_switch');
 5239:         my %defaults;
 5240:         if (ref($domconf{'defaults'}) eq 'HASH') {
 5241:             %defaults = %{$domconf{'defaults'}};
 5242:             if ($defaults{'intauth_cost'} !~ /^\d+$/) {
 5243:                 $defaults{'intauth_cost'} = 10;
 5244:             }
 5245:             if ($defaults{'intauth_check'} !~ /^(0|1|2)$/) {
 5246:                 $defaults{'intauth_check'} = 0;
 5247:             }
 5248:             if ($defaults{'intauth_switch'} !~ /^(0|1|2)$/) {
 5249:                 $defaults{'intauth_switch'} = 0;
 5250:             }
 5251:         } else {
 5252:             %defaults = (
 5253:                           'intauth_cost'   => 10,
 5254:                           'intauth_check'  => 0,
 5255:                           'intauth_switch' => 0,
 5256:                         );
 5257:         }
 5258:         foreach my $item (@items) {
 5259:             if ($itemcount%2) {
 5260:                 $css_class = '';
 5261:             } else {
 5262:                 $css_class = ' class="LC_odd_row" ';
 5263:             }
 5264:             $datatable .= '<tr'.$css_class.'>'.
 5265:                           '<td><span class="LC_nobreak">'.$titles{$item}.
 5266:                           '</span></td><td class="LC_left_item" colspan="3">';
 5267:             if ($item eq 'intauth_switch') {
 5268:                 my @options = (0,1,2);
 5269:                 my %optiondesc = &Apache::lonlocal::texthash (
 5270:                                    0 => 'No',
 5271:                                    1 => 'Yes',
 5272:                                    2 => 'Yes, and copy existing passwd file to passwd.bak file',
 5273:                                  );
 5274:                 $datatable .= '<table width="100%">';
 5275:                 foreach my $option (@options) {
 5276:                     my $checked = ' ';
 5277:                     if ($defaults{$item} eq $option) {
 5278:                         $checked = ' checked="checked"';
 5279:                     }
 5280:                     $datatable .= '<tr><td class="LC_left_item"><span class="LC_nobreak">'.
 5281:                                   '<label><input type="radio" name="'.$item.
 5282:                                   '" value="'.$option.'"'.$checked.' />'.
 5283:                                   $optiondesc{$option}.'</label></span></td></tr>';
 5284:                 }
 5285:                 $datatable .= '</table>';
 5286:             } elsif ($item eq 'intauth_check') {
 5287:                 my @options = (0,1,2);
 5288:                 my %optiondesc = &Apache::lonlocal::texthash (
 5289:                                    0 => 'No',
 5290:                                    1 => 'Yes, allow login then update passwd file using default cost (if higher)',
 5291:                                    2 => 'Yes, disallow login if stored cost is less than domain default',
 5292:                                  );
 5293:                 $datatable .= '<table width="100%">';
 5294:                 foreach my $option (@options) {
 5295:                     my $checked = ' ';
 5296:                     my $onclick;
 5297:                     if ($defaults{$item} eq $option) {
 5298:                         $checked = ' checked="checked"';
 5299:                     }
 5300:                     if ($option == 2) {
 5301:                         $onclick = ' onclick="javascript:warnIntAuth(this);"';
 5302:                     }
 5303:                     $datatable .= '<tr><td class="LC_left_item"><span class="LC_nobreak">'.
 5304:                                   '<label><input type="radio" name="'.$item.
 5305:                                   '" value="'.$option.'"'.$checked.$onclick.' />'.
 5306:                                   $optiondesc{$option}.'</label></span></td></tr>';
 5307:                 }
 5308:                 $datatable .= '</table>';
 5309:             } else {
 5310:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
 5311:                               $defaults{$item}.'" size="3" onblur="javascript:warnIntAuth(this);" />';
 5312:             }
 5313:             $datatable .= '</td></tr>';
 5314:             $itemcount ++;
 5315:         }
 5316:     } elsif ($position eq 'lower') {
 5317:         my ($min,$max,%chars,$numsaved);
 5318:         $min = $Apache::lonnet::passwdmin;
 5319:         if (ref($settings) eq 'HASH') {
 5320:             if ($settings->{min}) {
 5321:                 $min = $settings->{min};
 5322:             }
 5323:             if ($settings->{max}) {
 5324:                 $max = $settings->{max};
 5325:             }
 5326:             if (ref($settings->{chars}) eq 'ARRAY') {
 5327:                 map { $chars{$_} = 1; } (@{$settings->{chars}});
 5328:             }
 5329:             if ($settings->{numsaved}) {
 5330:                 $numsaved = $settings->{numsaved};
 5331:             }
 5332:         }
 5333:         my %rulenames = &Apache::lonlocal::texthash(
 5334:                                                      uc => 'At least one upper case letter',
 5335:                                                      lc => 'At least one lower case letter',
 5336:                                                      num => 'At least one number',
 5337:                                                      spec => 'At least one non-alphanumeric',
 5338:                                                    );
 5339:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5340:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'min'}.'</td>'.
 5341:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 5342:                       '<input type="text" name="passwords_min" value="'.$min.'" size="3" '.
 5343:                       'onblur="javascript:warnIntPass(this);" />'.
 5344:                       '<span class="LC_fontsize_small"> '.&mt('(Enter an integer: 7 or larger)').'</span>'.
 5345:                       '</span></td></tr>';
 5346:         $itemcount ++;
 5347:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5348:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'max'}.'</td>'.
 5349:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 5350:                       '<input type="text" name="passwords_max" value="'.$max.'" size="3" '.
 5351:                       'onblur="javascript:warnIntPass(this);" />'.
 5352:                       '<span class="LC_fontsize_small"> '.&mt('(Leave blank for no maximum)').'</span>'.
 5353:                       '</span></td></tr>';
 5354:         $itemcount ++;
 5355:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5356:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'chars'}.'<br />'.
 5357:                       '<span class="LC_nobreak LC_fontsize_small">'.&mt('(Leave unchecked if not required)').
 5358:                       '</span></td>';
 5359:         my $numinrow = 2;
 5360:         my @possrules = ('uc','lc','num','spec');
 5361:         $datatable .= '<td class="LC_left_item"><table>';
 5362:         for (my $i=0; $i<@possrules; $i++) {
 5363:             my ($rem,$checked);
 5364:             if ($chars{$possrules[$i]}) {
 5365:                 $checked = ' checked="checked"';
 5366:             }
 5367:             $rem = $i%($numinrow);
 5368:             if ($rem == 0) {
 5369:                 if ($i > 0) {
 5370:                     $datatable .= '</tr>';
 5371:                 }
 5372:                 $datatable .= '<tr>';
 5373:             }
 5374:             $datatable .= '<td><span class="LC_nobreak"><label>'.
 5375:                           '<input type="checkbox" name="passwords_chars" value="'.$possrules[$i].'"'.$checked.' />'.
 5376:                           $rulenames{$possrules[$i]}.'</label></span></td>';
 5377:         }
 5378:         my $rem = @possrules%($numinrow);
 5379:         my $colsleft = $numinrow - $rem;
 5380:         if ($colsleft > 1 ) {
 5381:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 5382:                           '&nbsp;</td>';
 5383:         } elsif ($colsleft == 1) {
 5384:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 5385:         }
 5386:         $datatable .='</table></td></tr>';
 5387:         $itemcount ++;
 5388:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5389:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'numsaved'}.'</td>'.
 5390:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 5391:                       '<input type="text" name="passwords_numsaved" value="'.$numsaved.'" size="3" '.
 5392:                       'onblur="javascript:warnIntPass(this);" />'.
 5393:                       '<span class="LC_fontsize_small"> '.&mt('(Leave blank to not save previous passwords)').'</span>'.
 5394:                       '</span></td></tr>';
 5395:     } else {
 5396:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 5397:         my %ownerchg = (
 5398:                           by  => {},
 5399:                           for => {},
 5400:                        );
 5401:         my %ownertitles = &Apache::lonlocal::texthash (
 5402:                             by  => 'Course owner status(es) allowed',
 5403:                             for => 'Student status(es) allowed',
 5404:                           );
 5405:         if (ref($settings) eq 'HASH') {
 5406:             if (ref($settings->{crsownerchg}) eq 'HASH') {
 5407:                 if (ref($settings->{crsownerchg}{'by'}) eq 'ARRAY') {
 5408:                     map { $ownerchg{by}{$_} = 1; } (@{$settings->{crsownerchg}{'by'}});
 5409:                 }
 5410:                 if (ref($settings->{crsownerchg}{'for'}) eq 'ARRAY') {
 5411:                     map { $ownerchg{for}{$_} = 1; } (@{$settings->{crsownerchg}{'for'}});
 5412:                 }
 5413:             }
 5414:         }
 5415:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5416:         $datatable .= '<tr '.$css_class.'>'.
 5417:                       '<td>'.
 5418:                       &mt('Requirements').'<ul>'.
 5419:                       '<li>'.&mt("Course 'type' is not a Community").'</li>'.
 5420:                       '<li>'.&mt('User is Course Coordinator and also course owner').'</li>'.
 5421:                       '<li>'.&mt("Student's only active roles are student role(s) in course(s) owned by this user").'</li>'.
 5422:                       '<li>'.&mt('User, course, and student share same domain').'</li>'.
 5423:                       '</ul>'.
 5424:                       '</td>'.
 5425:                       '<td class="LC_left_item">';
 5426:         foreach my $item ('by','for') {
 5427:             $datatable .= '<fieldset style="display: inline-block;">'.
 5428:                           '<legend>'.$ownertitles{$item}.'</legend>';
 5429:             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 5430:                 foreach my $type (@{$types}) {
 5431:                     my $checked;
 5432:                     if ($ownerchg{$item}{$type}) {
 5433:                         $checked = ' checked="checked"';
 5434:                     }
 5435:                     $datatable .= '<span class="LC_nobreak"><label>'.
 5436:                                   '<input type="checkbox" name="passwords_crsowner_'.$item.'" value="'.
 5437:                                   $type.'"'.$checked.' />'.$usertypes->{$type}.'</label>'.
 5438:                                   '</span>&nbsp;&nbsp; ';
 5439:                 }
 5440:             }
 5441:             my $checked;
 5442:             if ($ownerchg{$item}{'default'}) {
 5443:                 $checked = ' checked="checked"';
 5444:             }
 5445:             $datatable .= '<span class="LC_nobreak"><label><input type="checkbox" '.
 5446:                           'name="passwords_crsowner_'.$item.'" value="default"'.$checked.' />'.
 5447:                           $othertitle.'</label></span></fieldset>';
 5448:         }
 5449:         $datatable .= '</td></tr>';
 5450:     }
 5451:     return $datatable;
 5452: }
 5453: 
 5454: sub print_wafproxy {
 5455:     my ($position,$dom,$settings,$rowtotal) = @_;
 5456:     my $css_class;
 5457:     my $itemcount = 0;
 5458:     my $datatable;
 5459:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 5460:     my (%othercontrol,%otherdoms,%aliases,%saml,%values,$setdom,$showdom);
 5461:     my %lt = &wafproxy_titles();
 5462:     foreach my $server (sort(keys(%servers))) {
 5463:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
 5464:         next if ($serverhome eq '');
 5465:         my $serverdom;
 5466:         if ($serverhome ne $server) {
 5467:             $serverdom = &Apache::lonnet::host_domain($serverhome);
 5468:             if (($serverdom ne '') && (&Apache::lonnet::domain($serverdom) ne '')) {
 5469:                 $othercontrol{$server} = $serverdom;
 5470:             }
 5471:         } else {
 5472:             $serverdom = &Apache::lonnet::host_domain($server);
 5473:             next if (($serverdom eq '') || (&Apache::lonnet::domain($serverdom) eq ''));
 5474:             if ($serverdom ne $dom) {
 5475:                 $othercontrol{$server} = $serverdom;
 5476:             } else {
 5477:                 $setdom = 1;
 5478:                 if (ref($settings) eq 'HASH') {
 5479:                     if (ref($settings->{'alias'}) eq 'HASH') {
 5480:                         $aliases{$dom} = $settings->{'alias'};
 5481:                         if ($aliases{$dom} ne '') {
 5482:                             $showdom = 1;
 5483:                         }
 5484:                     }
 5485:                     if (ref($settings->{'saml'}) eq 'HASH') {
 5486:                         $saml{$dom} = $settings->{'saml'};
 5487:                     }
 5488:                 }
 5489:             }
 5490:         }
 5491:     }
 5492:     if ($setdom) {
 5493:         %{$values{$dom}} = ();
 5494:         if (ref($settings) eq 'HASH') {
 5495:             foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext') {
 5496:                 $values{$dom}{$item} = $settings->{$item};
 5497:             }
 5498:         }
 5499:     }
 5500:     if (keys(%othercontrol)) {
 5501:         %otherdoms = reverse(%othercontrol);
 5502:         foreach my $domain (keys(%otherdoms)) {
 5503:             %{$values{$domain}} = ();
 5504:             my %config = &Apache::lonnet::get_dom('configuration',['wafproxy'],$domain);
 5505:             if (ref($config{'wafproxy'}) eq 'HASH') {
 5506:                 $aliases{$domain} = $config{'wafproxy'}{'alias'};
 5507:                 if (exists($config{'wafproxy'}{'saml'})) {
 5508:                     $saml{$domain} = $config{'wafproxy'}{'saml'};
 5509:                 }
 5510:                 foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext') {
 5511:                     $values{$domain}{$item} = $config{'wafproxy'}{$item};
 5512:                 }
 5513:             }
 5514:         }
 5515:     }
 5516:     if ($position eq 'top') {
 5517:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 5518:         my %aliasinfo;
 5519:         foreach my $server (sort(keys(%servers))) {
 5520:             $itemcount ++;
 5521:             my $dom_in_effect;
 5522:             my $aliasrows = '<tr>'.
 5523:                             '<td class="LC_left_item" style="vertical-align: baseline;">'.
 5524:                             &mt('Hostname').':&nbsp;'.
 5525:                             '<i>'.&Apache::lonnet::hostname($server).'</i></td><td>&nbsp;</td>';
 5526:             if ($othercontrol{$server}) {
 5527:                 $dom_in_effect = $othercontrol{$server};
 5528:                 my ($current,$forsaml);
 5529:                 if (ref($aliases{$dom_in_effect}) eq 'HASH') {
 5530:                     $current = $aliases{$dom_in_effect}{$server};
 5531:                 }
 5532:                 if (ref($saml{$dom_in_effect}) eq 'HASH') {
 5533:                     if ($saml{$dom_in_effect}{$server}) {
 5534:                         $forsaml = 1;
 5535:                     }
 5536:                 }
 5537:                 $aliasrows .= '<td class="LC_left_item" style="vertical-align: baseline;">'.
 5538:                               &mt('Alias').':&nbsp';
 5539:                 if ($current) {
 5540:                     $aliasrows .= $current;
 5541:                     if ($forsaml) {
 5542:                          $aliasrows .= '&nbsp;('.&mt('also for SSO Auth').')';
 5543:                     }
 5544:                 } else {
 5545:                     $aliasrows .= &mt('None');
 5546:                 }
 5547:                 $aliasrows .= '&nbsp;<span class="LC_small">('.
 5548:                               &mt('controlled by domain: [_1]',
 5549:                                   '<b>'.$dom_in_effect.'</b>').')</span></td>';
 5550:             } else {
 5551:                 $dom_in_effect = $dom;
 5552:                 my ($current,$samlon,$samloff);
 5553:                 $samloff = ' checked="checked"';
 5554:                 if (ref($aliases{$dom}) eq 'HASH') {
 5555:                     if ($aliases{$dom}{$server}) {
 5556:                         $current = $aliases{$dom}{$server};
 5557:                     }
 5558:                 }
 5559:                 if (ref($saml{$dom}) eq 'HASH') {
 5560:                     if ($saml{$dom}{$server}) {
 5561:                         $samlon = $samloff;
 5562:                         undef($samloff);
 5563:                     }
 5564:                 }
 5565:                 $aliasrows .= '<td class="LC_left_item" style="vertical-align: baseline;">'.
 5566:                               &mt('Alias').':&nbsp;'.
 5567:                               '<input type="text" name="wafproxy_alias_'.$server.'" '.
 5568:                               'value="'.$current.'" size="30" />'.
 5569:                               ('&nbsp;'x2).'<span class="LC_nobreak">'.
 5570:                               &mt('Alias used for SSO Auth').':&nbsp;<label>'.
 5571:                               '<input type="radio" value="0"'.$samloff.' name="wafproxy_alias_saml_'.$server.'" />'.
 5572:                               &mt('No').'</label>&nbsp;<label>'.
 5573:                               '<input type="radio" value="1"'.$samlon.' name="wafproxy_alias_saml_'.$server.'" />'.
 5574:                               &mt('Yes').'</label></span>'.
 5575:                               '</td>';
 5576:             }
 5577:             $aliasrows .= '</tr>';
 5578:             $aliasinfo{$dom_in_effect} .= $aliasrows;
 5579:         }
 5580:         if ($aliasinfo{$dom}) {
 5581:             my ($onclick,$wafon,$wafoff,$showtable);
 5582:             $onclick = ' onclick="javascript:toggleWAF();"';
 5583:             $wafoff = ' checked="checked"';
 5584:             $showtable = ' style="display:none";';
 5585:             if ($showdom) {
 5586:                 $wafon = $wafoff;
 5587:                 $wafoff = '';
 5588:                 $showtable = ' style="display:inline;"';
 5589:             }
 5590:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 5591:             $datatable = '<tr'.$css_class.'>'.
 5592:                          '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'<br />'.
 5593:                          '<span class="LC_nobreak">'.&mt('WAF in use?').'&nbsp;<label>'.
 5594:                          '<input type="radio" name="wafproxy_'.$dom.'" value="1"'.$wafon.$onclick.' />'.
 5595:                          &mt('Yes').'</label>'.('&nbsp;'x2).'<label>'.
 5596:                          '<input type="radio" name="wafproxy_'.$dom.'" value="0"'.$wafoff.$onclick.' />'.
 5597:                          &mt('No').'</label></span></td>'.
 5598:                          '<td class="LC_left_item">'.
 5599:                          '<table id="wafproxy_table"'.$showtable.'>'.$aliasinfo{$dom}.
 5600:                          '</table></td></tr>';
 5601:             $itemcount++;
 5602:         }
 5603:         if (keys(%otherdoms)) {
 5604:             foreach my $key (sort(keys(%otherdoms))) {
 5605:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 5606:                 $datatable .= '<tr'.$css_class.'>'.
 5607:                               '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$key.'</b>').'</td>'.
 5608:                               '<td class="LC_left_item"><table>'.$aliasinfo{$key}.
 5609:                               '</table></td></tr>';
 5610:                 $itemcount++;
 5611:             }
 5612:         }
 5613:     } else {
 5614:         my %ip_methods = &remoteip_methods();
 5615:         if ($setdom) {
 5616:             $itemcount ++;
 5617:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 5618:             my ($nowafstyle,$wafstyle,$curr_remotip,$currwafdisplay,$vpndircheck,$vpnaliascheck,
 5619:                 $currwafvpn,$wafrangestyle,$alltossl,$ssltossl);
 5620:             $wafstyle = ' style="display:none;"';
 5621:             $nowafstyle = ' style="display:table-row;"';
 5622:             $currwafdisplay = ' style="display: none"';
 5623:             $wafrangestyle = ' style="display: none"';
 5624:             $curr_remotip = 'n';
 5625:             $ssltossl = ' checked="checked"';
 5626:             if ($showdom) {
 5627:                 $wafstyle = ' style="display:table-row;"';
 5628:                 $nowafstyle =  ' style="display:none;"';
 5629:                 if (keys(%{$values{$dom}})) {
 5630:                     if ($values{$dom}{remoteip} =~ /^[nmh]$/) {
 5631:                         $curr_remotip = $values{$dom}{remoteip};
 5632:                     }
 5633:                     if ($curr_remotip eq 'h') {
 5634:                         $currwafdisplay = ' style="display:table-row"';
 5635:                         $wafrangestyle = ' style="display:inline-block;"';
 5636:                     }
 5637:                     if ($values{$dom}{'sslopt'}) {
 5638:                         $alltossl = ' checked="checked"';
 5639:                         $ssltossl = '';
 5640:                     }
 5641:                 }
 5642:                 if (($values{$dom}{'vpnint'} ne '') || ($values{$dom}{'vpnext'} ne '')) {
 5643:                     $vpndircheck = ' checked="checked"';
 5644:                     $currwafvpn = ' style="display:table-row;"';
 5645:                     $wafrangestyle = ' style="display:inline-block;"';
 5646:                 } else {
 5647:                     $vpnaliascheck = ' checked="checked"';
 5648:                     $currwafvpn = ' style="display:none;"';
 5649:                 }
 5650:             }
 5651:             $datatable .= '<tr'.$css_class.' id="nowafproxyrow_'.$dom.'"'.$wafstyle.'>'.
 5652:                           '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'</td>'.
 5653:                           '<td class="LC_right_item">'.&mt('WAF not in use, nothing to set').'</td>'.
 5654:                           '</tr>'.
 5655:                           '<tr'.$css_class.' id="wafproxyrow_'.$dom.'"'.$wafstyle.'>'.
 5656:                           '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'<br /><br />'.
 5657:                           '<div id="wafproxyranges_'.$dom.'">'.&mt('Format for comma separated IP ranges').':<br />'.
 5658:                           &mt('A.B.C.D/N or A.B.C.D-E.F.G.H').'<br />'.
 5659:                           &mt('Range(s) stored in CIDR notation').'</div></td>'.
 5660:                           '<td class="LC_left_item"><table>'.
 5661:                           '<tr>'.
 5662:                           '<td valign="top">'.$lt{'remoteip'}.':&nbsp;'.
 5663:                           '<select name="wafproxy_remoteip" id="wafproxy_remoteip" onchange="javascript:updateWAF();">';
 5664:             foreach my $option ('m','h','n') {
 5665:                 my $sel;
 5666:                 if ($option eq $curr_remotip) {
 5667:                    $sel = ' selected="selected"';
 5668:                 }
 5669:                 $datatable .= '<option value="'.$option.'"'.$sel.'>'.
 5670:                               $ip_methods{$option}.'</option>';
 5671:             }
 5672:             $datatable .= '</select></td></tr>'."\n".
 5673:                           '<tr id="wafproxy_header"'.$currwafdisplay.'><td>'.
 5674:                           $lt{'ipheader'}.':&nbsp;'.
 5675:                           '<input type="text" value="'.$values{$dom}{'ipheader'}.'" '.
 5676:                           'name="wafproxy_ipheader" />'.
 5677:                           '</td></tr>'."\n".
 5678:                           '<tr id="wafproxy_trust"'.$currwafdisplay.'><td>'.
 5679:                           $lt{'trusted'}.':<br />'.
 5680:                           '<textarea name="wafproxy_trusted" rows="3" cols="80">'.
 5681:                           $values{$dom}{'trusted'}.'</textarea>'.
 5682:                           '</td></tr>'."\n".
 5683:                           '<tr><td><hr /></td></tr>'."\n".
 5684:                           '<tr>'.
 5685:                           '<td valign="top">'.$lt{'vpnaccess'}.':<br /><span class="LC_nobreak">'.
 5686:                           '<label><input type="radio" name="wafproxy_vpnaccess"'.$vpndircheck.' value="1" onclick="javascript:checkWAF();" />'.
 5687:                           $lt{'vpndirect'}.'</label>'.('&nbsp;'x2).
 5688:                           '<label><input type="radio" name="wafproxy_vpnaccess"'.$vpnaliascheck.' value="0" onclick="javascript:checkWAF();" />'.
 5689:                           $lt{'vpnaliased'}.'</label></span></td></tr>';
 5690:             foreach my $item ('vpnint','vpnext') {
 5691:                 $datatable .= '<tr id="wafproxy_show_'.$item.'"'.$currwafvpn.'>'.
 5692:                               '<td valign="top">'.$lt{$item}.':<br />'.
 5693:                               '<textarea name="wafproxy_'.$item.'" rows="3" cols="80">'.
 5694:                               $values{$dom}{$item}.'</textarea>'.
 5695:                               '</td></tr>'."\n";
 5696:             }
 5697:             $datatable .= '<tr><td><hr /></td></tr>'."\n".
 5698:                           '<tr>'.
 5699:                           '<td valign="top">'.$lt{'sslopt'}.':<br /><span class="LC_nobreak">'.
 5700:                           '<label><input type="radio" name="wafproxy_sslopt"'.$alltossl.' value="1" />'.
 5701:                           $lt{'alltossl'}.'</label>'.('&nbsp;'x2).
 5702:                           '<label><input type="radio" name="wafproxy_sslopt"'.$ssltossl.' value="0" />'.
 5703:                           $lt{'ssltossl'}.'</label></span></td></tr>'."\n".
 5704:                           '</table></td></tr>';
 5705:         }
 5706:         if (keys(%otherdoms)) {
 5707:             foreach my $domain (sort(keys(%otherdoms))) {
 5708:                 $itemcount ++;
 5709:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 5710:                 $datatable .= '<tr'.$css_class.'>'.
 5711:                               '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$domain.'</b>').'</td>'.
 5712:                               '<td class="LC_left_item"><table>';
 5713:                 foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
 5714:                     my $showval = &mt('None');
 5715:                     if ($item eq 'ssl') {
 5716:                         $showval = $lt{'ssltossl'};
 5717:                     }
 5718:                     if ($values{$domain}{$item}) {
 5719:                         $showval = $values{$domain}{$item};
 5720:                         if ($item eq 'ssl') {
 5721:                             $showval = $lt{'alltossl'};
 5722:                         } elsif ($item eq 'remoteip') {
 5723:                             $showval = $ip_methods{$values{$domain}{$item}};
 5724:                         }
 5725:                     }
 5726:                     $datatable .= '<tr>'.
 5727:                                   '<td>'.$lt{$item}.':&nbsp;'.$showval.'</td></tr>';
 5728:                 }
 5729:                 $datatable .= '</table></td></tr>';
 5730:             }
 5731:         }
 5732:     }
 5733:     $$rowtotal += $itemcount;
 5734:     return $datatable;
 5735: }
 5736: 
 5737: sub wafproxy_titles {
 5738:     return &Apache::lonlocal::texthash(
 5739:                remoteip   => "Method for determining user's IP",
 5740:                ipheader   => 'Request header containing remote IP',
 5741:                trusted    => 'Trusted IP range(s)',
 5742:                vpnaccess  => 'Access from institutional VPN',
 5743:                vpndirect  => 'via regular hostname (no WAF)',
 5744:                vpnaliased => 'via aliased hostname (WAF)',
 5745:                vpnint     => 'Internal IP Range(s) for VPN sessions',
 5746:                vpnext     => 'IP Range(s) for backend WAF connections',
 5747:                sslopt     => 'Forwarding http/https',
 5748:                alltossl   => 'WAF forwards both http and https requests to https',
 5749:                ssltossl   => 'WAF forwards http requests to http and https to https',
 5750:            );
 5751: }
 5752: 
 5753: sub remoteip_methods {
 5754:     return &Apache::lonlocal::texthash(
 5755:               m => 'Use Apache mod_remoteip',
 5756:               h => 'Use headers parsed by LON-CAPA',
 5757:               n => 'Not in use',
 5758:            );
 5759: }
 5760: 
 5761: sub print_usersessions {
 5762:     my ($position,$dom,$settings,$rowtotal) = @_;
 5763:     my ($css_class,$datatable,%checked,%choices);
 5764:     my (%by_ip,%by_location,@intdoms);
 5765:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location);
 5766: 
 5767:     my @alldoms = &Apache::lonnet::all_domains();
 5768:     my %serverhomes = %Apache::lonnet::serverhomeIDs;
 5769:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 5770:     my %altids = &id_for_thisdom(%servers);
 5771:     my $itemcount = 1;
 5772:     if ($position eq 'top') {
 5773:         if (keys(%serverhomes) > 1) {
 5774:             my %spareid = &current_offloads_to($dom,$settings,\%servers);
 5775:             my ($curroffloadnow,$curroffloadoth);
 5776:             if (ref($settings) eq 'HASH') {
 5777:                 if (ref($settings->{'offloadnow'}) eq 'HASH') {
 5778:                     $curroffloadnow = $settings->{'offloadnow'};
 5779:                 }
 5780:                 if (ref($settings->{'offloadoth'}) eq 'HASH') {
 5781:                     $curroffloadoth = $settings->{'offloadoth'};
 5782:                 }
 5783:             }
 5784:             my $other_insts = scalar(keys(%by_location));
 5785:             $datatable .= &spares_row($dom,\%servers,\%spareid,\%serverhomes,\%altids,
 5786:                                       $other_insts,$curroffloadnow,$curroffloadoth,$rowtotal);
 5787:         } else {
 5788:             $datatable .= '<tr'.$css_class.'><td colspan="2">'.
 5789:                           &mt('Nothing to set here, as the cluster to which this domain belongs only contains one server.');
 5790:         }
 5791:     } else {
 5792:         if (keys(%by_location) == 0) {
 5793:             $datatable .= '<tr'.$css_class.'><td colspan="2">'.
 5794:                           &mt('Nothing to set here, as the cluster to which this domain belongs only contains one institution.');
 5795:         } else {
 5796:             my %lt = &usersession_titles();
 5797:             my $numinrow = 5;
 5798:             my $prefix;
 5799:             my @types;
 5800:             if ($position eq 'bottom') {
 5801:                 $prefix = 'remote';
 5802:                 @types = ('version','excludedomain','includedomain');
 5803:             } else {
 5804:                 $prefix = 'hosted';
 5805:                 @types = ('excludedomain','includedomain');
 5806:             }
 5807:             my (%current,%checkedon,%checkedoff);
 5808:             my @lcversions = &Apache::lonnet::all_loncaparevs();
 5809:             my @locations = sort(keys(%by_location));
 5810:             foreach my $type (@types) {
 5811:                 $checkedon{$type} = '';
 5812:                 $checkedoff{$type} = ' checked="checked"';
 5813:             }
 5814:             if (ref($settings) eq 'HASH') {
 5815:                 if (ref($settings->{$prefix}) eq 'HASH') {
 5816:                     foreach my $key (keys(%{$settings->{$prefix}})) {
 5817:                         $current{$key} = $settings->{$prefix}{$key};
 5818:                         if ($key eq 'version') {
 5819:                             if ($current{$key} ne '') {
 5820:                                 $checkedon{$key} = ' checked="checked"';
 5821:                                 $checkedoff{$key} = '';
 5822:                             }
 5823:                         } elsif (ref($current{$key}) eq 'ARRAY') {
 5824:                             $checkedon{$key} = ' checked="checked"';
 5825:                             $checkedoff{$key} = '';
 5826:                         }
 5827:                     }
 5828:                 }
 5829:             }
 5830:             foreach my $type (@types) {
 5831:                 next if ($type ne 'version' && !@locations);
 5832:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 5833:                 $datatable .= '<tr'.$css_class.'>
 5834:                                <td><span class="LC_nobreak">'.$lt{$type}.'</span><br />
 5835:                                <span class="LC_nobreak">&nbsp;
 5836:                                <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedoff{$type}.' value="0" />'.&mt('Not in use').'</label>&nbsp;
 5837:                                <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedon{$type}.' value="1" />'.&mt('In use').'</label></span></td><td>';
 5838:                 if ($type eq 'version') {
 5839:                     my $selector = '<select name="'.$prefix.'_version">';
 5840:                     foreach my $version (@lcversions) {
 5841:                         my $selected = '';
 5842:                         if ($current{'version'} eq $version) {
 5843:                             $selected = ' selected="selected"';
 5844:                         }
 5845:                         $selector .= ' <option value="'.$version.'"'.
 5846:                                      $selected.'>'.$version.'</option>';
 5847:                     }
 5848:                     $selector .= '</select> ';
 5849:                     $datatable .= &mt('remote server must be version: [_1] or later',$selector);
 5850:                 } else {
 5851:                     $datatable.= '<div><input type="button" value="'.&mt('check all').'" '.
 5852:                                  'onclick="javascript:checkAll(document.display.'.$prefix.'_'.$type.')"'.
 5853:                                  ' />'.('&nbsp;'x2).
 5854:                                  '<input type="button" value="'.&mt('uncheck all').'" '.
 5855:                                  'onclick="javascript:uncheckAll(document.display.'.$prefix.'_'.$type.')" />'.
 5856:                                  "\n".
 5857:                                  '</div><div><table>';
 5858:                     my $rem;
 5859:                     for (my $i=0; $i<@locations; $i++) {
 5860:                         my ($showloc,$value,$checkedtype);
 5861:                         if (ref($by_location{$locations[$i]}) eq 'ARRAY') {
 5862:                             my $ip = $by_location{$locations[$i]}->[0];
 5863:                             if (ref($by_ip{$ip}) eq 'ARRAY') {
 5864:                                  $value = join(':',@{$by_ip{$ip}});
 5865:                                 $showloc = join(', ',@{$by_ip{$ip}});
 5866:                                 if (ref($current{$type}) eq 'ARRAY') {
 5867:                                     foreach my $loc (@{$by_ip{$ip}}) {  
 5868:                                         if (grep(/^\Q$loc\E$/,@{$current{$type}})) {
 5869:                                             $checkedtype = ' checked="checked"';
 5870:                                             last;
 5871:                                         }
 5872:                                     }
 5873:                                 }
 5874:                             }
 5875:                         }
 5876:                         $rem = $i%($numinrow);
 5877:                         if ($rem == 0) {
 5878:                             if ($i > 0) {
 5879:                                 $datatable .= '</tr>';
 5880:                             }
 5881:                             $datatable .= '<tr>';
 5882:                         }
 5883:                         $datatable .= '<td class="LC_left_item">'.
 5884:                                       '<span class="LC_nobreak"><label>'.
 5885:                                       '<input type="checkbox" name="'.$prefix.'_'.$type.
 5886:                                       '" value="'.$value.'"'.$checkedtype.' />'.$showloc.
 5887:                                       '</label></span></td>';
 5888:                     }
 5889:                     $rem = @locations%($numinrow);
 5890:                     my $colsleft = $numinrow - $rem;
 5891:                     if ($colsleft > 1 ) {
 5892:                         $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 5893:                                       '&nbsp;</td>';
 5894:                     } elsif ($colsleft == 1) {
 5895:                         $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 5896:                     }
 5897:                     $datatable .= '</tr></table>';
 5898:                 }
 5899:                 $datatable .= '</td></tr>';
 5900:                 $itemcount ++;
 5901:             }
 5902:         }
 5903:     }
 5904:     $$rowtotal += $itemcount;
 5905:     return $datatable;
 5906: }
 5907: 
 5908: sub build_location_hashes {
 5909:     my ($intdoms,$by_ip,$by_location) = @_;
 5910:     return unless((ref($intdoms) eq 'ARRAY') && (ref($by_ip) eq 'HASH') &&
 5911:                   (ref($by_location) eq 'HASH')); 
 5912:     my %iphost = &Apache::lonnet::get_iphost();
 5913:     my $primary_id = &Apache::lonnet::domain($env{'request.role.domain'},'primary');
 5914:     my $primary_ip = &Apache::lonnet::get_host_ip($primary_id);
 5915:     if (ref($iphost{$primary_ip}) eq 'ARRAY') {
 5916:         foreach my $id (@{$iphost{$primary_ip}}) {
 5917:             my $intdom = &Apache::lonnet::internet_dom($id);
 5918:             unless(grep(/^\Q$intdom\E$/,@{$intdoms})) {
 5919:                 push(@{$intdoms},$intdom);
 5920:             }
 5921:         }
 5922:     }
 5923:     foreach my $ip (keys(%iphost)) {
 5924:         if (ref($iphost{$ip}) eq 'ARRAY') {
 5925:             foreach my $id (@{$iphost{$ip}}) {
 5926:                 my $location = &Apache::lonnet::internet_dom($id);
 5927:                 if ($location) {
 5928:                     next if (grep(/^\Q$location\E$/,@{$intdoms}));
 5929:                     if (ref($by_ip->{$ip}) eq 'ARRAY') {
 5930:                         unless(grep(/^\Q$location\E$/,@{$by_ip->{$ip}})) {
 5931:                             push(@{$by_ip->{$ip}},$location);
 5932:                         }
 5933:                     } else {
 5934:                         $by_ip->{$ip} = [$location];
 5935:                     }
 5936:                 }
 5937:             }
 5938:         }
 5939:     }
 5940:     foreach my $ip (sort(keys(%{$by_ip}))) {
 5941:         if (ref($by_ip->{$ip}) eq 'ARRAY') {
 5942:             @{$by_ip->{$ip}} = sort(@{$by_ip->{$ip}});
 5943:             my $first = $by_ip->{$ip}->[0];
 5944:             if (ref($by_location->{$first}) eq 'ARRAY') {
 5945:                 unless (grep(/^\Q$ip\E$/,@{$by_location->{$first}})) {
 5946:                     push(@{$by_location->{$first}},$ip);
 5947:                 }
 5948:             } else {
 5949:                 $by_location->{$first} = [$ip];
 5950:             }
 5951:         }
 5952:     }
 5953:     return;
 5954: }
 5955: 
 5956: sub current_offloads_to {
 5957:     my ($dom,$settings,$servers) = @_;
 5958:     my (%spareid,%otherdomconfigs);
 5959:     if (ref($servers) eq 'HASH') {
 5960:         foreach my $lonhost (sort(keys(%{$servers}))) {
 5961:             my $gotspares;
 5962:             if (ref($settings) eq 'HASH') {
 5963:                 if (ref($settings->{'spares'}) eq 'HASH') {
 5964:                     if (ref($settings->{'spares'}{$lonhost}) eq 'HASH') {
 5965:                         $spareid{$lonhost}{'primary'} = $settings->{'spares'}{$lonhost}{'primary'};
 5966:                         $spareid{$lonhost}{'default'} = $settings->{'spares'}{$lonhost}{'default'};
 5967:                         $gotspares = 1;
 5968:                     }
 5969:                 }
 5970:             }
 5971:             unless ($gotspares) {
 5972:                 my $gotspares;
 5973:                 my $serverhomeID =
 5974:                     &Apache::lonnet::get_server_homeID($servers->{$lonhost});
 5975:                 my $serverhomedom =
 5976:                     &Apache::lonnet::host_domain($serverhomeID);
 5977:                 if ($serverhomedom ne $dom) {
 5978:                     if (ref($otherdomconfigs{$serverhomedom} eq 'HASH')) {
 5979:                         if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 5980:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 5981:                                 $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 5982:                                 $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 5983:                                 $gotspares = 1;
 5984:                             }
 5985:                         }
 5986:                     } else {
 5987:                         $otherdomconfigs{$serverhomedom} =
 5988:                             &Apache::lonnet::get_dom('configuration',['usersessions'],$serverhomedom);
 5989:                         if (ref($otherdomconfigs{$serverhomedom}) eq 'HASH') {
 5990:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 5991:                                 if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 5992:                                     if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{$lonhost}) eq 'HASH') {
 5993:                                         $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 5994:                                         $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 5995:                                         $gotspares = 1;
 5996:                                     }
 5997:                                 }
 5998:                             }
 5999:                         }
 6000:                     }
 6001:                 }
 6002:             }
 6003:             unless ($gotspares) {
 6004:                 if ($lonhost eq $Apache::lonnet::perlvar{'lonHostID'}) {
 6005:                     $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 6006:                     $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 6007:                } else {
 6008:                     my $server_hostname = &Apache::lonnet::hostname($lonhost);
 6009:                     my $server_homeID = &Apache::lonnet::get_server_homeID($server_hostname);
 6010:                     if ($server_homeID eq $Apache::lonnet::perlvar{'lonHostID'}) {
 6011:                         $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 6012:                         $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 6013:                     } else {
 6014:                         my %what = (
 6015:                              spareid => 1,
 6016:                         );
 6017:                         my ($result,$returnhash) = 
 6018:                             &Apache::lonnet::get_remote_globals($lonhost,\%what);
 6019:                         if ($result eq 'ok') { 
 6020:                             if (ref($returnhash) eq 'HASH') {
 6021:                                 if (ref($returnhash->{'spareid'}) eq 'HASH') {
 6022:                                     $spareid{$lonhost}{'primary'} = $returnhash->{'spareid'}->{'primary'};
 6023:                                     $spareid{$lonhost}{'default'} = $returnhash->{'spareid'}->{'default'};
 6024:                                 }
 6025:                             }
 6026:                         }
 6027:                     }
 6028:                 }
 6029:             }
 6030:         }
 6031:     }
 6032:     return %spareid;
 6033: }
 6034: 
 6035: sub spares_row {
 6036:     my ($dom,$servers,$spareid,$serverhomes,$altids,$other_insts,
 6037:         $curroffloadnow,$curroffloadoth,$rowtotal) = @_;
 6038:     my $css_class;
 6039:     my $numinrow = 4;
 6040:     my $itemcount = 1;
 6041:     my $datatable;
 6042:     my %typetitles = &sparestype_titles();
 6043:     if ((ref($servers) eq 'HASH') && (ref($spareid) eq 'HASH') && (ref($altids) eq 'HASH')) {
 6044:         foreach my $server (sort(keys(%{$servers}))) {
 6045:             my $serverhome = &Apache::lonnet::get_server_homeID($servers->{$server});
 6046:             my ($othercontrol,$serverdom);
 6047:             if ($serverhome ne $server) {
 6048:                 $serverdom = &Apache::lonnet::host_domain($serverhome);
 6049:                 $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 6050:             } else {
 6051:                 $serverdom = &Apache::lonnet::host_domain($server);
 6052:                 if ($serverdom ne $dom) {
 6053:                     $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 6054:                 }
 6055:             }
 6056:             next unless (ref($spareid->{$server}) eq 'HASH');
 6057:             my ($checkednow,$checkedoth);
 6058:             if (ref($curroffloadnow) eq 'HASH') {
 6059:                 if ($curroffloadnow->{$server}) {
 6060:                     $checkednow = ' checked="checked"';
 6061:                 }
 6062:             }
 6063:             if (ref($curroffloadoth) eq 'HASH') {
 6064:                 if ($curroffloadoth->{$server}) {
 6065:                     $checkedoth = ' checked="checked"';
 6066:                 }
 6067:             }
 6068:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6069:             $datatable .= '<tr'.$css_class.'>
 6070:                            <td rowspan="2">
 6071:                             <span class="LC_nobreak">'.
 6072:                           &mt('[_1] when busy, offloads to:'
 6073:                               ,'<b>'.$server.'</b>').'</span><br />'.
 6074:                           '<span class="LC_nobreak">'."\n".
 6075:                           '<label><input type="checkbox" name="offloadnow" value="'.$server.'"'.$checkednow.' />'.
 6076:                           '&nbsp;'.&mt('Switch any active user on next access').'</label></span>'.
 6077:                           "\n";
 6078:             if ($other_insts) {
 6079:                 $datatable .= '<br />'.
 6080:                               '<span class="LC_nobreak">'."\n".
 6081:                           '<label><input type="checkbox" name="offloadoth" value="'.$server.'"'.$checkedoth.' />'.
 6082:                           '&nbsp;'.&mt('Switch other institutions on next access').'</label></span>'.
 6083:                           "\n";
 6084:             }
 6085:             my (%current,%canselect);
 6086:             my @choices = 
 6087:                 &possible_newspares($server,$spareid->{$server},$serverhomes,$altids);
 6088:             foreach my $type ('primary','default') {
 6089:                 if (ref($spareid->{$server}) eq 'HASH') {
 6090:                     if (ref($spareid->{$server}{$type}) eq 'ARRAY') {
 6091:                         my @spares = @{$spareid->{$server}{$type}};
 6092:                         if (@spares > 0) {
 6093:                             if ($othercontrol) {
 6094:                                 $current{$type} = join(', ',@spares);
 6095:                             } else {
 6096:                                 $current{$type} .= '<table>';
 6097:                                 my $numspares = scalar(@spares);
 6098:                                 for (my $i=0;  $i<@spares; $i++) {
 6099:                                     my $rem = $i%($numinrow);
 6100:                                     if ($rem == 0) {
 6101:                                         if ($i > 0) {
 6102:                                             $current{$type} .= '</tr>';
 6103:                                         }
 6104:                                         $current{$type} .= '<tr>';
 6105:                                     }
 6106:                                     $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;'.
 6107:                                                        $spareid->{$server}{$type}[$i].
 6108:                                                        '</label></td>'."\n";
 6109:                                 }
 6110:                                 my $rem = @spares%($numinrow);
 6111:                                 my $colsleft = $numinrow - $rem;
 6112:                                 if ($colsleft > 1 ) {
 6113:                                     $current{$type} .= '<td colspan="'.$colsleft.
 6114:                                                        '" class="LC_left_item">'.
 6115:                                                        '&nbsp;</td>';
 6116:                                 } elsif ($colsleft == 1) {
 6117:                                     $current{$type} .= '<td class="LC_left_item">&nbsp;</td>'."\n";
 6118:                                 }
 6119:                                 $current{$type} .= '</tr></table>';
 6120:                             }
 6121:                         }
 6122:                     }
 6123:                     if ($current{$type} eq '') {
 6124:                         $current{$type} = &mt('None specified');
 6125:                     }
 6126:                     if ($othercontrol) {
 6127:                         if ($type eq 'primary') {
 6128:                             $canselect{$type} = $othercontrol;
 6129:                         }
 6130:                     } else {
 6131:                         $canselect{$type} = 
 6132:                             &mt('Add new [_1]'.$type.'[_2]:','<i>','</i>').'&nbsp;'.
 6133:                             '<select name="newspare_'.$type.'_'.$server.'" '.
 6134:                             'id="newspare_'.$type.'_'.$server.'" onchange="checkNewSpares('."'$server','$type'".');">'."\n".
 6135:                             '<option value="" selected ="selected">'.&mt('Select').'</option>'."\n";
 6136:                         if (@choices > 0) {
 6137:                             foreach my $lonhost (@choices) {
 6138:                                 $canselect{$type} .= '<option value="'.$lonhost.'">'.$lonhost.'</option>'."\n";
 6139:                             }
 6140:                         }
 6141:                         $canselect{$type} .= '</select>'."\n";
 6142:                     }
 6143:                 } else {
 6144:                     $current{$type} = &mt('Could not be determined');
 6145:                     if ($type eq 'primary') {
 6146:                         $canselect{$type} =  $othercontrol;
 6147:                     }
 6148:                 }
 6149:                 if ($type eq 'default') {
 6150:                     $datatable .= '<tr'.$css_class.'>';
 6151:                 }
 6152:                 $datatable .= '<td><i>'.$typetitles{$type}.'</i></td>'."\n".
 6153:                               '<td>'.$current{$type}.'</td>'."\n".
 6154:                               '<td>'.$canselect{$type}.'</td></tr>'."\n";
 6155:             }
 6156:             $itemcount ++;
 6157:         }
 6158:     }
 6159:     $$rowtotal += $itemcount;
 6160:     return $datatable;
 6161: }
 6162: 
 6163: sub possible_newspares {
 6164:     my ($server,$currspares,$serverhomes,$altids) = @_;
 6165:     my $serverhostname = &Apache::lonnet::hostname($server);
 6166:     my %excluded;
 6167:     if ($serverhostname ne '') {
 6168:         %excluded = (
 6169:                        $serverhostname => 1,
 6170:                     );
 6171:     }
 6172:     if (ref($currspares) eq 'HASH') {
 6173:         foreach my $type (keys(%{$currspares})) {
 6174:             if (ref($currspares->{$type}) eq 'ARRAY') {
 6175:                 if (@{$currspares->{$type}} > 0) {
 6176:                     foreach my $curr (@{$currspares->{$type}}) {
 6177:                         my $hostname = &Apache::lonnet::hostname($curr);
 6178:                         $excluded{$hostname} = 1;
 6179:                     }
 6180:                 }
 6181:             }
 6182:         }
 6183:     }
 6184:     my @choices;
 6185:     if ((ref($serverhomes) eq 'HASH') && (ref($altids) eq 'HASH')) {
 6186:         if (keys(%{$serverhomes}) > 1) {
 6187:             foreach my $name (sort(keys(%{$serverhomes}))) {
 6188:                 unless ($excluded{$name}) {
 6189:                     if (exists($altids->{$serverhomes->{$name}})) {
 6190:                         push(@choices,$altids->{$serverhomes->{$name}});
 6191:                     } else {
 6192:                         push(@choices,$serverhomes->{$name});
 6193:                     }
 6194:                 }
 6195:             }
 6196:         }
 6197:     }
 6198:     return sort(@choices);
 6199: }
 6200: 
 6201: sub print_loadbalancing {
 6202:     my ($dom,$settings,$rowtotal) = @_;
 6203:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
 6204:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
 6205:     my $numinrow = 1;
 6206:     my $datatable;
 6207:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 6208:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
 6209:     if (ref($settings) eq 'HASH') {
 6210:         %existing = %{$settings};
 6211:     }
 6212:     if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
 6213:         &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
 6214:                                   \%currtargets,\%currrules,\%currcookies);
 6215:     } else {
 6216:         return;
 6217:     }
 6218:     my ($othertitle,$usertypes,$types) =
 6219:         &Apache::loncommon::sorted_inst_types($dom);
 6220:     my $rownum = 8;
 6221:     if (ref($types) eq 'ARRAY') {
 6222:         $rownum += scalar(@{$types});
 6223:     }
 6224:     my @css_class = ('LC_odd_row','LC_even_row');
 6225:     my $balnum = 0;
 6226:     my $islast;
 6227:     my (@toshow,$disabledtext);
 6228:     if (keys(%currbalancer) > 0) {
 6229:         @toshow = sort(keys(%currbalancer));
 6230:         if (scalar(@toshow) < scalar(keys(%servers)) + 1) {
 6231:             push(@toshow,'');
 6232:         }
 6233:     } else {
 6234:         @toshow = ('');
 6235:         $disabledtext = &mt('No existing load balancer');
 6236:     }
 6237:     foreach my $lonhost (@toshow) {
 6238:         if ($balnum == scalar(@toshow)-1) {
 6239:             $islast = 1;
 6240:         } else {
 6241:             $islast = 0;
 6242:         }
 6243:         my $cssidx = $balnum%2;
 6244:         my $targets_div_style = 'display: none';
 6245:         my $disabled_div_style = 'display: block';
 6246:         my $homedom_div_style = 'display: none';
 6247:         $datatable .= '<tr class="'.$css_class[$cssidx].'">'.
 6248:                       '<td rowspan="'.$rownum.'" valign="top">'.
 6249:                       '<p>';
 6250:         if ($lonhost eq '') {
 6251:             $datatable .= '<span class="LC_nobreak">';
 6252:             if (keys(%currbalancer) > 0) {
 6253:                 $datatable .= &mt('Add balancer:');
 6254:             } else {
 6255:                 $datatable .= &mt('Enable balancer:');
 6256:             }
 6257:             $datatable .= '&nbsp;'.
 6258:                           '<select name="loadbalancing_lonhost_'.$balnum.'"'.
 6259:                           ' id="loadbalancing_lonhost_'.$balnum.'"'.
 6260:                           ' onchange="toggleTargets('."'$balnum'".');">'."\n".
 6261:                           '<option value="" selected="selected">'.&mt('None').
 6262:                           '</option>'."\n";
 6263:             foreach my $server (sort(keys(%servers))) {
 6264:                 next if ($currbalancer{$server});
 6265:                 $datatable .= '<option value="'.$server.'">'.$server.'</option>'."\n";
 6266:             }
 6267:             $datatable .=
 6268:                 '</select>'."\n".
 6269:                 '<input type="hidden" name="loadbalancing_prevlonhost_'.$balnum.'" id="loadbalancing_prevlonhost_'.$balnum.'" value="" />&nbsp;</span>'."\n";
 6270:         } else {
 6271:             $datatable .= '<i>'.$lonhost.'</i><br /><span class="LC_nobreak">'.
 6272:                           '<label><input type="checkbox" name="loadbalancing_delete" value="'.$balnum.'" id="loadbalancing_delete_'.$balnum.'" onclick="javascript:balancerDeleteChange('."'$balnum'".');" />&nbsp;'.
 6273:                            &mt('Stop balancing').'</label>'.
 6274:                            '<input type="hidden" name="loadbalancing_lonhost_'.$balnum.'" value="'.$lonhost.'" id="loadbalancing_lonhost_'.$balnum.'" /></span>';
 6275:             $targets_div_style = 'display: block';
 6276:             $disabled_div_style = 'display: none';
 6277:             if ($dom eq &Apache::lonnet::host_domain($lonhost)) {
 6278:                 $homedom_div_style = 'display: block';
 6279:             }
 6280:         }
 6281:         $datatable .= '</p></td><td rowspan="'.$rownum.'" valign="top">'.
 6282:                   '<div id="loadbalancing_disabled_'.$balnum.'" style="'.
 6283:                   $disabled_div_style.'">'.$disabledtext.'</div>'."\n".
 6284:                   '<div id="loadbalancing_targets_'.$balnum.'" style="'.$targets_div_style.'">'.&mt('Offloads to:').'<br />';
 6285:         my ($numspares,@spares) = &count_servers($lonhost,%servers);
 6286:         my @sparestypes = ('primary','default');
 6287:         my %typetitles = &sparestype_titles();
 6288:         my %hostherechecked = (
 6289:                                   no => ' checked="checked"',
 6290:                               );
 6291:         my %balcookiechecked = (
 6292:                                   no => ' checked="checked"',
 6293:                                );
 6294:         foreach my $sparetype (@sparestypes) {
 6295:             my $targettable;
 6296:             for (my $i=0; $i<$numspares; $i++) {
 6297:                 my $checked;
 6298:                 if (ref($currtargets{$lonhost}) eq 'HASH') {
 6299:                     if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 6300:                         if (grep(/^\Q$spares[$i]\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 6301:                             $checked = ' checked="checked"';
 6302:                         }
 6303:                     }
 6304:                 }
 6305:                 my ($chkboxval,$disabled);
 6306:                 if (($lonhost ne '') && (exists($servers{$lonhost}))) {
 6307:                     $chkboxval = $spares[$i];
 6308:                 }
 6309:                 if (exists($currbalancer{$spares[$i]})) {
 6310:                     $disabled = ' disabled="disabled"';
 6311:                 }
 6312:                 $targettable .=
 6313:                     '<td><span class="LC_nobreak"><label>'.
 6314:                     '<input type="checkbox" name="loadbalancing_target_'.$balnum.'_'.$sparetype.'"'.
 6315:                     $checked.$disabled.' value="'.$chkboxval.'" id="loadbalancing_target_'.$balnum.'_'.$sparetype.'_'.$i.'" onclick="checkOffloads('."this,'$balnum','$sparetype'".');" /><span id="loadbalancing_targettxt_'.$balnum.'_'.$sparetype.'_'.$i.'">&nbsp;'.$chkboxval.
 6316:                     '</span></label></span></td>';
 6317:                 my $rem = $i%($numinrow);
 6318:                 if ($rem == 0) {
 6319:                     if (($i > 0) && ($i < $numspares-1)) {
 6320:                         $targettable .= '</tr>';
 6321:                     }
 6322:                     if ($i < $numspares-1) {
 6323:                         $targettable .= '<tr>';
 6324:                     }
 6325:                 }
 6326:             }
 6327:             if ($targettable ne '') {
 6328:                 my $rem = $numspares%($numinrow);
 6329:                 my $colsleft = $numinrow - $rem;
 6330:                 if ($colsleft > 1 ) {
 6331:                     $targettable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 6332:                                     '&nbsp;</td>';
 6333:                 } elsif ($colsleft == 1) {
 6334:                     $targettable .= '<td class="LC_left_item">&nbsp;</td>';
 6335:                 }
 6336:                 $datatable .=  '<i>'.$typetitles{$sparetype}.'</i><br />'.
 6337:                                '<table><tr>'.$targettable.'</tr></table><br />';
 6338:             }
 6339:             $hostherechecked{$sparetype} = '';
 6340:             if (ref($currtargets{$lonhost}) eq 'HASH') {
 6341:                 if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 6342:                     if (grep(/^\Q$lonhost\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 6343:                         $hostherechecked{$sparetype} = ' checked="checked"';
 6344:                         $hostherechecked{'no'} = '';
 6345:                     }
 6346:                 }
 6347:             }
 6348:         }
 6349:         if ($currcookies{$lonhost}) {
 6350:             %balcookiechecked = (
 6351:                                     yes => ' checked="checked"',
 6352:                                 );
 6353:         }
 6354:         $datatable .= &mt('Hosting on balancer itself').'<br />'.
 6355:                       '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" value="no"'.
 6356:                       $hostherechecked{'no'}.' />'.&mt('No').'</label><br />';
 6357:         foreach my $sparetype (@sparestypes) {
 6358:             $datatable .= '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" '.
 6359:                           'value="'.$sparetype.'"'.$hostherechecked{$sparetype}.' /><i>'.$typetitles{$sparetype}.
 6360:                           '</i></label><br />';
 6361:         }
 6362:         $datatable .= &mt('Use balancer cookie').'<br />'.
 6363:                       '<label><input type="radio" name="loadbalancing_cookie_'.$balnum.'" value="1"'.
 6364:                       $balcookiechecked{'yes'}.' />'.&mt('Yes').'</label><br />'.
 6365:                       '<label><input type="radio" name="loadbalancing_cookie_'.$balnum.'" value="0"'.
 6366:                       $balcookiechecked{'no'}.' />'.&mt('No').'</label><br />'.
 6367:                       '</div></td></tr>'.
 6368:                       &loadbalancing_rules($dom,$intdom,$currrules{$lonhost},
 6369:                                            $othertitle,$usertypes,$types,\%servers,
 6370:                                            \%currbalancer,$lonhost,
 6371:                                            $targets_div_style,$homedom_div_style,
 6372:                                            $css_class[$cssidx],$balnum,$islast);
 6373:         $$rowtotal += $rownum;
 6374:         $balnum ++;
 6375:     }
 6376:     $datatable .= '<input type="hidden" name="loadbalancing_total" id="loadbalancing_total" value="'.$balnum.'" />';
 6377:     return $datatable;
 6378: }
 6379: 
 6380: sub get_loadbalancers_config {
 6381:     my ($servers,$existing,$currbalancer,$currtargets,$currrules,$currcookies) = @_;
 6382:     return unless ((ref($servers) eq 'HASH') &&
 6383:                    (ref($existing) eq 'HASH') && (ref($currbalancer) eq 'HASH') &&
 6384:                    (ref($currtargets) eq 'HASH') && (ref($currrules) eq 'HASH') &&
 6385:                    (ref($currcookies) eq 'HASH'));
 6386:     if (keys(%{$existing}) > 0) {
 6387:         my $oldlonhost;
 6388:         foreach my $key (sort(keys(%{$existing}))) {
 6389:             if ($key eq 'lonhost') {
 6390:                 $oldlonhost = $existing->{'lonhost'};
 6391:                 $currbalancer->{$oldlonhost} = 1;
 6392:             } elsif ($key eq 'targets') {
 6393:                 if ($oldlonhost) {
 6394:                     $currtargets->{$oldlonhost} = $existing->{'targets'};
 6395:                 }
 6396:             } elsif ($key eq 'rules') {
 6397:                 if ($oldlonhost) {
 6398:                     $currrules->{$oldlonhost} = $existing->{'rules'};
 6399:                 }
 6400:             } elsif (ref($existing->{$key}) eq 'HASH') {
 6401:                 $currbalancer->{$key} = 1;
 6402:                 $currtargets->{$key} = $existing->{$key}{'targets'};
 6403:                 $currrules->{$key} = $existing->{$key}{'rules'};
 6404:                 if ($existing->{$key}{'cookie'}) {
 6405:                     $currcookies->{$key} = 1;
 6406:                 }
 6407:             }
 6408:         }
 6409:     } else {
 6410:         my ($balancerref,$targetsref) =
 6411:                 &Apache::lonnet::get_lonbalancer_config($servers);
 6412:         if ((ref($balancerref) eq 'HASH') && (ref($targetsref) eq 'HASH')) {
 6413:             foreach my $server (sort(keys(%{$balancerref}))) {
 6414:                 $currbalancer->{$server} = 1;
 6415:                 $currtargets->{$server} = $targetsref->{$server};
 6416:             }
 6417:         }
 6418:     }
 6419:     return;
 6420: }
 6421: 
 6422: sub loadbalancing_rules {
 6423:     my ($dom,$intdom,$currrules,$othertitle,$usertypes,$types,$servers,
 6424:         $currbalancer,$lonhost,$targets_div_style,$homedom_div_style,
 6425:         $css_class,$balnum,$islast) = @_;
 6426:     my $output;
 6427:     my $num = 0;
 6428:     my ($alltypes,$othertypes,$titles) =
 6429:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
 6430:     if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH'))  {
 6431:         foreach my $type (@{$alltypes}) {
 6432:             $num ++;
 6433:             my $current;
 6434:             if (ref($currrules) eq 'HASH') {
 6435:                 $current = $currrules->{$type};
 6436:             }
 6437:             if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 6438:                 if ($dom ne &Apache::lonnet::host_domain($lonhost)) {
 6439:                     $current = '';
 6440:                 }
 6441:             }
 6442:             $output .= &loadbalance_rule_row($type,$titles->{$type},$current,
 6443:                                              $servers,$currbalancer,$lonhost,$dom,
 6444:                                              $targets_div_style,$homedom_div_style,
 6445:                                              $css_class,$balnum,$num,$islast);
 6446:         }
 6447:     }
 6448:     return $output;
 6449: }
 6450: 
 6451: sub loadbalancing_titles {
 6452:     my ($dom,$intdom,$usertypes,$types) = @_;
 6453:     my %othertypes = (
 6454:            '_LC_adv'         => &mt('Advanced users from [_1]',$dom),
 6455:            '_LC_author'      => &mt('Users from [_1] with author role',$dom),
 6456:            '_LC_internetdom' => &mt('Users not from [_1], but from [_2]',$dom,$intdom),
 6457:            '_LC_external'    => &mt('Users not from [_1]',$intdom),
 6458:            '_LC_ipchangesso' => &mt('SSO users from [_1], with IP mismatch',$dom),
 6459:            '_LC_ipchange'    => &mt('Non-SSO users with IP mismatch'),
 6460:                      );
 6461:     my @alltypes = ('_LC_adv','_LC_author','_LC_internetdom','_LC_external','_LC_ipchangesso','_LC_ipchange');
 6462:     my @available;
 6463:     if (ref($types) eq 'ARRAY') {
 6464:         @available = @{$types};
 6465:     }
 6466:     unless (grep(/^default$/,@available)) {
 6467:         push(@available,'default');
 6468:     }
 6469:     unshift(@alltypes,@available);
 6470:     my %titles;
 6471:     foreach my $type (@alltypes) {
 6472:         if ($type =~ /^_LC_/) {
 6473:             $titles{$type} = $othertypes{$type};
 6474:         } elsif ($type eq 'default') {
 6475:             $titles{$type} = &mt('All users from [_1]',$dom);
 6476:             if (ref($types) eq 'ARRAY') {
 6477:                 if (@{$types} > 0) {
 6478:                     $titles{$type} = &mt('Other users from [_1]',$dom);
 6479:                 }
 6480:             }
 6481:         } elsif (ref($usertypes) eq 'HASH') {
 6482:             $titles{$type} = $usertypes->{$type};
 6483:         }
 6484:     }
 6485:     return (\@alltypes,\%othertypes,\%titles);
 6486: }
 6487: 
 6488: sub loadbalance_rule_row {
 6489:     my ($type,$title,$current,$servers,$currbalancer,$lonhost,$dom,
 6490:         $targets_div_style,$homedom_div_style,$css_class,$balnum,$num,$islast) = @_;
 6491:     my @rulenames;
 6492:     my %ruletitles = &offloadtype_text();
 6493:     if (($type eq '_LC_ipchangesso') || ($type eq '_LC_ipchange')) {
 6494:         @rulenames = ('balancer','offloadedto','specific');
 6495:     } else {
 6496:         @rulenames = ('default','homeserver');
 6497:         if ($type eq '_LC_external') {
 6498:             push(@rulenames,'externalbalancer');
 6499:         } else {
 6500:             push(@rulenames,'specific');
 6501:         }
 6502:         push(@rulenames,'none');
 6503:     }
 6504:     my $style = $targets_div_style;
 6505:     if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 6506:         $style = $homedom_div_style;
 6507:     }
 6508:     my $space;
 6509:     if ($islast && $num == 1) {
 6510:         $space = '<div display="inline-block">&nbsp;</div>';
 6511:     }
 6512:     my $output =
 6513:         '<tr class="'.$css_class.'" id="balanceruletr_'.$balnum.'_'.$num.'"><td valign="top">'.$space.
 6514:         '<div id="balanceruletitle_'.$balnum.'_'.$type.'" style="'.$style.'">'.$title.'</div></td>'."\n".
 6515:         '<td valaign="top">'.$space.
 6516:         '<div id="balancerule_'.$balnum.'_'.$type.'" style="'.$style.'">'."\n";
 6517:     for (my $i=0; $i<@rulenames; $i++) {
 6518:         my $rule = $rulenames[$i];
 6519:         my ($checked,$extra);
 6520:         if ($rulenames[$i] eq 'default') {
 6521:             $rule = '';
 6522:         }
 6523:         if ($rulenames[$i] eq 'specific') {
 6524:             if (ref($servers) eq 'HASH') {
 6525:                 my $default;
 6526:                 if (($current ne '') && (exists($servers->{$current}))) {
 6527:                     $checked = ' checked="checked"';
 6528:                 }
 6529:                 unless ($checked) {
 6530:                     $default = ' selected="selected"';
 6531:                 }
 6532:                 $extra =
 6533:                     ':&nbsp;<select name="loadbalancing_singleserver_'.$balnum.'_'.$type.
 6534:                     '" id="loadbalancing_singleserver_'.$balnum.'_'.$type.
 6535:                     '" onchange="singleServerToggle('."'$balnum','$type'".')">'."\n".
 6536:                     '<option value=""'.$default.'></option>'."\n";
 6537:                 foreach my $server (sort(keys(%{$servers}))) {
 6538:                     if (ref($currbalancer) eq 'HASH') {
 6539:                         next if (exists($currbalancer->{$server}));
 6540:                     }
 6541:                     my $selected;
 6542:                     if ($server eq $current) {
 6543:                         $selected = ' selected="selected"';
 6544:                     }
 6545:                     $extra .= '<option value="'.$server.'"'.$selected.'>'.$server.'</option>';
 6546:                 }
 6547:                 $extra .= '</select>';
 6548:             }
 6549:         } elsif ($rule eq $current) {
 6550:             $checked = ' checked="checked"';
 6551:         }
 6552:         $output .= '<span class="LC_nobreak"><label>'.
 6553:                    '<input type="radio" name="loadbalancing_rules_'.$balnum.'_'.$type.
 6554:                    '" id="loadbalancing_rules_'.$balnum.'_'.$type.'_'.$i.'" value="'.
 6555:                    $rule.'" onclick="balanceruleChange('."this.form,'$balnum','$type'".
 6556:                    ')"'.$checked.' />&nbsp;';
 6557:         if (($rulenames[$i] eq 'specific') && ($type =~ /^_LC_ipchange/)) {
 6558:             $output .= $ruletitles{'particular'};
 6559:         } else {
 6560:             $output .= $ruletitles{$rulenames[$i]};
 6561:         }
 6562:         $output .= '</label>'.$extra.'</span><br />'."\n";
 6563:     }
 6564:     $output .= '</div></td></tr>'."\n";
 6565:     return $output;
 6566: }
 6567: 
 6568: sub offloadtype_text {
 6569:     my %ruletitles = &Apache::lonlocal::texthash (
 6570:            'default'          => 'Offloads to default destinations',
 6571:            'homeserver'       => "Offloads to user's home server",
 6572:            'externalbalancer' => "Offloads to Load Balancer in user's domain",
 6573:            'specific'         => 'Offloads to specific server',
 6574:            'none'             => 'No offload',
 6575:            'balancer'         => 'Session hosted on Load Balancer, after re-authentication',
 6576:            'offloadedto'      => 'Session hosted on offload server, after re-authentication',
 6577:            'particular'       => 'Session hosted (after re-auth) on server:',
 6578:     );
 6579:     return %ruletitles;
 6580: }
 6581: 
 6582: sub sparestype_titles {
 6583:     my %typestitles = &Apache::lonlocal::texthash (
 6584:                           'primary' => 'primary',
 6585:                           'default' => 'default',
 6586:                       );
 6587:     return %typestitles;
 6588: }
 6589: 
 6590: sub contact_titles {
 6591:     my %titles = &Apache::lonlocal::texthash (
 6592:                    'supportemail'    => 'Support E-mail address',
 6593:                    'adminemail'      => 'Default Server Admin E-mail address',
 6594:                    'errormail'       => 'Error reports to be e-mailed to',
 6595:                    'packagesmail'    => 'Package update alerts to be e-mailed to',
 6596:                    'helpdeskmail'    => "Helpdesk requests from all users in this domain",
 6597:                    'otherdomsmail'   => 'Helpdesk requests from users in other (unconfigured) domains',
 6598:                    'lonstatusmail'   => 'E-mail from nightly status check (warnings/errors)',
 6599:                    'requestsmail'    => 'E-mail from course requests requiring approval',
 6600:                    'updatesmail'     => 'E-mail from nightly check of LON-CAPA module integrity/updates',
 6601:                    'idconflictsmail' => 'E-mail from bi-nightly check for multiple users sharing same student/employee ID',
 6602:                    'hostipmail'      => 'E-mail from nightly check of hostname/IP network changes',
 6603:                    'errorthreshold'  => 'Error count threshold for status e-mail to admin(s)',
 6604:                    'errorsysmail'    => 'Error count threshold for e-mail to developer group',
 6605:                    'errorweights'    => 'Weights used to compute error count',
 6606:                    'errorexcluded'   => 'Servers with unsent updates excluded from count',
 6607:                  );
 6608:     my %short_titles = &Apache::lonlocal::texthash (
 6609:                            adminemail   => 'Admin E-mail address',
 6610:                            supportemail => 'Support E-mail',
 6611:                        );   
 6612:     return (\%titles,\%short_titles);
 6613: }
 6614: 
 6615: sub helpform_fields {
 6616:     my %titles =  &Apache::lonlocal::texthash (
 6617:                        'username'   => 'Name',
 6618:                        'user'       => 'Username/domain',
 6619:                        'phone'      => 'Phone',
 6620:                        'cc'         => 'Cc e-mail',
 6621:                        'course'     => 'Course Details',
 6622:                        'section'    => 'Sections',
 6623:                        'screenshot' => 'File upload',
 6624:     );
 6625:     my @fields = ('username','phone','user','course','section','cc','screenshot');
 6626:     my %possoptions = (
 6627:                         username     => ['yes','no','req'],
 6628:                         phone        => ['yes','no','req'],
 6629:                         user         => ['yes','no'],
 6630:                         cc           => ['yes','no'],
 6631:                         course       => ['yes','no'],
 6632:                         section      => ['yes','no'],
 6633:                         screenshot   => ['yes','no'],
 6634:                       );
 6635:     my %fieldoptions = &Apache::lonlocal::texthash (
 6636:                          'yes'  => 'Optional',
 6637:                          'req'  => 'Required',
 6638:                          'no'   => "Not shown",
 6639:     );
 6640:     return (\@fields,\%titles,\%fieldoptions,\%possoptions);
 6641: }
 6642: 
 6643: sub tool_titles {
 6644:     my %titles = &Apache::lonlocal::texthash (
 6645:                      aboutme    => 'Personal web page',
 6646:                      blog       => 'Blog',
 6647:                      webdav     => 'WebDAV',
 6648:                      portfolio  => 'Portfolio',
 6649:                      official   => 'Official courses (with institutional codes)',
 6650:                      unofficial => 'Unofficial courses',
 6651:                      community  => 'Communities',
 6652:                      textbook   => 'Textbook courses',
 6653:                  );
 6654:     return %titles;
 6655: }
 6656: 
 6657: sub courserequest_titles {
 6658:     my %titles = &Apache::lonlocal::texthash (
 6659:                                    official   => 'Official',
 6660:                                    unofficial => 'Unofficial',
 6661:                                    community  => 'Communities',
 6662:                                    textbook   => 'Textbook',
 6663:                                    norequest  => 'Not allowed',
 6664:                                    approval   => 'Approval by Dom. Coord.',
 6665:                                    validate   => 'With validation',
 6666:                                    autolimit  => 'Numerical limit',
 6667:                                    unlimited  => '(blank for unlimited)',
 6668:                  );
 6669:     return %titles;
 6670: }
 6671: 
 6672: sub authorrequest_titles {
 6673:     my %titles = &Apache::lonlocal::texthash (
 6674:                                    norequest  => 'Not allowed',
 6675:                                    approval   => 'Approval by Dom. Coord.',
 6676:                                    automatic  => 'Automatic approval',
 6677:                  );
 6678:     return %titles;
 6679: }
 6680: 
 6681: sub courserequest_conditions {
 6682:     my %conditions = &Apache::lonlocal::texthash (
 6683:        approval    => '(Processing of request subject to approval by Domain Coordinator).',
 6684:        validate   => '(Processing of request subject to institutional validation).',
 6685:                  );
 6686:     return %conditions;
 6687: }
 6688: 
 6689: 
 6690: sub print_usercreation {
 6691:     my ($position,$dom,$settings,$rowtotal) = @_;
 6692:     my $numinrow = 4;
 6693:     my $datatable;
 6694:     if ($position eq 'top') {
 6695:         $$rowtotal ++;
 6696:         my $rowcount = 0;
 6697:         my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($dom,'username');
 6698:         if (ref($rules) eq 'HASH') {
 6699:             if (keys(%{$rules}) > 0) {
 6700:                 $datatable .= &user_formats_row('username',$settings,$rules,
 6701:                                                 $ruleorder,$numinrow,$rowcount);
 6702:                 $$rowtotal ++;
 6703:                 $rowcount ++;
 6704:             }
 6705:         }
 6706:         my ($idrules,$idruleorder) = &Apache::lonnet::inst_userrules($dom,'id');
 6707:         if (ref($idrules) eq 'HASH') {
 6708:             if (keys(%{$idrules}) > 0) {
 6709:                 $datatable .= &user_formats_row('id',$settings,$idrules,
 6710:                                                 $idruleorder,$numinrow,$rowcount);
 6711:                 $$rowtotal ++;
 6712:                 $rowcount ++;
 6713:             }
 6714:         }
 6715:         if ($rowcount == 0) {
 6716:             $datatable .= '<tr><td colspan="2">'.&mt('No format rules have been defined for usernames or IDs in this domain.').'</td></tr>';  
 6717:             $$rowtotal ++;
 6718:             $rowcount ++;
 6719:         }
 6720:     } elsif ($position eq 'middle') {
 6721:         my @creators = ('author','course','requestcrs');
 6722:         my ($rules,$ruleorder) =
 6723:             &Apache::lonnet::inst_userrules($dom,'username');
 6724:         my %lt = &usercreation_types();
 6725:         my %checked;
 6726:         if (ref($settings) eq 'HASH') {
 6727:             if (ref($settings->{'cancreate'}) eq 'HASH') {
 6728:                 foreach my $item (@creators) {
 6729:                     $checked{$item} = $settings->{'cancreate'}{$item};
 6730:                 }
 6731:             } elsif (ref($settings->{'cancreate'}) eq 'ARRAY') {
 6732:                 foreach my $item (@creators) {
 6733:                     if (grep(/^\Q$item\E$/,@{$settings->{'cancreate'}})) {
 6734:                         $checked{$item} = 'none';
 6735:                     }
 6736:                 }
 6737:             }
 6738:         }
 6739:         my $rownum = 0;
 6740:         foreach my $item (@creators) {
 6741:             $rownum ++;
 6742:             if ($checked{$item} eq '') {
 6743:                 $checked{$item} = 'any';
 6744:             }
 6745:             my $css_class;
 6746:             if ($rownum%2) {
 6747:                 $css_class = '';
 6748:             } else {
 6749:                 $css_class = ' class="LC_odd_row" ';
 6750:             }
 6751:             $datatable .= '<tr'.$css_class.'>'.
 6752:                          '<td><span class="LC_nobreak">'.$lt{$item}.
 6753:                          '</span></td><td align="right">';
 6754:             my @options = ('any');
 6755:             if (ref($rules) eq 'HASH') {
 6756:                 if (keys(%{$rules}) > 0) {
 6757:                     push(@options,('official','unofficial'));
 6758:                 }
 6759:             }
 6760:             push(@options,'none');
 6761:             foreach my $option (@options) {
 6762:                 my $type = 'radio';
 6763:                 my $check = ' ';
 6764:                 if ($checked{$item} eq $option) {
 6765:                     $check = ' checked="checked" ';
 6766:                 } 
 6767:                 $datatable .= '<span class="LC_nobreak"><label>'.
 6768:                               '<input type="'.$type.'" name="can_createuser_'.
 6769:                               $item.'" value="'.$option.'"'.$check.'/>&nbsp;'.
 6770:                               $lt{$option}.'</label>&nbsp;&nbsp;</span>';
 6771:             }
 6772:             $datatable .= '</td></tr>';
 6773:         }
 6774:     } else {
 6775:         my @contexts = ('author','course','domain');
 6776:         my @authtypes = ('int','krb4','krb5','loc');
 6777:         my %checked;
 6778:         if (ref($settings) eq 'HASH') {
 6779:             if (ref($settings->{'authtypes'}) eq 'HASH') {
 6780:                 foreach my $item (@contexts) {
 6781:                     if (ref($settings->{'authtypes'}{$item}) eq 'HASH') {
 6782:                         foreach my $auth (@authtypes) {
 6783:                             if ($settings->{'authtypes'}{$item}{$auth}) {
 6784:                                 $checked{$item}{$auth} = ' checked="checked" ';
 6785:                             }
 6786:                         }
 6787:                     }
 6788:                 }
 6789:             }
 6790:         } else {
 6791:             foreach my $item (@contexts) {
 6792:                 foreach my $auth (@authtypes) {
 6793:                     $checked{$item}{$auth} = ' checked="checked" ';
 6794:                 }
 6795:             }
 6796:         }
 6797:         my %title = &context_names();
 6798:         my %authname = &authtype_names();
 6799:         my $rownum = 0;
 6800:         my $css_class; 
 6801:         foreach my $item (@contexts) {
 6802:             if ($rownum%2) {
 6803:                 $css_class = '';
 6804:             } else {
 6805:                 $css_class = ' class="LC_odd_row" ';
 6806:             }
 6807:             $datatable .=   '<tr'.$css_class.'>'.
 6808:                             '<td>'.$title{$item}.
 6809:                             '</td><td class="LC_left_item">'.
 6810:                             '<span class="LC_nobreak">';
 6811:             foreach my $auth (@authtypes) {
 6812:                 $datatable .= '<label>'. 
 6813:                               '<input type="checkbox" name="'.$item.'_auth" '.
 6814:                               $checked{$item}{$auth}.' value="'.$auth.'" />'.
 6815:                               $authname{$auth}.'</label>&nbsp;';
 6816:             }
 6817:             $datatable .= '</span></td></tr>';
 6818:             $rownum ++;
 6819:         }
 6820:         $$rowtotal += $rownum;
 6821:     }
 6822:     return $datatable;
 6823: }
 6824: 
 6825: sub print_selfcreation {
 6826:     my ($position,$dom,$settings,$rowtotal) = @_;
 6827:     my (@selfcreate,$createsettings,$processing,$emailoptions,$emailverified,
 6828:         $emaildomain,$datatable);
 6829:     if (ref($settings) eq 'HASH') {
 6830:         if (ref($settings->{'cancreate'}) eq 'HASH') {
 6831:             $createsettings = $settings->{'cancreate'};
 6832:             if (ref($createsettings) eq 'HASH') {
 6833:                 if (ref($createsettings->{'selfcreate'}) eq 'ARRAY') {
 6834:                     @selfcreate = @{$createsettings->{'selfcreate'}};
 6835:                 } elsif ($createsettings->{'selfcreate'} ne '') {
 6836:                     if ($settings->{'cancreate'}{'selfcreate'} eq 'any') {
 6837:                         @selfcreate = ('email','login','sso');
 6838:                     } elsif ($createsettings->{'selfcreate'} ne 'none') {
 6839:                         @selfcreate = ($createsettings->{'selfcreate'});
 6840:                     }
 6841:                 }
 6842:                 if (ref($createsettings->{'selfcreateprocessing'}) eq 'HASH') {
 6843:                     $processing = $createsettings->{'selfcreateprocessing'};
 6844:                 }
 6845:                 if (ref($createsettings->{'emailoptions'}) eq 'HASH') {
 6846:                     $emailoptions = $createsettings->{'emailoptions'};
 6847:                 }
 6848:                 if (ref($createsettings->{'emailverified'}) eq 'HASH') {
 6849:                     $emailverified = $createsettings->{'emailverified'};
 6850:                 }
 6851:                 if (ref($createsettings->{'emaildomain'}) eq 'HASH') {
 6852:                     $emaildomain = $createsettings->{'emaildomain'};
 6853:                 }
 6854:             }
 6855:         }
 6856:     }
 6857:     my %radiohash;
 6858:     my $numinrow = 4;
 6859:     map { $radiohash{'cancreate_'.$_} = 1; } @selfcreate;
 6860:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 6861:     if ($position eq 'top') {
 6862:         my %choices = &Apache::lonlocal::texthash (
 6863:                                                       cancreate_login      => 'Institutional Login',
 6864:                                                       cancreate_sso        => 'Institutional Single Sign On',
 6865:                                                   );
 6866:         my @toggles = sort(keys(%choices));
 6867:         my %defaultchecked = (
 6868:                                'cancreate_login' => 'off',
 6869:                                'cancreate_sso'   => 'off',
 6870:                              );
 6871:         my ($onclick,$itemcount);
 6872:         ($datatable,$itemcount) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 6873:                                                      \%choices,$itemcount,$onclick);
 6874:         $$rowtotal += $itemcount;
 6875: 
 6876:         if (ref($usertypes) eq 'HASH') {
 6877:             if (keys(%{$usertypes}) > 0) {
 6878:                 $datatable .= &insttypes_row($createsettings,$types,$usertypes,
 6879:                                              $dom,$numinrow,$othertitle,
 6880:                                              'statustocreate',$rowtotal);
 6881:                 $$rowtotal ++;
 6882:             }
 6883:         }
 6884:         my @fields = ('lastname','firstname','middlename','permanentemail','id','inststatus');
 6885:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 6886:         $fieldtitles{'inststatus'} = &mt('Institutional status');
 6887:         my $rem;
 6888:         my $numperrow = 2;
 6889:         my $css_class = $$rowtotal%2?' class="LC_odd_row"':'';
 6890:         $datatable .= '<tr'.$css_class.'>'.
 6891:                      '<td class="LC_left_item">'.&mt('Mapping of Shibboleth environment variable names to user data fields (SSO auth)').'</td>'.
 6892:                      '<td class="LC_left_item">'."\n".
 6893:                      '<table>'."\n";
 6894:         for (my $i=0; $i<@fields; $i++) {
 6895:             $rem = $i%($numperrow);
 6896:             if ($rem == 0) {
 6897:                 if ($i > 0) {
 6898:                     $datatable .= '</tr>';
 6899:                 }
 6900:                 $datatable .= '<tr>';
 6901:             }
 6902:             my $currval;
 6903:             if (ref($createsettings) eq 'HASH') {
 6904:                 if (ref($createsettings->{'shibenv'}) eq 'HASH') {
 6905:                     $currval = $createsettings->{'shibenv'}{$fields[$i]};
 6906:                 }
 6907:             }
 6908:             $datatable .= '<td class="LC_left_item">'.
 6909:                           '<span class="LC_nobreak">'.
 6910:                           '<input type="text" name="shibenv_'.$fields[$i].'" '.
 6911:                           'value="'.$currval.'" size="10" />&nbsp;'.
 6912:                           $fieldtitles{$fields[$i]}.'</span></td>';
 6913:         }
 6914:         my $colsleft = $numperrow - $rem;
 6915:         if ($colsleft > 1 ) {
 6916:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 6917:                          '&nbsp;</td>';
 6918:         } elsif ($colsleft == 1) {
 6919:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 6920:         }
 6921:         $datatable .= '</tr></table></td></tr>';
 6922:         $$rowtotal ++;
 6923:     } elsif ($position eq 'middle') {
 6924:         my %domconf = &Apache::lonnet::get_dom('configuration',['usermodification'],$dom);
 6925:         my @posstypes;
 6926:         if (ref($types) eq 'ARRAY') {
 6927:             @posstypes = @{$types};
 6928:         }
 6929:         unless (grep(/^default$/,@posstypes)) {
 6930:             push(@posstypes,'default');
 6931:         }
 6932:         my %usertypeshash;
 6933:         if (ref($usertypes) eq 'HASH') {
 6934:             %usertypeshash = %{$usertypes};
 6935:         }
 6936:         $usertypeshash{'default'} = $othertitle;
 6937:         foreach my $status (@posstypes) {
 6938:             $datatable .= &modifiable_userdata_row('selfcreate',$status,$domconf{'usermodification'},
 6939:                                                    $numinrow,$$rowtotal,\%usertypeshash);
 6940:             $$rowtotal ++;
 6941:         }
 6942:     } else {
 6943:         my %choices = &Apache::lonlocal::texthash (
 6944:                           'cancreate_email' => 'Non-institutional username (via e-mail verification)',
 6945:                                                   );
 6946:         my @toggles = sort(keys(%choices));
 6947:         my %defaultchecked = (
 6948:                                'cancreate_email' => 'off',
 6949:                              );
 6950:         my $customclass = 'LC_selfcreate_email';
 6951:         my $classprefix = 'LC_canmodify_emailusername_';
 6952:         my $optionsprefix = 'LC_options_emailusername_';
 6953:         my $display = 'none';
 6954:         my $rowstyle = 'display:none';
 6955:         if (grep(/^\Qemail\E$/,@selfcreate)) {
 6956:             $display = 'block';
 6957:             $rowstyle = 'display:table-row';
 6958:         }
 6959:         my $onclick = "toggleRows(this.form,'cancreate_email','selfassign','$customclass','$classprefix','$optionsprefix');";
 6960:         ($datatable,$$rowtotal) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 6961:                                                      \%choices,$$rowtotal,$onclick);
 6962:         $datatable .= &print_requestmail($dom,'selfcreation',$createsettings,$rowtotal,$customclass,
 6963:                                          $rowstyle);
 6964:         $$rowtotal ++;
 6965:         $datatable .= &captcha_choice('cancreate',$createsettings,$$rowtotal,$customclass,
 6966:                                       $rowstyle);
 6967:         $$rowtotal ++;
 6968:         my (@ordered,@posstypes,%usertypeshash);
 6969:         my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
 6970:         my ($emailrules,$emailruleorder) =
 6971:             &Apache::lonnet::inst_userrules($dom,'email');
 6972:         my $primary_id = &Apache::lonnet::domain($dom,'primary');
 6973:         my $intdom = &Apache::lonnet::internet_dom($primary_id);
 6974:         if (ref($types) eq 'ARRAY') {
 6975:             @posstypes = @{$types};
 6976:         }
 6977:         if (@posstypes) {
 6978:             unless (grep(/^default$/,@posstypes)) {
 6979:                 push(@posstypes,'default');
 6980:             }
 6981:             if (ref($usertypes) eq 'HASH') {
 6982:                 %usertypeshash = %{$usertypes};
 6983:             }
 6984:             my $currassign;
 6985:             if (ref($domdefaults{'inststatusguest'}) eq 'ARRAY') {
 6986:                 $currassign = {
 6987:                                   selfassign => $domdefaults{'inststatusguest'},
 6988:                               };
 6989:                 @ordered = @{$domdefaults{'inststatusguest'}};
 6990:             } else {
 6991:                 $currassign = { selfassign => [] };
 6992:             }
 6993:             my $onclicktypes = "toggleDataRow(this.form,'selfassign','$customclass','$optionsprefix',);".
 6994:                                "toggleDataRow(this.form,'selfassign','$customclass','$classprefix',1);";
 6995:             $datatable .= &insttypes_row($currassign,$types,$usertypes,$dom,
 6996:                                          $numinrow,$othertitle,'selfassign',
 6997:                                          $rowtotal,$onclicktypes,$customclass,
 6998:                                          $rowstyle);
 6999:             $$rowtotal ++;
 7000:             $usertypeshash{'default'} = $othertitle;
 7001:             foreach my $status (@posstypes) {
 7002:                 my $css_class;
 7003:                 if ($$rowtotal%2) {
 7004:                     $css_class = 'LC_odd_row ';
 7005:                 }
 7006:                 $css_class .= $customclass;
 7007:                 my $rowid = $optionsprefix.$status;
 7008:                 my $hidden = 1;
 7009:                 my $currstyle = 'display:none';
 7010:                 if (grep(/^\Q$status\E$/,@ordered)) {
 7011:                     $currstyle = $rowstyle;
 7012:                     $hidden = 0;
 7013:                 }
 7014:                 $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
 7015:                                              $emailrules,$emailruleorder,$settings,$status,$rowid,
 7016:                                              $usertypeshash{$status},$css_class,$currstyle,$intdom);
 7017:                 unless ($hidden) {
 7018:                     $$rowtotal ++;
 7019:                 }
 7020:             }
 7021:         } else {
 7022:             my $css_class;
 7023:             if ($$rowtotal%2) {
 7024:                 $css_class = 'LC_odd_row ';
 7025:             }
 7026:             $css_class .= $customclass;
 7027:             $usertypeshash{'default'} = $othertitle;
 7028:             $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
 7029:                                          $emailrules,$emailruleorder,$settings,'default','',
 7030:                                          $othertitle,$css_class,$rowstyle,$intdom);
 7031:             $$rowtotal ++;
 7032:         }
 7033:         my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 7034:         $numinrow = 1;
 7035:         if (@posstypes) {
 7036:             foreach my $status (@posstypes) {
 7037:                 my $rowid = $classprefix.$status;
 7038:                 my $datarowstyle = 'display:none';
 7039:                 if (grep(/^\Q$status\E$/,@ordered)) {
 7040:                     $datarowstyle = $rowstyle;
 7041:                 }
 7042:                 $datatable .= &modifiable_userdata_row('cancreate','emailusername_'.$status,$settings,
 7043:                                                        $numinrow,$$rowtotal,\%usertypeshash,$infofields,
 7044:                                                        $infotitles,$rowid,$customclass,$datarowstyle);
 7045:                 unless ($datarowstyle eq 'display:none') {
 7046:                     $$rowtotal ++;
 7047:                 }
 7048:             }
 7049:         } else {
 7050:             $datatable .= &modifiable_userdata_row('cancreate','emailusername_default',$settings,
 7051:                                                    $numinrow,$$rowtotal,\%usertypeshash,$infofields,
 7052:                                                    $infotitles,'',$customclass,$rowstyle);
 7053:         }
 7054:     }
 7055:     return $datatable;
 7056: }
 7057: 
 7058: sub selfcreate_javascript {
 7059:     return <<"ENDSCRIPT";
 7060: 
 7061: <script type="text/javascript">
 7062: // <![CDATA[
 7063: 
 7064: function toggleRows(form,radio,checkbox,target,prefix,altprefix) {
 7065:     var x = document.getElementsByClassName(target);
 7066:     var insttypes = 0;
 7067:     var insttypeRegExp = new RegExp(prefix);
 7068:     if ((x.length != undefined) && (x.length > 0)) {
 7069:         if (form.elements[radio].length != undefined) {
 7070:             for (var i=0; i<form.elements[radio].length; i++) {
 7071:                 if (form.elements[radio][i].checked) {
 7072:                     if (form.elements[radio][i].value == 1) {
 7073:                         for (var j=0; j<x.length; j++) {
 7074:                             if (x[j].id == 'undefined') {
 7075:                                 x[j].style.display = 'table-row';
 7076:                             } else if (insttypeRegExp.test(x[j].id)) {
 7077:                                 insttypes ++;
 7078:                             } else {
 7079:                                 x[j].style.display = 'table-row';
 7080:                             }
 7081:                         }
 7082:                     } else {
 7083:                         for (var j=0; j<x.length; j++) {
 7084:                             x[j].style.display = 'none';
 7085:                         }
 7086:                     }
 7087:                     break;
 7088:                 }
 7089:             }
 7090:             if (insttypes > 0) {
 7091:                 toggleDataRow(form,checkbox,target,altprefix);
 7092:                 toggleDataRow(form,checkbox,target,prefix,1);
 7093:             }
 7094:         }
 7095:     }
 7096:     return;
 7097: }
 7098: 
 7099: function toggleDataRow(form,checkbox,target,prefix,docount) {
 7100:     if (form.elements[checkbox].length != undefined) {
 7101:         var count = 0;
 7102:         if (docount) {
 7103:             for (var i=0; i<form.elements[checkbox].length; i++) {
 7104:                 if (form.elements[checkbox][i].checked) {
 7105:                     count ++;
 7106:                 }
 7107:             }
 7108:         }
 7109:         for (var i=0; i<form.elements[checkbox].length; i++) {
 7110:             var type = form.elements[checkbox][i].value;
 7111:             if (document.getElementById(prefix+type)) {
 7112:                 if (form.elements[checkbox][i].checked) {
 7113:                     document.getElementById(prefix+type).style.display = 'table-row';
 7114:                     if (count % 2 == 1) {
 7115:                         document.getElementById(prefix+type).className = target+' LC_odd_row';
 7116:                     } else {
 7117:                         document.getElementById(prefix+type).className = target;
 7118:                     }
 7119:                     count ++;
 7120:                 } else {
 7121:                     document.getElementById(prefix+type).style.display = 'none';
 7122:                 }
 7123:             }
 7124:         }
 7125:     }
 7126:     return;
 7127: }
 7128: 
 7129: function toggleEmailOptions(form,radio,prefix,altprefix,status) {
 7130:     var caller = radio+'_'+status;
 7131:     if (form.elements[caller].length != undefined) {
 7132:         for (var i=0; i<form.elements[caller].length; i++) {
 7133:             if (form.elements[caller][i].checked) {
 7134:                 if (document.getElementById(altprefix+'_inst_'+status)) {
 7135:                     var curr = form.elements[caller][i].value;
 7136:                     if (prefix) {
 7137:                         document.getElementById(prefix+'_'+status).style.display = 'none';
 7138:                     }
 7139:                     document.getElementById(altprefix+'_inst_'+status).style.display = 'none';
 7140:                     document.getElementById(altprefix+'_noninst_'+status).style.display = 'none';
 7141:                     if (curr == 'custom') {
 7142:                         if (prefix) {
 7143:                             document.getElementById(prefix+'_'+status).style.display = 'inline';
 7144:                         }
 7145:                     } else if (curr == 'inst') {
 7146:                         document.getElementById(altprefix+'_inst_'+status).style.display = 'inline';
 7147:                     } else if (curr == 'noninst') {
 7148:                         document.getElementById(altprefix+'_noninst_'+status).style.display = 'inline';
 7149:                     }
 7150:                     break;
 7151:                 }
 7152:             }
 7153:         }
 7154:     }
 7155: }
 7156: 
 7157: // ]]>
 7158: </script>
 7159: 
 7160: ENDSCRIPT
 7161: }
 7162: 
 7163: sub noninst_users {
 7164:     my ($processing,$emailverified,$emailoptions,$emaildomain,$emailrules,
 7165:         $emailruleorder,$settings,$type,$rowid,$typetitle,$css_class,$rowstyle,$intdom) = @_;
 7166:     my $class = 'LC_left_item';
 7167:     if ($css_class) {
 7168:         $css_class = ' class="'.$css_class.'"';
 7169:     }
 7170:     if ($rowid) {
 7171:         $rowid = ' id="'.$rowid.'"';
 7172:     }
 7173:     if ($rowstyle) {
 7174:         $rowstyle = ' style="'.$rowstyle.'"';
 7175:     }
 7176:     my ($output,$description);
 7177:     if ($type eq 'default') {
 7178:         $description = &mt('Requests for: [_1]',$typetitle);
 7179:     } else {
 7180:         $description = &mt('Requests for: [_1] (status self-reported)',$typetitle);
 7181:     }
 7182:     $output = '<tr'.$css_class.$rowid.$rowstyle.'>'.
 7183:               "<td>$description</td>\n".
 7184:               '<td class="'.$class.'" colspan="2">'.
 7185:               '<table><tr>';
 7186:     my %headers = &Apache::lonlocal::texthash(
 7187:               approve  => 'Processing',
 7188:               email    => 'E-mail',
 7189:               username => 'Username',
 7190:     );
 7191:     foreach my $item ('approve','email','username') {
 7192:         $output .= '<th>'.$headers{$item}.'</th>';
 7193:     }
 7194:     $output .= '</tr><tr>';
 7195:     foreach my $item ('approve','email','username') {
 7196:         $output .= '<td valign="top">';
 7197:         my (%choices,@options,$hashref,$defoption,$name,$onclick,$hascustom);
 7198:         if ($item eq 'approve') {
 7199:             %choices = &Apache::lonlocal::texthash (
 7200:                                                      automatic => 'Automatically approved',
 7201:                                                      approval  => 'Queued for approval',
 7202:                                                    );
 7203:             @options = ('automatic','approval');
 7204:             $hashref = $processing;
 7205:             $defoption = 'automatic';
 7206:             $name = 'cancreate_emailprocess_'.$type;
 7207:         } elsif ($item eq 'email') {
 7208:             %choices = &Apache::lonlocal::texthash (
 7209:                                                      any     => 'Any e-mail',
 7210:                                                      inst    => 'Institutional only',
 7211:                                                      noninst => 'Non-institutional only',
 7212:                                                      custom  => 'Custom restrictions',
 7213:                                                    );
 7214:             @options = ('any','inst','noninst');
 7215:             my $showcustom;
 7216:             if (ref($emailrules) eq 'HASH') {
 7217:                 if (keys(%{$emailrules}) > 0) {
 7218:                     push(@options,'custom');
 7219:                     $showcustom = 'cancreate_emailrule';
 7220:                     if (ref($settings) eq 'HASH') {
 7221:                         if (ref($settings->{'email_rule'}) eq 'ARRAY') {
 7222:                             foreach my $rule (@{$settings->{'email_rule'}}) {
 7223:                                 if (exists($emailrules->{$rule})) {
 7224:                                     $hascustom ++;
 7225:                                 }
 7226:                             }
 7227:                         } elsif (ref($settings->{'email_rule'}) eq 'HASH') {
 7228:                             if (ref($settings->{'email_rule'}{$type}) eq 'ARRAY') {
 7229:                                 foreach my $rule (@{$settings->{'email_rule'}{$type}}) {
 7230:                                     if (exists($emailrules->{$rule})) {
 7231:                                         $hascustom ++;
 7232:                                     }
 7233:                                 }
 7234:                             }
 7235:                         }
 7236:                     }
 7237:                 }
 7238:             }
 7239:             $onclick = ' onclick="toggleEmailOptions(this.form,'."'cancreate_emailoptions','$showcustom',".
 7240:                                                      "'cancreate_emaildomain','$type'".');"';
 7241:             $hashref = $emailoptions;
 7242:             $defoption = 'any';
 7243:             $name = 'cancreate_emailoptions_'.$type;
 7244:         } elsif ($item eq 'username') {
 7245:             %choices = &Apache::lonlocal::texthash (
 7246:                                                      all    => 'Same as e-mail',
 7247:                                                      first  => 'Omit @domain',
 7248:                                                      free   => 'Free to choose',
 7249:                                                    );
 7250:             @options = ('all','first','free');
 7251:             $hashref = $emailverified;
 7252:             $defoption = 'all';
 7253:             $name = 'cancreate_usernameoptions_'.$type;
 7254:         }
 7255:         foreach my $option (@options) {
 7256:             my $checked;
 7257:             if (ref($hashref) eq 'HASH') {
 7258:                 if ($type eq '') {
 7259:                     if (!exists($hashref->{'default'})) {
 7260:                         if ($option eq $defoption) {
 7261:                             $checked = ' checked="checked"';
 7262:                         }
 7263:                     } else {
 7264:                         if ($hashref->{'default'} eq $option) {
 7265:                             $checked = ' checked="checked"';
 7266:                         }
 7267:                     }
 7268:                 } else {
 7269:                     if (!exists($hashref->{$type})) {
 7270:                         if ($option eq $defoption) {
 7271:                             $checked = ' checked="checked"';
 7272:                         }
 7273:                     } else {
 7274:                         if ($hashref->{$type} eq $option) {
 7275:                             $checked = ' checked="checked"';
 7276:                         }
 7277:                     }
 7278:                 }
 7279:             } elsif (($item eq 'email') && ($hascustom)) {
 7280:                 if ($option eq 'custom') {
 7281:                     $checked = ' checked="checked"';
 7282:                 }
 7283:             } elsif ($option eq $defoption) {
 7284:                 $checked = ' checked="checked"';
 7285:             }
 7286:             $output .= '<span class="LC_nobreak"><label>'.
 7287:                        '<input type="radio" name="'.$name.'"'.
 7288:                        $checked.' value="'.$option.'"'.$onclick.' />'.
 7289:                        $choices{$option}.'</label></span><br />';
 7290:             if ($item eq 'email') {
 7291:                 if ($option eq 'custom') {
 7292:                     my $id = 'cancreate_emailrule_'.$type;
 7293:                     my $display = 'none';
 7294:                     if ($checked) {
 7295:                         $display = 'inline';
 7296:                     }
 7297:                     my $numinrow = 2;
 7298:                     $output .= '<fieldset id="'.$id.'" style="display:'.$display.';">'.
 7299:                                '<legend>'.&mt('Disallow').'</legend><table>'.
 7300:                                &user_formats_row('email',$settings,$emailrules,
 7301:                                                  $emailruleorder,$numinrow,'',$type);
 7302:                               '</table></fieldset>';
 7303:                 } elsif (($option eq 'inst') || ($option eq 'noninst')) {
 7304:                     my %text = &Apache::lonlocal::texthash (
 7305:                                                              inst    => 'must end:',
 7306:                                                              noninst => 'cannot end:',
 7307:                                                            );
 7308:                     my $value;
 7309:                     if (ref($emaildomain) eq 'HASH') {
 7310:                         if (ref($emaildomain->{$type}) eq 'HASH') {
 7311:                             $value = $emaildomain->{$type}->{$option};
 7312:                         }
 7313:                     }
 7314:                     if ($value eq '') {
 7315:                         $value = '@'.$intdom;
 7316:                     }
 7317:                     my $condition = 'cancreate_emaildomain_'.$option.'_'.$type;
 7318:                     my $display = 'none';
 7319:                     if ($checked) {
 7320:                         $display = 'inline';
 7321:                     }
 7322:                     $output .= '<div id="'.$condition.'" style="display:'.$display.';">'.
 7323:                                '<span class="LC_domprefs_email">'.$text{$option}.'</span> '.
 7324:                                '<input type="text" name="'.$condition.'" value="'.$value.'" size="10" />'.
 7325:                                '</div>';
 7326:                 }
 7327:             }
 7328:         }
 7329:         $output .= '</td>'."\n";
 7330:     }
 7331:     $output .= "</tr></table></td></tr>\n";
 7332:     return $output;
 7333: }
 7334: 
 7335: sub captcha_choice {
 7336:     my ($context,$settings,$itemcount,$customcss,$rowstyle) = @_;
 7337:     my ($keyentry,$currpub,$currpriv,%checked,$rowname,$pubtext,$privtext,
 7338:         $vertext,$currver); 
 7339:     my %lt = &captcha_phrases();
 7340:     $keyentry = 'hidden';
 7341:     my $colspan=2;
 7342:     if ($context eq 'cancreate') {
 7343:         $rowname = &mt('CAPTCHA validation');
 7344:     } elsif ($context eq 'login') {
 7345:         $rowname =  &mt('"Contact helpdesk" CAPTCHA validation');
 7346:     } elsif ($context eq 'passwords') {
 7347:         $rowname = &mt('"Forgot Password" CAPTCHA validation');
 7348:         $colspan=1;
 7349:     }
 7350:     if (ref($settings) eq 'HASH') {
 7351:         if ($settings->{'captcha'}) {
 7352:             $checked{$settings->{'captcha'}} = ' checked="checked"';
 7353:         } else {
 7354:             $checked{'original'} = ' checked="checked"';
 7355:         }
 7356:         if ($settings->{'captcha'} eq 'recaptcha') {
 7357:             $pubtext = $lt{'pub'};
 7358:             $privtext = $lt{'priv'};
 7359:             $keyentry = 'text';
 7360:             $vertext = $lt{'ver'};
 7361:             $currver = $settings->{'recaptchaversion'};
 7362:             if ($currver ne '2') {
 7363:                 $currver = 1;
 7364:             }
 7365:         }
 7366:         if (ref($settings->{'recaptchakeys'}) eq 'HASH') {
 7367:             $currpub = $settings->{'recaptchakeys'}{'public'};
 7368:             $currpriv = $settings->{'recaptchakeys'}{'private'};
 7369:         }
 7370:     } else {
 7371:         $checked{'original'} = ' checked="checked"';
 7372:     }
 7373:     my $css_class;
 7374:     if ($itemcount%2) {
 7375:         $css_class = 'LC_odd_row';
 7376:     }
 7377:     if ($customcss) {
 7378:         $css_class .= " $customcss";
 7379:     }
 7380:     $css_class =~ s/^\s+//;
 7381:     if ($css_class) {
 7382:         $css_class = ' class="'.$css_class.'"';
 7383:     }
 7384:     if ($rowstyle) {
 7385:         $css_class .= ' style="'.$rowstyle.'"';
 7386:     }
 7387:     my $output = '<tr'.$css_class.'>'.
 7388:                  '<td class="LC_left_item">'.$rowname.'</td><td class="LC_left_item" colspan="'.$colspan.'">'."\n".
 7389:                  '<table><tr><td>'."\n";
 7390:     foreach my $option ('original','recaptcha','notused') {
 7391:         $output .= '<span class="LC_nobreak"><label><input type="radio" name="'.$context.'_captcha" value="'.
 7392:                    $option.'" '.$checked{$option}.' onchange="javascript:updateCaptcha('."this,'$context'".');" />'.
 7393:                    $lt{$option}.'</label></span>';
 7394:         unless ($option eq 'notused') {
 7395:             $output .= ('&nbsp;'x2)."\n";
 7396:         }
 7397:     }
 7398: #
 7399: # Note: If reCAPTCHA is to be used for LON-CAPA servers in a domain, a domain coordinator should visit:
 7400: # https://www.google.com/recaptcha and generate a Public and Private key. For domains with multiple
 7401: # servers a single key pair will be used for all servers, so the internet domain (e.g., yourcollege.edu)
 7402: # specified for use with the key should be broad enough to accommodate all servers in the LON-CAPA domain.
 7403: #
 7404:     $output .= '</td></tr>'."\n".
 7405:                '<tr><td class="LC_zero_height">'."\n".
 7406:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchapubtxt">'.$pubtext.'</span>&nbsp;'."\n".
 7407:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapub" name="'.$context.'_recaptchapub" value="'.
 7408:                $currpub.'" size="40" /></span><br />'."\n".
 7409:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchaprivtxt">'.$privtext.'</span>&nbsp;'."\n".
 7410:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapriv" name="'.$context.'_recaptchapriv" value="'.
 7411:                $currpriv.'" size="40" /></span><br />'.
 7412:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchavertxt">'.$vertext.'</span>&nbsp;'."\n".
 7413:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchaversion" name="'.$context.'_recaptchaversion" value="'.
 7414:                $currver.'" size="3" /></span><br />'.
 7415:                '</td></tr></table>'."\n".
 7416:                '</td></tr>';
 7417:     return $output;
 7418: }
 7419: 
 7420: sub user_formats_row {
 7421:     my ($type,$settings,$rules,$ruleorder,$numinrow,$rowcount,$status) = @_;
 7422:     my $output;
 7423:     my %text = (
 7424:                    'username' => 'new usernames',
 7425:                    'id'       => 'IDs',
 7426:                );
 7427:     unless ($type eq 'email') {
 7428:         my $css_class = $rowcount%2?' class="LC_odd_row"':'';
 7429:         $output = '<tr '.$css_class.'>'.
 7430:                   '<td><span class="LC_nobreak">'.
 7431:                   &mt("Format rules to check for $text{$type}: ").
 7432:                   '</td><td class="LC_left_item" colspan="2"><table>';
 7433:     }
 7434:     my $rem;
 7435:     if (ref($ruleorder) eq 'ARRAY') {
 7436:         for (my $i=0; $i<@{$ruleorder}; $i++) {
 7437:             if (ref($rules->{$ruleorder->[$i]}) eq 'HASH') {
 7438:                 my $rem = $i%($numinrow);
 7439:                 if ($rem == 0) {
 7440:                     if ($i > 0) {
 7441:                         $output .= '</tr>';
 7442:                     }
 7443:                     $output .= '<tr>';
 7444:                 }
 7445:                 my $check = ' ';
 7446:                 if (ref($settings) eq 'HASH') {
 7447:                     if (ref($settings->{$type.'_rule'}) eq 'ARRAY') {
 7448:                         if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}})) {
 7449:                             $check = ' checked="checked" ';
 7450:                         }
 7451:                     } elsif ((ref($settings->{$type.'_rule'}) eq 'HASH') && ($status ne '')) {
 7452:                         if (ref($settings->{$type.'_rule'}->{$status}) eq 'ARRAY') {
 7453:                             if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}->{$status}})) {
 7454:                                 $check = ' checked="checked" ';
 7455:                             }
 7456:                         }
 7457:                     }
 7458:                 }
 7459:                 my $name = $type.'_rule';
 7460:                 if ($type eq 'email') {
 7461:                     $name .= '_'.$status;
 7462:                 }
 7463:                 $output .= '<td class="LC_left_item">'.
 7464:                            '<span class="LC_nobreak"><label>'.
 7465:                            '<input type="checkbox" name="'.$name.'" '.
 7466:                            'value="'.$ruleorder->[$i].'"'.$check.'/>'.
 7467:                            $rules->{$ruleorder->[$i]}{'name'}.'</label></span></td>';
 7468:             }
 7469:         }
 7470:         $rem = @{$ruleorder}%($numinrow);
 7471:     }
 7472:     my $colsleft;
 7473:     if ($rem) {
 7474:         $colsleft = $numinrow - $rem;
 7475:     }
 7476:     if ($colsleft > 1 ) {
 7477:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 7478:                    '&nbsp;</td>';
 7479:     } elsif ($colsleft == 1) {
 7480:         $output .= '<td class="LC_left_item">&nbsp;</td>';
 7481:     }
 7482:     $output .= '</tr></table>';
 7483:     unless ($type eq 'email') {
 7484:         $output .= '</td></tr>';
 7485:     }
 7486:     return $output;
 7487: }
 7488: 
 7489: sub usercreation_types {
 7490:     my %lt = &Apache::lonlocal::texthash (
 7491:                     author     => 'When adding a co-author',
 7492:                     course     => 'When adding a user to a course',
 7493:                     requestcrs => 'When requesting a course',
 7494:                     any        => 'Any',
 7495:                     official   => 'Institutional only ',
 7496:                     unofficial => 'Non-institutional only',
 7497:                     none       => 'None',
 7498:     );
 7499:     return %lt;
 7500: }
 7501: 
 7502: sub selfcreation_types {
 7503:     my %lt = &Apache::lonlocal::texthash (
 7504:                     selfcreate => 'User creates own account',
 7505:                     any        => 'Any',
 7506:                     official   => 'Institutional only ',
 7507:                     unofficial => 'Non-institutional only',
 7508:                     email      => 'E-mail address',
 7509:                     login      => 'Institutional Login',
 7510:                     sso        => 'SSO',
 7511:              );
 7512: }
 7513: 
 7514: sub authtype_names {
 7515:     my %lt = &Apache::lonlocal::texthash(
 7516:                       int    => 'Internal',
 7517:                       krb4   => 'Kerberos 4',
 7518:                       krb5   => 'Kerberos 5',
 7519:                       loc    => 'Local',
 7520:                   );
 7521:     return %lt;
 7522: }
 7523: 
 7524: sub context_names {
 7525:     my %context_title = &Apache::lonlocal::texthash(
 7526:        author => 'Creating users when an Author',
 7527:        course => 'Creating users when in a course',
 7528:        domain => 'Creating users when a Domain Coordinator',
 7529:     );
 7530:     return %context_title;
 7531: }
 7532: 
 7533: sub print_usermodification {
 7534:     my ($position,$dom,$settings,$rowtotal) = @_;
 7535:     my $numinrow = 4;
 7536:     my ($context,$datatable,$rowcount);
 7537:     if ($position eq 'top') {
 7538:         $rowcount = 0;
 7539:         $context = 'author'; 
 7540:         foreach my $role ('ca','aa') {
 7541:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
 7542:                                                    $numinrow,$rowcount);
 7543:             $$rowtotal ++;
 7544:             $rowcount ++;
 7545:         }
 7546:     } elsif ($position eq 'bottom') {
 7547:         $context = 'course';
 7548:         $rowcount = 0;
 7549:         foreach my $role ('st','ep','ta','in','cr') {
 7550:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
 7551:                                                    $numinrow,$rowcount);
 7552:             $$rowtotal ++;
 7553:             $rowcount ++;
 7554:         }
 7555:     }
 7556:     return $datatable;
 7557: }
 7558: 
 7559: sub print_defaults {
 7560:     my ($position,$dom,$settings,$rowtotal) = @_;
 7561:     my $rownum = 0;
 7562:     my ($datatable,$css_class,$titles);
 7563:     unless ($position eq 'bottom') {
 7564:         $titles = &defaults_titles($dom);
 7565:     }
 7566:     if ($position eq 'top') {
 7567:         my @items = ('auth_def','auth_arg_def','lang_def','timezone_def',
 7568:                      'datelocale_def','portal_def');
 7569:         my %defaults;
 7570:         if (ref($settings) eq 'HASH') {
 7571:             %defaults = %{$settings};
 7572:         } else {
 7573:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
 7574:             foreach my $item (@items) {
 7575:                 $defaults{$item} = $domdefaults{$item};
 7576:             }
 7577:         }
 7578:         foreach my $item (@items) {
 7579:             if ($rownum%2) {
 7580:                 $css_class = '';
 7581:             } else {
 7582:                 $css_class = ' class="LC_odd_row" ';
 7583:             }
 7584:             $datatable .= '<tr'.$css_class.'>'.
 7585:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
 7586:                           '</span></td><td class="LC_right_item" colspan="3">';
 7587:             if ($item eq 'auth_def') {
 7588:                 my @authtypes = ('internal','krb4','krb5','localauth');
 7589:                 my %shortauth = (
 7590:                                  internal => 'int',
 7591:                                  krb4 => 'krb4',
 7592:                                  krb5 => 'krb5',
 7593:                                  localauth  => 'loc'
 7594:                                 );
 7595:                 my %authnames = &authtype_names();
 7596:                 foreach my $auth (@authtypes) {
 7597:                     my $checked = ' ';
 7598:                     if ($defaults{$item} eq $auth) {
 7599:                         $checked = ' checked="checked" ';
 7600:                     }
 7601:                     $datatable .= '<label><input type="radio" name="'.$item.
 7602:                                   '" value="'.$auth.'"'.$checked.'/>'.
 7603:                                   $authnames{$shortauth{$auth}}.'</label>&nbsp;&nbsp;';
 7604:                 }
 7605:             } elsif ($item eq 'timezone_def') {
 7606:                 my $includeempty = 1;
 7607:                 $datatable .= &Apache::loncommon::select_timezone($item,$defaults{$item},undef,$includeempty);
 7608:             } elsif ($item eq 'datelocale_def') {
 7609:                 my $includeempty = 1;
 7610:                 $datatable .= &Apache::loncommon::select_datelocale($item,$defaults{$item},undef,$includeempty);
 7611:             } elsif ($item eq 'lang_def') {
 7612:                 my $includeempty = 1;
 7613:                 $datatable .= &Apache::loncommon::select_language($item,$defaults{$item},$includeempty);
 7614:             } else {
 7615:                 my $size;
 7616:                 if ($item eq 'portal_def') {
 7617:                     $size = ' size="25"';
 7618:                 }
 7619:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
 7620:                               $defaults{$item}.'"'.$size.' />';
 7621:             }
 7622:             $datatable .= '</td></tr>';
 7623:             $rownum ++;
 7624:         }
 7625:     } else {
 7626:         my %defaults;
 7627:         if (ref($settings) eq 'HASH') {
 7628:             if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
 7629:                 my $maxnum = @{$settings->{'inststatusorder'}};
 7630:                 for (my $i=0; $i<$maxnum; $i++) {
 7631:                     $css_class = $rownum%2?' class="LC_odd_row"':'';
 7632:                     my $item = $settings->{'inststatusorder'}->[$i];
 7633:                     my $title = $settings->{'inststatustypes'}->{$item};
 7634:                     my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'$item'".');"';
 7635:                     $datatable .= '<tr'.$css_class.'>'.
 7636:                                   '<td><span class="LC_nobreak">'.
 7637:                                   '<select name="inststatus_pos_'.$item.'"'.$chgstr.'>';
 7638:                     for (my $k=0; $k<=$maxnum; $k++) {
 7639:                         my $vpos = $k+1;
 7640:                         my $selstr;
 7641:                         if ($k == $i) {
 7642:                             $selstr = ' selected="selected" ';
 7643:                         }
 7644:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 7645:                     }
 7646:                     $datatable .= '</select>&nbsp;'.&mt('Internal ID:').'&nbsp;<b>'.$item.'</b>&nbsp;'.
 7647:                                   '<input type="checkbox" name="inststatus_delete" value="'.$item.'" />'.
 7648:                                   &mt('delete').'</span></td>'.
 7649:                                   '<td class="LC_left_item"><span class="LC_nobreak">'.&mt('Name displayed').':'.
 7650:                                   '<input type="text" size="20" name="inststatus_title_'.$item.'" value="'.$title.'" />'.
 7651:                                   '</span></td></tr>';
 7652:                 }
 7653:                 $css_class = $rownum%2?' class="LC_odd_row"':'';
 7654:                 my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'addinststatus_pos'".');"';
 7655:                 $datatable .= '<tr '.$css_class.'>'.
 7656:                               '<td><span class="LC_nobreak"><select name="addinststatus_pos"'.$chgstr.'>';
 7657:                 for (my $k=0; $k<=$maxnum; $k++) {
 7658:                     my $vpos = $k+1;
 7659:                     my $selstr;
 7660:                     if ($k == $maxnum) {
 7661:                         $selstr = ' selected="selected" ';
 7662:                     }
 7663:                     $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 7664:                 }
 7665:                 $datatable .= '</select>&nbsp;'.&mt('Internal ID:').
 7666:                               '<input type="text" size="10" name="addinststatus" value="" />'.
 7667:                               '&nbsp;'.&mt('(new)').
 7668:                               '</span></td><td class="LC_left_item"><span class="LC_nobreak">'.
 7669:                               &mt('Name displayed').':'.
 7670:                               '<input type="text" size="20" name="addinststatus_title" value="" /></span></td>'.
 7671:                               '</tr>'."\n";
 7672:                 $rownum ++;
 7673:             }
 7674:         }
 7675:     }
 7676:     $$rowtotal += $rownum;
 7677:     return $datatable;
 7678: }
 7679: 
 7680: sub get_languages_hash {
 7681:     my %langchoices;
 7682:     foreach my $id (&Apache::loncommon::languageids()) {
 7683:         my $code = &Apache::loncommon::supportedlanguagecode($id);
 7684:         if ($code ne '') {
 7685:             $langchoices{$code} =  &Apache::loncommon::plainlanguagedescription($id);
 7686:         }
 7687:     }
 7688:     return %langchoices;
 7689: }
 7690: 
 7691: sub defaults_titles {
 7692:     my ($dom) = @_;
 7693:     my %titles = &Apache::lonlocal::texthash (
 7694:                    'auth_def'      => 'Default authentication type',
 7695:                    'auth_arg_def'  => 'Default authentication argument',
 7696:                    'lang_def'      => 'Default language',
 7697:                    'timezone_def'  => 'Default timezone',
 7698:                    'datelocale_def' => 'Default locale for dates',
 7699:                    'portal_def'     => 'Portal/Default URL',
 7700:                    'intauth_cost'   => 'Encryption cost for bcrypt (positive integer)',
 7701:                    'intauth_check'  => 'Check bcrypt cost if authenticated',
 7702:                    'intauth_switch' => 'Existing crypt-based switched to bcrypt on authentication',
 7703:                  );
 7704:     if ($dom) {
 7705:         my $uprimary_id = &Apache::lonnet::domain($dom,'primary');
 7706:         my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 7707:         my $protocol = $Apache::lonnet::protocol{$uprimary_id};
 7708:         $protocol = 'http' if ($protocol ne 'https');
 7709:         if ($uint_dom) {
 7710:             $titles{'portal_def'} .= ' '.&mt('(for example: [_1])',$protocol.'://loncapa.'.
 7711:                                          $uint_dom);
 7712:         }
 7713:     }
 7714:     return (\%titles);
 7715: }
 7716: 
 7717: sub print_scantron {
 7718:     my ($r,$position,$dom,$confname,$settings,$rowtotal) = @_;
 7719:     if ($position eq 'top') {
 7720:         return &print_scantronformat($r,$dom,$confname,$settings,\$rowtotal);
 7721:     } else {
 7722:         return &print_scantronconfig($dom,$settings,\$rowtotal);
 7723:     }
 7724: }
 7725: 
 7726: sub scantron_javascript {
 7727:     return <<"ENDSCRIPT";
 7728: 
 7729: <script type="text/javascript">
 7730: // <![CDATA[
 7731: 
 7732: function toggleScantron(form) {
 7733:     var csvfieldset = new Array();
 7734:     if (document.getElementById('scantroncsv_cols')) {
 7735:         csvfieldset.push(document.getElementById('scantroncsv_cols'));
 7736:     }
 7737:     if (document.getElementById('scantroncsv_options')) {
 7738:         csvfieldset.push(document.getElementById('scantroncsv_options'));
 7739:     }
 7740:     if (csvfieldset.length) {
 7741:         if (document.getElementById('scantronconfcsv')) {
 7742:             var scantroncsv = document.getElementById('scantronconfcsv');
 7743:             if (scantroncsv.checked) {
 7744:                 for (var i=0; i<csvfieldset.length; i++) {
 7745:                     csvfieldset[i].style.display = 'block';
 7746:                 }
 7747:             } else {
 7748:                 for (var i=0; i<csvfieldset.length; i++) {
 7749:                     csvfieldset[i].style.display = 'none';
 7750:                 }
 7751:                 var csvselects = document.getElementsByClassName('scantronconfig_csv');
 7752:                 if (csvselects.length) {
 7753:                     for (var j=0; j<csvselects.length; j++) {
 7754:                         csvselects[j].selectedIndex = 0;
 7755:                     }
 7756:                 }
 7757:             }
 7758:         }
 7759:     }
 7760:     return;
 7761: }
 7762: // ]]>
 7763: </script>
 7764: 
 7765: ENDSCRIPT
 7766: 
 7767: }
 7768: 
 7769: sub print_scantronformat {
 7770:     my ($r,$dom,$confname,$settings,$rowtotal) = @_;
 7771:     my $itemcount = 1;
 7772:     my ($datatable,$css_class,$scantronurl,$is_custom,%error,%scantronurls,
 7773:         %confhash);
 7774:     my $switchserver = &check_switchserver($dom,$confname);
 7775:     my %lt = &Apache::lonlocal::texthash (
 7776:                 default => 'Default bubblesheet format file error',
 7777:                 custom  => 'Custom bubblesheet format file error',
 7778:              );
 7779:     my %scantronfiles = (
 7780:         default => 'default.tab',
 7781:         custom => 'custom.tab',
 7782:     );
 7783:     foreach my $key (keys(%scantronfiles)) {
 7784:         $scantronurls{$key} = '/res/'.$dom.'/'.$confname.'/scantron/'
 7785:                               .$scantronfiles{$key};
 7786:     }
 7787:     my @defaultinfo = &Apache::lonnet::stat_file($scantronurls{'default'});
 7788:     if ((!@defaultinfo) || ($defaultinfo[0] eq 'no_such_dir')) {
 7789:         if (!$switchserver) {
 7790:             my $servadm = $r->dir_config('lonAdmEMail');
 7791:             my ($configuserok,$author_ok) = &config_check($dom,$confname,$servadm);
 7792:             if ($configuserok eq 'ok') {
 7793:                 if ($author_ok eq 'ok') {
 7794:                     my %legacyfile = (
 7795:  default => $Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab',
 7796:  custom  => $Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab',
 7797:                     );
 7798:                     my %md5chk;
 7799:                     foreach my $type (keys(%legacyfile)) {
 7800:                         ($md5chk{$type}) = split(/ /,`md5sum $legacyfile{$type}`);
 7801:                         chomp($md5chk{$type});
 7802:                     }
 7803:                     if ($md5chk{'default'} ne $md5chk{'custom'}) {
 7804:                         foreach my $type (keys(%legacyfile)) {
 7805:                             ($scantronurls{$type},my $error) =
 7806:                                 &legacy_scantronformat($r,$dom,$confname,
 7807:                                                  $type,$legacyfile{$type},
 7808:                                                  $scantronurls{$type},
 7809:                                                  $scantronfiles{$type});
 7810:                             if ($error ne '') {
 7811:                                 $error{$type} = $error;
 7812:                             }
 7813:                         }
 7814:                         if (keys(%error) == 0) {
 7815:                             $is_custom = 1;
 7816:                             $confhash{'scantron'}{'scantronformat'} =
 7817:                                 $scantronurls{'custom'};
 7818:                             my $putresult =
 7819:                                 &Apache::lonnet::put_dom('configuration',
 7820:                                                          \%confhash,$dom);
 7821:                             if ($putresult ne 'ok') {
 7822:                                 $error{'custom'} =
 7823:                                     '<span class="LC_error">'.
 7824:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
 7825:                             }
 7826:                         }
 7827:                     } else {
 7828:                         ($scantronurls{'default'},my $error) =
 7829:                             &legacy_scantronformat($r,$dom,$confname,
 7830:                                           'default',$legacyfile{'default'},
 7831:                                           $scantronurls{'default'},
 7832:                                           $scantronfiles{'default'});
 7833:                         if ($error eq '') {
 7834:                             $confhash{'scantron'}{'scantronformat'} = ''; 
 7835:                             my $putresult =
 7836:                                 &Apache::lonnet::put_dom('configuration',
 7837:                                                          \%confhash,$dom);
 7838:                             if ($putresult ne 'ok') {
 7839:                                 $error{'default'} =
 7840:                                     '<span class="LC_error">'.
 7841:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
 7842:                             }
 7843:                         } else {
 7844:                             $error{'default'} = $error;
 7845:                         }
 7846:                     }
 7847:                 }
 7848:             }
 7849:         } else {
 7850:             $error{'default'} = &mt("Unable to copy default bubblesheet formatfile to domain's RES space: [_1]",$switchserver);
 7851:         }
 7852:     }
 7853:     if (ref($settings) eq 'HASH') {
 7854:         if ($settings->{'scantronformat'} eq "/res/$dom/$confname/scantron/custom.tab") {
 7855:             my @info = &Apache::lonnet::stat_file($settings->{'scantronformat'});
 7856:             if ((!@info) || ($info[0] eq 'no_such_dir')) {
 7857:                 $scantronurl = '';
 7858:             } else {
 7859:                 $scantronurl = $settings->{'scantronformat'};
 7860:             }
 7861:             $is_custom = 1;
 7862:         } else {
 7863:             $scantronurl = $scantronurls{'default'};
 7864:         }
 7865:     } else {
 7866:         if ($is_custom) {
 7867:             $scantronurl = $scantronurls{'custom'};
 7868:         } else {
 7869:             $scantronurl = $scantronurls{'default'};
 7870:         }
 7871:     }
 7872:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7873:     $datatable .= '<tr'.$css_class.'>';
 7874:     if (!$is_custom) {
 7875:         $datatable .= '<td>'.&mt('Default in use:').'<br />'.
 7876:                       '<span class="LC_nobreak">';
 7877:         if ($scantronurl) {
 7878:             $datatable .= &Apache::loncommon::modal_link($scantronurl,&mt('Default bubblesheet format file'),600,500,
 7879:                                                          undef,undef,undef,undef,'background-color:#ffffff');
 7880:         } else {
 7881:             $datatable = &mt('File unavailable for display');
 7882:         }
 7883:         $datatable .= '</span></td>';
 7884:         if (keys(%error) == 0) { 
 7885:             $datatable .= '<td valign="bottom">';
 7886:             if (!$switchserver) {
 7887:                 $datatable .= &mt('Upload:').'<br />';
 7888:             }
 7889:         } else {
 7890:             my $errorstr;
 7891:             foreach my $key (sort(keys(%error))) {
 7892:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
 7893:             }
 7894:             $datatable .= '<td>'.$errorstr;
 7895:         }
 7896:     } else {
 7897:         if (keys(%error) > 0) {
 7898:             my $errorstr;
 7899:             foreach my $key (sort(keys(%error))) {
 7900:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
 7901:             } 
 7902:             $datatable .= '<td>'.$errorstr.'</td><td>&nbsp;';
 7903:         } elsif ($scantronurl) {
 7904:             my $link =  &Apache::loncommon::modal_link($scantronurl,&mt('Custom bubblesheet format file'),600,500,
 7905:                                                        undef,undef,undef,undef,'background-color:#ffffff');
 7906:             $datatable .= '<td><span class="LC_nobreak">'.
 7907:                           $link.
 7908:                           '<label><input type="checkbox" name="scantronformat_del"'.
 7909:                           ' value="1" />'.&mt('Delete?').'</label></span></td>'.
 7910:                           '<td><span class="LC_nobreak">&nbsp;'.
 7911:                           &mt('Replace:').'</span><br />';
 7912:         }
 7913:     }
 7914:     if (keys(%error) == 0) {
 7915:         if ($switchserver) {
 7916:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 7917:         } else {
 7918:             $datatable .='<span class="LC_nobreak">&nbsp;'.
 7919:                          '<input type="file" name="scantronformat" /></span>';
 7920:         }
 7921:     }
 7922:     $datatable .= '</td></tr>';
 7923:     $$rowtotal ++;
 7924:     return $datatable;
 7925: }
 7926: 
 7927: sub legacy_scantronformat {
 7928:     my ($r,$dom,$confname,$file,$legacyfile,$newurl,$newfile) = @_;
 7929:     my ($url,$error);
 7930:     my @statinfo = &Apache::lonnet::stat_file($newurl);
 7931:     if ((!@statinfo) || ($statinfo[0] eq 'no_such_dir')) {
 7932:         (my $result,$url) =
 7933:             &publishlogo($r,'copy',$legacyfile,$dom,$confname,'scantron',
 7934:                          '','',$newfile);
 7935:         if ($result ne 'ok') {
 7936:             $error = &mt("An error occurred publishing the [_1] bubblesheet format file in RES space. Error was: [_2].",$newfile,$result);
 7937:         }
 7938:     }
 7939:     return ($url,$error);
 7940: }
 7941: 
 7942: sub print_scantronconfig {
 7943:     my ($dom,$settings,$rowtotal) = @_;
 7944:     my $itemcount = 2;
 7945:     my $is_checked = ' checked="checked"';
 7946:     my %optionson = (
 7947:                      hdr => ' checked="checked"',
 7948:                      pad => ' checked="checked"',
 7949:                      rem => ' checked="checked"',
 7950:                     );
 7951:     my %optionsoff = (
 7952:                       hdr => '',
 7953:                       pad => '',
 7954:                       rem => '',
 7955:                      );
 7956:     my $currcsvsty = 'none';
 7957:     my ($datatable,%csvfields,%checked,%onclick,%csvoptions);
 7958:     my @fields = &scantroncsv_fields();
 7959:     my %titles = &scantronconfig_titles();
 7960:     if (ref($settings) eq 'HASH') {
 7961:         if (ref($settings->{config}) eq 'HASH') {
 7962:             if ($settings->{config}->{dat}) {
 7963:                 $checked{'dat'} = $is_checked;
 7964:             }
 7965:             if (ref($settings->{config}->{csv}) eq 'HASH') {
 7966:                 if (ref($settings->{config}->{csv}->{fields}) eq 'HASH') {
 7967:                     %csvfields = %{$settings->{config}->{csv}->{fields}};
 7968:                     if (keys(%csvfields) > 0) {
 7969:                         $checked{'csv'} = $is_checked;
 7970:                         $currcsvsty = 'block';
 7971:                     }
 7972:                 }
 7973:                 if (ref($settings->{config}->{csv}->{options}) eq 'HASH') {
 7974:                     %csvoptions = %{$settings->{config}->{csv}->{options}};
 7975:                     foreach my $option (keys(%optionson)) {
 7976:                         unless ($csvoptions{$option}) {
 7977:                             $optionsoff{$option} = $optionson{$option};
 7978:                             $optionson{$option} = '';
 7979:                         }
 7980:                     }
 7981:                 }
 7982:             }
 7983:         } else {
 7984:             $checked{'dat'} = $is_checked;
 7985:         }
 7986:     } else {
 7987:         $checked{'dat'} = $is_checked;
 7988:     }
 7989:     $onclick{'csv'} = ' onclick="toggleScantron(this.form);"';
 7990:     my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
 7991:     $datatable = '<tr '.$css_class.'><td>'.&mt('Supported formats').'</td>'.
 7992:                  '<td class="LC_left_item" valign="top"><span class="LC_nobreak">';
 7993:     foreach my $item ('dat','csv') {
 7994:         my $id;
 7995:         if ($item eq 'csv') {
 7996:             $id = 'id="scantronconfcsv" ';
 7997:         }
 7998:         $datatable .= '<label><input type="checkbox" name="scantronconfig" '.$id.'value="'.$item.'"'.$checked{$item}.$onclick{$item}.' />'.
 7999:                       $titles{$item}.'</label>'.('&nbsp;'x3);
 8000:         if ($item eq 'csv') {
 8001:             $datatable .= '<fieldset style="display:'.$currcsvsty.'" id="scantroncsv_cols">'.
 8002:                           '<legend>'.&mt('CSV Column Mapping').'</legend>'.
 8003:                           '<table><tr><th>'.&mt('Field').'</th><th>'.&mt('Location').'</th></tr>'."\n";
 8004:             foreach my $col (@fields) {
 8005:                 my $selnone;
 8006:                 if ($csvfields{$col} eq '') {
 8007:                     $selnone = ' selected="selected"';
 8008:                 }
 8009:                 $datatable .= '<tr><td>'.$titles{$col}.'</td>'.
 8010:                               '<td><select name="scantronconfig_csv_'.$col.'" class="scantronconfig_csv">'.
 8011:                               '<option value=""'.$selnone.'></option>';
 8012:                 for (my $i=0; $i<20; $i++) {
 8013:                     my $shown = $i+1;
 8014:                     my $sel;
 8015:                     unless ($selnone) {
 8016:                         if (exists($csvfields{$col})) {
 8017:                             if ($csvfields{$col} == $i) {
 8018:                                 $sel = ' selected="selected"';
 8019:                             }
 8020:                         }
 8021:                     }
 8022:                     $datatable .= '<option value="'.$i.'"'.$sel.'>'.$shown.'</option>';
 8023:                 }
 8024:                 $datatable .= '</select></td></tr>';
 8025:            }
 8026:            $datatable .= '</table></fieldset>'.
 8027:                          '<fieldset style="display:'.$currcsvsty.'" id="scantroncsv_options">'.
 8028:                          '<legend>'.&mt('CSV Options').'</legend>';
 8029:            foreach my $option ('hdr','pad','rem') {
 8030:                $datatable .= '<span class="LC_nobreak">'.$titles{$option}.':'.
 8031:                          '<label><input type="radio" name="scantroncsv_'.$option.'" value="1"'.$optionson{$option}.' />'.
 8032:                          &mt('Yes').'</label>'.('&nbsp;'x2)."\n".
 8033:                          '<label><input type="radio" name="scantroncsv_'.$option.'" value="0"'.$optionsoff{$option}.' />'.&mt('No').'</label></span><br />';
 8034:            }
 8035:            $datatable .= '</fieldset>';
 8036:            $itemcount ++;
 8037:         }
 8038:     }
 8039:     $datatable .= '</td></tr>';
 8040:     $$rowtotal ++;
 8041:     return $datatable;
 8042: }
 8043: 
 8044: sub scantronconfig_titles {
 8045:     return &Apache::lonlocal::texthash(
 8046:                                           dat => 'Standard format (.dat)',
 8047:                                           csv => 'Comma separated values (.csv)',
 8048:                                           hdr => 'Remove first line in file (contains column titles)',
 8049:                                           pad => 'Prepend 0s to PaperID',
 8050:                                           rem => 'Remove leading spaces (except Question Response columns)',
 8051:                                           CODE => 'CODE',
 8052:                                           ID   => 'Student ID',
 8053:                                           PaperID => 'Paper ID',
 8054:                                           FirstName => 'First Name',
 8055:                                           LastName => 'Last Name',
 8056:                                           FirstQuestion => 'First Question Response',
 8057:                                           Section => 'Section',
 8058:     );
 8059: }
 8060: 
 8061: sub scantroncsv_fields {
 8062:     return ('PaperID','LastName','FirstName','ID','Section','CODE','FirstQuestion');
 8063: }
 8064: 
 8065: sub print_coursecategories {
 8066:     my ($position,$dom,$hdritem,$settings,$rowtotal) = @_;
 8067:     my $datatable;
 8068:     if ($position eq 'top') {
 8069:         my (%checked);
 8070:         my @catitems = ('unauth','auth');
 8071:         my @cattypes = ('std','domonly','codesrch','none');
 8072:         $checked{'unauth'} = 'std';
 8073:         $checked{'auth'} = 'std';
 8074:         if (ref($settings) eq 'HASH') {
 8075:             foreach my $type (@cattypes) {
 8076:                 if ($type eq $settings->{'unauth'}) {
 8077:                     $checked{'unauth'} = $type;
 8078:                 }
 8079:                 if ($type eq $settings->{'auth'}) {
 8080:                     $checked{'auth'} = $type;
 8081:                 }
 8082:             }
 8083:         }
 8084:         my %lt = &Apache::lonlocal::texthash (
 8085:                                                unauth   => 'Catalog type for unauthenticated users',
 8086:                                                auth     => 'Catalog type for authenticated users',
 8087:                                                none     => 'No catalog',
 8088:                                                std      => 'Standard catalog',
 8089:                                                domonly  => 'Domain-only catalog',
 8090:                                                codesrch => "Code search form",
 8091:                                              );
 8092:        my $itemcount = 0;
 8093:        foreach my $item (@catitems) {
 8094:            my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
 8095:            $datatable .= '<tr '.$css_class.'>'.
 8096:                          '<td>'.$lt{$item}.'</td>'.
 8097:                          '<td class="LC_right_item"><span class="LC_nobreak">';
 8098:            foreach my $type (@cattypes) {
 8099:                my $ischecked;
 8100:                if ($checked{$item} eq $type) {
 8101:                    $ischecked=' checked="checked"';
 8102:                }
 8103:                $datatable .= '<label>'.
 8104:                              '<input type="radio" name="coursecat_'.$item.'" value="'.$type.'"'.$ischecked.
 8105:                              ' />'.$lt{$type}.'</label>&nbsp;';
 8106:            }
 8107:            $datatable .= '</span></td></tr>';
 8108:            $itemcount ++;
 8109:         }
 8110:         $$rowtotal += $itemcount;
 8111:     } elsif ($position eq 'middle') {
 8112:         my $toggle_cats_crs = ' ';
 8113:         my $toggle_cats_dom = ' checked="checked" ';
 8114:         my $can_cat_crs = ' ';
 8115:         my $can_cat_dom = ' checked="checked" ';
 8116:         my $toggle_catscomm_comm = ' ';
 8117:         my $toggle_catscomm_dom = ' checked="checked" ';
 8118:         my $can_catcomm_comm = ' ';
 8119:         my $can_catcomm_dom = ' checked="checked" ';
 8120: 
 8121:         if (ref($settings) eq 'HASH') {
 8122:             if ($settings->{'togglecats'} eq 'crs') {
 8123:                 $toggle_cats_crs = $toggle_cats_dom;
 8124:                 $toggle_cats_dom = ' ';
 8125:             }
 8126:             if ($settings->{'categorize'} eq 'crs') {
 8127:                 $can_cat_crs = $can_cat_dom;
 8128:                 $can_cat_dom = ' ';
 8129:             }
 8130:             if ($settings->{'togglecatscomm'} eq 'comm') {
 8131:                 $toggle_catscomm_comm = $toggle_catscomm_dom;
 8132:                 $toggle_catscomm_dom = ' ';
 8133:             }
 8134:             if ($settings->{'categorizecomm'} eq 'comm') {
 8135:                 $can_catcomm_comm = $can_catcomm_dom;
 8136:                 $can_catcomm_dom = ' ';
 8137:             }
 8138:         }
 8139:         my %title = &Apache::lonlocal::texthash (
 8140:                      togglecats     => 'Show/Hide a course in catalog',
 8141:                      togglecatscomm => 'Show/Hide a community in catalog',
 8142:                      categorize     => 'Assign a category to a course',
 8143:                      categorizecomm => 'Assign a category to a community',
 8144:                     );
 8145:         my %level = &Apache::lonlocal::texthash (
 8146:                      dom  => 'Set in Domain',
 8147:                      crs  => 'Set in Course',
 8148:                      comm => 'Set in Community',
 8149:                     );
 8150:         $datatable = '<tr class="LC_odd_row">'.
 8151:                   '<td>'.$title{'togglecats'}.'</td>'.
 8152:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 8153:                   '<input type="radio" name="togglecats"'.
 8154:                   $toggle_cats_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 8155:                   '<label><input type="radio" name="togglecats"'.
 8156:                   $toggle_cats_crs.' value="crs" />'.$level{'crs'}.'</label></span></td>'.
 8157:                   '</tr><tr>'.
 8158:                   '<td>'.$title{'categorize'}.'</td>'.
 8159:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 8160:                   '<label><input type="radio" name="categorize"'.
 8161:                   $can_cat_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 8162:                   '<label><input type="radio" name="categorize"'.
 8163:                   $can_cat_crs.'value="crs" />'.$level{'crs'}.'</label></span></td>'.
 8164:                   '</tr><tr class="LC_odd_row">'.
 8165:                   '<td>'.$title{'togglecatscomm'}.'</td>'.
 8166:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 8167:                   '<input type="radio" name="togglecatscomm"'.
 8168:                   $toggle_catscomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 8169:                   '<label><input type="radio" name="togglecatscomm"'.
 8170:                   $toggle_catscomm_comm.' value="comm" />'.$level{'comm'}.'</label></span></td>'.
 8171:                   '</tr><tr>'.
 8172:                   '<td>'.$title{'categorizecomm'}.'</td>'.
 8173:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 8174:                   '<label><input type="radio" name="categorizecomm"'.
 8175:                   $can_catcomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 8176:                   '<label><input type="radio" name="categorizecomm"'.
 8177:                   $can_catcomm_comm.'value="comm" />'.$level{'comm'}.'</label></span></td>'.
 8178:                   '</tr>';
 8179:         $$rowtotal += 4;
 8180:     } else {
 8181:         my $css_class;
 8182:         my $itemcount = 1;
 8183:         my $cathash; 
 8184:         if (ref($settings) eq 'HASH') {
 8185:             $cathash = $settings->{'cats'};
 8186:         }
 8187:         if (ref($cathash) eq 'HASH') {
 8188:             my (@cats,@trails,%allitems,%idx,@jsarray);
 8189:             &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,
 8190:                                                    \%allitems,\%idx,\@jsarray);
 8191:             my $maxdepth = scalar(@cats);
 8192:             my $colattrib = '';
 8193:             if ($maxdepth > 2) {
 8194:                 $colattrib = ' colspan="2" ';
 8195:             }
 8196:             my @path;
 8197:             if (@cats > 0) {
 8198:                 if (ref($cats[0]) eq 'ARRAY') {
 8199:                     my $numtop = @{$cats[0]};
 8200:                     my $maxnum = $numtop;
 8201:                     my %default_names = (
 8202:                           instcode    => &mt('Official courses'),
 8203:                           communities => &mt('Communities'),
 8204:                     );
 8205: 
 8206:                     if ((!grep(/^instcode$/,@{$cats[0]})) || 
 8207:                         ($cathash->{'instcode::0'} eq '') ||
 8208:                         (!grep(/^communities$/,@{$cats[0]})) || 
 8209:                         ($cathash->{'communities::0'} eq '')) {
 8210:                         $maxnum ++;
 8211:                     }
 8212:                     my $lastidx;
 8213:                     for (my $i=0; $i<$numtop; $i++) {
 8214:                         my $parent = $cats[0][$i];
 8215:                         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8216:                         my $item = &escape($parent).'::0';
 8217:                         my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$item','$idx{$item}'".');"';
 8218:                         $lastidx = $idx{$item};
 8219:                         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 8220:                                       .'<select name="'.$item.'"'.$chgstr.'>';
 8221:                         for (my $k=0; $k<=$maxnum; $k++) {
 8222:                             my $vpos = $k+1;
 8223:                             my $selstr;
 8224:                             if ($k == $i) {
 8225:                                 $selstr = ' selected="selected" ';
 8226:                             }
 8227:                             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 8228:                         }
 8229:                         $datatable .= '</select></span></td><td>';
 8230:                         if ($parent eq 'instcode' || $parent eq 'communities') {
 8231:                             $datatable .=  '<span class="LC_nobreak">'
 8232:                                            .$default_names{$parent}.'</span>';
 8233:                             if ($parent eq 'instcode') {
 8234:                                 $datatable .= '<br /><span class="LC_nobreak">('
 8235:                                               .&mt('with institutional codes')
 8236:                                               .')</span></td><td'.$colattrib.'>';
 8237:                             } else {
 8238:                                 $datatable .= '<table><tr><td>';
 8239:                             }
 8240:                             $datatable .= '<span class="LC_nobreak">'
 8241:                                           .'<label><input type="radio" name="'
 8242:                                           .$parent.'" value="1" checked="checked" />'
 8243:                                           .&mt('Display').'</label>';
 8244:                             if ($parent eq 'instcode') {
 8245:                                 $datatable .= '&nbsp;';
 8246:                             } else {
 8247:                                 $datatable .= '</span></td></tr><tr><td>'
 8248:                                               .'<span class="LC_nobreak">';
 8249:                             }
 8250:                             $datatable .= '<label><input type="radio" name="'
 8251:                                           .$parent.'" value="0" />'
 8252:                                           .&mt('Do not display').'</label></span>';
 8253:                             if ($parent eq 'communities') {
 8254:                                 $datatable .= '</td></tr></table>';
 8255:                             }
 8256:                             $datatable .= '</td>';
 8257:                         } else {
 8258:                             $datatable .= $parent
 8259:                                           .'&nbsp;<span class="LC_nobreak"><label>'
 8260:                                           .'<input type="checkbox" name="deletecategory" '
 8261:                                           .'value="'.$item.'" />'.&mt('Delete').'</label></span></td>';
 8262:                         }
 8263:                         my $depth = 1;
 8264:                         push(@path,$parent);
 8265:                         $datatable .= &build_category_rows($itemcount,\@cats,$depth,$parent,\@path,\%idx);
 8266:                         pop(@path);
 8267:                         $datatable .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
 8268:                         $itemcount ++;
 8269:                     }
 8270:                     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8271:                     my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','$lastidx'".');"';
 8272:                     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="addcategory_pos"'.$chgstr.'>';
 8273:                     for (my $k=0; $k<=$maxnum; $k++) {
 8274:                         my $vpos = $k+1;
 8275:                         my $selstr;
 8276:                         if ($k == $numtop) {
 8277:                             $selstr = ' selected="selected" ';
 8278:                         }
 8279:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 8280:                     }
 8281:                     $datatable .= '</select></span></td><td colspan="2">'.&mt('Add category:').'&nbsp;'
 8282:                                   .'<input type="text" size="20" name="addcategory_name" value="" /></td>'
 8283:                                   .'</tr>'."\n";
 8284:                     $itemcount ++;
 8285:                     foreach my $default ('instcode','communities') {
 8286:                         if ((!grep(/^\Q$default\E$/,@{$cats[0]})) || ($cathash->{$default.'::0'} eq '')) {
 8287:                             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8288:                             my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','$lastidx'".');"';
 8289:                             $datatable .= '<tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr><tr '.$css_class.'><td>'.
 8290:                                           '<span class="LC_nobreak"><select name="'.$default.'_pos"'.$chgstr.'>';
 8291:                             for (my $k=0; $k<=$maxnum; $k++) {
 8292:                                 my $vpos = $k+1;
 8293:                                 my $selstr;
 8294:                                 if ($k == $maxnum) {
 8295:                                     $selstr = ' selected="selected" ';
 8296:                                 }
 8297:                                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 8298:                             }
 8299:                             $datatable .= '</select></span></td>'.
 8300:                                           '<td><span class="LC_nobreak">'.
 8301:                                           $default_names{$default}.'</span>';
 8302:                             if ($default eq 'instcode') {
 8303:                                 $datatable .= '<br /><span class="LC_nobreak">(' 
 8304:                                               .&mt('with institutional codes').')</span>';
 8305:                             }
 8306:                             $datatable .= '</td>'
 8307:                                           .'<td><span class="LC_nobreak"><label><input type="radio" name="'.$default.'" value="1" />'
 8308:                                           .&mt('Display').'</label>&nbsp;'
 8309:                                           .'<label><input type="radio" name="'.$default.'" value="0" checked="checked"/>'
 8310:                                           .&mt('Do not display').'</label></span></td></tr>';
 8311:                         }
 8312:                     }
 8313:                 }
 8314:             } else {
 8315:                 $datatable .= &initialize_categories($itemcount);
 8316:             }
 8317:         } else {
 8318:             $datatable .= '<tr><td class="LC_right_item">'.$hdritem->{'header'}->[1]->{'col2'}.'</td></tr>'
 8319:                           .&initialize_categories($itemcount);
 8320:         }
 8321:         $$rowtotal += $itemcount;
 8322:     }
 8323:     return $datatable;
 8324: }
 8325: 
 8326: sub print_serverstatuses {
 8327:     my ($dom,$settings,$rowtotal) = @_;
 8328:     my $datatable;
 8329:     my @pages = &serverstatus_pages();
 8330:     my (%namedaccess,%machineaccess);
 8331:     foreach my $type (@pages) {
 8332:         $namedaccess{$type} = '';
 8333:         $machineaccess{$type}= '';
 8334:     }
 8335:     if (ref($settings) eq 'HASH') {
 8336:         foreach my $type (@pages) {
 8337:             if (exists($settings->{$type})) {
 8338:                 if (ref($settings->{$type}) eq 'HASH') {
 8339:                     foreach my $key (keys(%{$settings->{$type}})) {
 8340:                         if ($key eq 'namedusers') {
 8341:                             $namedaccess{$type} = $settings->{$type}->{$key};
 8342:                         } elsif ($key eq 'machines') {
 8343:                             $machineaccess{$type} = $settings->{$type}->{$key};
 8344:                         }
 8345:                     }
 8346:                 }
 8347:             }
 8348:         }
 8349:     }
 8350:     my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
 8351:     my $rownum = 0;
 8352:     my $css_class;
 8353:     foreach my $type (@pages) {
 8354:         $rownum ++;
 8355:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 8356:         $datatable .= '<tr'.$css_class.'>'.
 8357:                       '<td><span class="LC_nobreak">'.
 8358:                       $titles->{$type}.'</span></td>'.
 8359:                       '<td class="LC_left_item">'.
 8360:                       '<input type="text" name="'.$type.'_namedusers" '.
 8361:                       'value="'.$namedaccess{$type}.'" size="30" /></td>'.
 8362:                       '<td class="LC_right_item">'.
 8363:                       '<span class="LC_nobreak">'.
 8364:                       '<input type="text" name="'.$type.'_machines" '.
 8365:                       'value="'.$machineaccess{$type}.'" size="10" />'.
 8366:                       '</span></td></tr>'."\n";
 8367:     }
 8368:     $$rowtotal += $rownum;
 8369:     return $datatable;
 8370: }
 8371: 
 8372: sub serverstatus_pages {
 8373:     return ('userstatus','lonstatus','loncron','server-status','codeversions',
 8374:             'checksums','clusterstatus','metadata_keywords','metadata_harvest',
 8375:             'takeoffline','takeonline','showenv','toggledebug','ping','domconf',
 8376:             'uniquecodes','diskusage','coursecatalog');
 8377: }
 8378: 
 8379: sub defaults_javascript {
 8380:     my ($settings) = @_;
 8381:     return unless (ref($settings) eq 'HASH');
 8382:     if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
 8383:         my $maxnum = scalar(@{$settings->{'inststatusorder'}});
 8384:         if ($maxnum eq '') {
 8385:             $maxnum = 0;
 8386:         }
 8387:         $maxnum ++;
 8388:         my $jstext = '    var inststatuses = Array('."'".join("','",@{$settings->{'inststatusorder'}})."'".');';  
 8389:         return <<"ENDSCRIPT";
 8390: <script type="text/javascript">
 8391: // <![CDATA[
 8392: function reorderTypes(form,caller) {
 8393:     var changedVal;
 8394: $jstext 
 8395:     var newpos = 'addinststatus_pos';
 8396:     var current = new Array;
 8397:     var maxh = $maxnum;
 8398:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 8399:     var oldVal;
 8400:     if (caller == newpos) {
 8401:         changedVal = newitemVal;
 8402:     } else {
 8403:         var curritem = 'inststatus_pos_'+caller;
 8404:         changedVal = form.elements[curritem].options[form.elements[curritem].selectedIndex].value;
 8405:         current[newitemVal] = newpos;
 8406:     }
 8407:     for (var i=0; i<inststatuses.length; i++) {
 8408:         if (inststatuses[i] != caller) {
 8409:             var elementName = 'inststatus_pos_'+inststatuses[i];
 8410:             if (form.elements[elementName]) {
 8411:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 8412:                 current[currVal] = elementName;
 8413:             }
 8414:         }
 8415:     }
 8416:     for (var j=0; j<maxh; j++) {
 8417:         if (current[j] == undefined) {
 8418:             oldVal = j;
 8419:         }
 8420:     }
 8421:     if (oldVal < changedVal) {
 8422:         for (var k=oldVal+1; k<=changedVal ; k++) {
 8423:            var elementName = current[k];
 8424:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 8425:         }
 8426:     } else {
 8427:         for (var k=changedVal; k<oldVal; k++) {
 8428:             var elementName = current[k];
 8429:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 8430:         }
 8431:     }
 8432:     return;
 8433: }
 8434: 
 8435: // ]]>
 8436: </script>
 8437: 
 8438: ENDSCRIPT
 8439:     }
 8440: }
 8441: 
 8442: sub passwords_javascript {
 8443:     my %intalert = &Apache::lonlocal::texthash (
 8444:         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.',
 8445:         authcost => 'Warning: bcrypt encryption cost for internal authentication must be an integer.',
 8446:         passmin => 'Warning: minimum password length must be a positive integer greater than 6.',
 8447:         passmax => 'Warning: maximum password length must be a positive integer (or blank).',
 8448:         passexp => 'Warning: days before password expiration must be a positive integer (or blank).',
 8449:         passnum => 'Warning: number of previous passwords to save must be a positive integer (or blank).',
 8450:     );
 8451:     &js_escape(\%intalert);
 8452:     my $defmin = $Apache::lonnet::passwdmin;
 8453:     my $intauthjs = <<"ENDSCRIPT";
 8454: 
 8455: function warnIntAuth(field) {
 8456:     if (field.name == 'intauth_check') {
 8457:         if (field.value == '2') {
 8458:             alert('$intalert{authcheck}');
 8459:         }
 8460:     }
 8461:     if (field.name == 'intauth_cost') {
 8462:         field.value.replace(/\s/g,'');
 8463:         if (field.value != '') {
 8464:             var regexdigit=/^\\d+\$/;
 8465:             if (!regexdigit.test(field.value)) {
 8466:                 alert('$intalert{authcost}');
 8467:             }
 8468:         }
 8469:     }
 8470:     return;
 8471: }
 8472: 
 8473: function warnIntPass(field) {
 8474:     field.value.replace(/^\s+/,'');
 8475:     field.value.replace(/\s+\$/,'');
 8476:     var regexdigit=/^\\d+\$/;
 8477:     if (field.name == 'passwords_min') {
 8478:         if (field.value == '') {
 8479:             alert('$intalert{passmin}');
 8480:             field.value = '$defmin';
 8481:         } else {
 8482:             if (!regexdigit.test(field.value)) {
 8483:                 alert('$intalert{passmin}');
 8484:                 field.value = '$defmin';
 8485:             }
 8486:             var minval = parseInt(field.value,10);
 8487:             if (minval < $defmin) {
 8488:                 alert('$intalert{passmin}');
 8489:                 field.value = '$defmin';
 8490:             }
 8491:         }
 8492:     } else {
 8493:         if (field.value == '0') {
 8494:             field.value = '';
 8495:         }
 8496:         if (field.value != '') {
 8497:             if (field.name == 'passwords_expire') {
 8498:                 var regexpposnum=/^\\d+(|\\.\\d*)\$/;
 8499:                 if (!regexpposnum.test(field.value)) {
 8500:                     alert('$intalert{passexp}');
 8501:                     field.value = '';
 8502:                 } else {
 8503:                     var expval = parseFloat(field.value);
 8504:                     if (expval == 0) {
 8505:                         alert('$intalert{passexp}');
 8506:                         field.value = '';
 8507:                     }
 8508:                 }
 8509:             } else {
 8510:                 if (!regexdigit.test(field.value)) {
 8511:                     if (field.name == 'passwords_max') {
 8512:                         alert('$intalert{passmax}');
 8513:                     } else {
 8514:                         if (field.name == 'passwords_numsaved') {
 8515:                             alert('$intalert{passnum}');
 8516:                         }
 8517:                     }
 8518:                     field.value = '';
 8519:                 }
 8520:             }
 8521:         }
 8522:     }
 8523:     return;
 8524: }
 8525: 
 8526: ENDSCRIPT
 8527:     return &Apache::lonhtmlcommon::scripttag($intauthjs);
 8528: }
 8529: 
 8530: sub coursecategories_javascript {
 8531:     my ($settings) = @_;
 8532:     my ($output,$jstext,$cathash);
 8533:     if (ref($settings) eq 'HASH') {
 8534:         $cathash = $settings->{'cats'};
 8535:     }
 8536:     if (ref($cathash) eq 'HASH') {
 8537:         my (@cats,@jsarray,%idx);
 8538:         &Apache::loncommon::gather_categories($cathash,\@cats,\%idx,\@jsarray);
 8539:         if (@jsarray > 0) {
 8540:             $jstext = '    var categories = Array('.scalar(@jsarray).');'."\n";
 8541:             for (my $i=0; $i<@jsarray; $i++) {
 8542:                 if (ref($jsarray[$i]) eq 'ARRAY') {
 8543:                     my $catstr = join('","',@{$jsarray[$i]});
 8544:                     $jstext .= '    categories['.$i.'] = Array("'.$catstr.'");'."\n";
 8545:                 }
 8546:             }
 8547:         }
 8548:     } else {
 8549:         $jstext  = '    var categories = Array(1);'."\n".
 8550:                    '    categories[0] = Array("instcode_pos");'."\n"; 
 8551:     }
 8552:     my $instcode_reserved = &mt('The name: [_1] is a reserved category.','"instcode"');
 8553:     my $communities_reserved = &mt('The name: [_1] is a reserved category.','"communities"');
 8554:     my $choose_again = "\n".&mt('Please use a different name for the new top level category.'); 
 8555:     &js_escape(\$instcode_reserved);
 8556:     &js_escape(\$communities_reserved);
 8557:     &js_escape(\$choose_again);
 8558:     $output = <<"ENDSCRIPT";
 8559: <script type="text/javascript">
 8560: // <![CDATA[
 8561: function reorderCats(form,parent,item,idx) {
 8562:     var changedVal;
 8563: $jstext
 8564:     var newpos = 'addcategory_pos';
 8565:     if (parent == '') {
 8566:         var has_instcode = 0;
 8567:         var maxtop = categories[idx].length;
 8568:         for (var j=0; j<maxtop; j++) {
 8569:             if (categories[idx][j] == 'instcode::0') {
 8570:                 has_instcode == 1;
 8571:             }
 8572:         }
 8573:         if (has_instcode == 0) {
 8574:             categories[idx][maxtop] = 'instcode_pos';
 8575:         }
 8576:     } else {
 8577:         newpos += '_'+parent;
 8578:     }
 8579:     var maxh = 1 + categories[idx].length;
 8580:     var current = new Array;
 8581:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 8582:     if (item == newpos) {
 8583:         changedVal = newitemVal;
 8584:     } else {
 8585:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 8586:         current[newitemVal] = newpos;
 8587:     }
 8588:     for (var i=0; i<categories[idx].length; i++) {
 8589:         var elementName = categories[idx][i];
 8590:         if (elementName != item) {
 8591:             if (form.elements[elementName]) {
 8592:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 8593:                 current[currVal] = elementName;
 8594:             }
 8595:         }
 8596:     }
 8597:     var oldVal;
 8598:     for (var j=0; j<maxh; j++) {
 8599:         if (current[j] == undefined) {
 8600:             oldVal = j;
 8601:         }
 8602:     }
 8603:     if (oldVal < changedVal) {
 8604:         for (var k=oldVal+1; k<=changedVal ; k++) {
 8605:            var elementName = current[k];
 8606:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 8607:         }
 8608:     } else {
 8609:         for (var k=changedVal; k<oldVal; k++) {
 8610:             var elementName = current[k];
 8611:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 8612:         }
 8613:     }
 8614:     return;
 8615: }
 8616: 
 8617: function categoryCheck(form) {
 8618:     if (form.elements['addcategory_name'].value == 'instcode') {
 8619:         alert('$instcode_reserved\\n$choose_again');
 8620:         return false;
 8621:     }
 8622:     if (form.elements['addcategory_name'].value == 'communities') {
 8623:         alert('$communities_reserved\\n$choose_again');
 8624:         return false;
 8625:     }
 8626:     return true;
 8627: }
 8628: 
 8629: // ]]>
 8630: </script>
 8631: 
 8632: ENDSCRIPT
 8633:     return $output;
 8634: }
 8635: 
 8636: sub initialize_categories {
 8637:     my ($itemcount) = @_;
 8638:     my ($datatable,$css_class,$chgstr);
 8639:     my %default_names = &Apache::lonlocal::texthash (
 8640:                       instcode    => 'Official courses (with institutional codes)',
 8641:                       communities => 'Communities',
 8642:                         );
 8643:     my $select0 = ' selected="selected"';
 8644:     my $select1 = '';
 8645:     foreach my $default ('instcode','communities') {
 8646:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8647:         $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','0'".');"';
 8648:         if ($default eq 'communities') {
 8649:             $select1 = $select0;
 8650:             $select0 = '';
 8651:         }
 8652:         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 8653:                      .'<select name="'.$default.'_pos">'
 8654:                      .'<option value="0"'.$select0.'>1</option>'
 8655:                      .'<option value="1"'.$select1.'>2</option>'
 8656:                      .'<option value="2">3</option></select>&nbsp;'
 8657:                      .$default_names{$default}
 8658:                      .'</span></td><td><span class="LC_nobreak">'
 8659:                      .'<label><input type="radio" name="'.$default.'" value="1" checked="checked" />'
 8660:                      .&mt('Display').'</label>&nbsp;<label>'
 8661:                      .'<input type="radio" name="'.$default.'" value="0" />'.&mt('Do not display')
 8662:                  .'</label></span></td></tr>';
 8663:         $itemcount ++;
 8664:     }
 8665:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8666:     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','0'".');"';
 8667:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 8668:                   .'<select name="addcategory_pos"'.$chgstr.'>'
 8669:                   .'<option value="0">1</option>'
 8670:                   .'<option value="1">2</option>'
 8671:                   .'<option value="2" selected="selected">3</option></select>&nbsp;'
 8672:                   .&mt('Add category').'</span></td><td><span class="LC_nobreak">'.&mt('Name:')
 8673:                   .'&nbsp;<input type="text" size="20" name="addcategory_name" value="" /></span>'
 8674:                   .'</td></tr>';
 8675:     return $datatable;
 8676: }
 8677: 
 8678: sub build_category_rows {
 8679:     my ($itemcount,$cats,$depth,$parent,$path,$idx) = @_;
 8680:     my ($text,$name,$item,$chgstr);
 8681:     if (ref($cats) eq 'ARRAY') {
 8682:         my $maxdepth = scalar(@{$cats});
 8683:         if (ref($cats->[$depth]) eq 'HASH') {
 8684:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
 8685:                 my $numchildren = @{$cats->[$depth]{$parent}};
 8686:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8687:                 $text .= '<td><table class="LC_data_table">';
 8688:                 my ($idxnum,$parent_name,$parent_item);
 8689:                 my $higher = $depth - 1;
 8690:                 if ($higher == 0) {
 8691:                     $parent_name = &escape($parent).'::'.$higher;
 8692:                 } else {
 8693:                     if (ref($path) eq 'ARRAY') {
 8694:                         $parent_name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
 8695:                     }
 8696:                 }
 8697:                 $parent_item = 'addcategory_pos_'.$parent_name;
 8698:                 for (my $j=0; $j<=$numchildren; $j++) {
 8699:                     if ($j < $numchildren) {
 8700:                         $name = $cats->[$depth]{$parent}[$j];
 8701:                         $item = &escape($name).':'.&escape($parent).':'.$depth;
 8702:                         $idxnum = $idx->{$item};
 8703:                     } else {
 8704:                         $name = $parent_name;
 8705:                         $item = $parent_item;
 8706:                     }
 8707:                     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'$parent_name','$item','$idxnum'".');"';
 8708:                     $text .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="'.$item.'"'.$chgstr.'>';
 8709:                     for (my $i=0; $i<=$numchildren; $i++) {
 8710:                         my $vpos = $i+1;
 8711:                         my $selstr;
 8712:                         if ($j == $i) {
 8713:                             $selstr = ' selected="selected" ';
 8714:                         }
 8715:                         $text .= '<option value="'.$i.'"'.$selstr.'>'.$vpos.'</option>';
 8716:                     }
 8717:                     $text .= '</select>&nbsp;';
 8718:                     if ($j < $numchildren) {
 8719:                         my $deeper = $depth+1;
 8720:                         $text .= $name.'&nbsp;'
 8721:                                  .'<label><input type="checkbox" name="deletecategory" value="'
 8722:                                  .$item.'" />'.&mt('Delete').'</label></span></td><td>';
 8723:                         if(ref($path) eq 'ARRAY') {
 8724:                             push(@{$path},$name);
 8725:                             $text .= &build_category_rows($itemcount,$cats,$deeper,$name,$path,$idx);
 8726:                             pop(@{$path});
 8727:                         }
 8728:                     } else {
 8729:                         $text .= &mt('Add subcategory:').'&nbsp;</span><input type="text" size="20" name="addcategory_name_';
 8730:                         if ($j == $numchildren) {
 8731:                             $text .= $name;
 8732:                         } else {
 8733:                             $text .= $item;
 8734:                         }
 8735:                         $text .= '" value="" />';
 8736:                     }
 8737:                     $text .= '</td></tr>';
 8738:                 }
 8739:                 $text .= '</table></td>';
 8740:             } else {
 8741:                 my $higher = $depth-1;
 8742:                 if ($higher == 0) {
 8743:                     $name = &escape($parent).'::'.$higher;
 8744:                 } else {
 8745:                     if (ref($path) eq 'ARRAY') {
 8746:                         $name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
 8747:                     }
 8748:                 }
 8749:                 my $colspan;
 8750:                 if ($parent ne 'instcode') {
 8751:                     $colspan = $maxdepth - $depth - 1;
 8752:                     $text .= '<td colspan="'.$colspan.'">'.&mt('Add subcategory:').'<input type="text" size="20" name="subcat_'.$name.'" value="" /></td>';
 8753:                 }
 8754:             }
 8755:         }
 8756:     }
 8757:     return $text;
 8758: }
 8759: 
 8760: sub modifiable_userdata_row {
 8761:     my ($context,$item,$settings,$numinrow,$rowcount,$usertypes,$fieldsref,$titlesref,
 8762:         $rowid,$customcss,$rowstyle) = @_;
 8763:     my ($role,$rolename,$statustype);
 8764:     $role = $item;
 8765:     if ($context eq 'cancreate') {
 8766:         if ($item =~ /^(emailusername)_(.+)$/) {
 8767:             $role = $1;
 8768:             $statustype = $2;
 8769:             if (ref($usertypes) eq 'HASH') {
 8770:                 if ($usertypes->{$statustype}) {
 8771:                     $rolename = &mt('Data provided by [_1]',$usertypes->{$statustype});
 8772:                 } else {
 8773:                     $rolename = &mt('Data provided by user');
 8774:                 }
 8775:             }
 8776:         }
 8777:     } elsif ($context eq 'selfcreate') {
 8778:         if (ref($usertypes) eq 'HASH') {
 8779:             $rolename = $usertypes->{$role};
 8780:         } else {
 8781:             $rolename = $role;
 8782:         }
 8783:     } else {
 8784:         if ($role eq 'cr') {
 8785:             $rolename = &mt('Custom role');
 8786:         } else {
 8787:             $rolename = &Apache::lonnet::plaintext($role);
 8788:         }
 8789:     }
 8790:     my (@fields,%fieldtitles);
 8791:     if (ref($fieldsref) eq 'ARRAY') {
 8792:         @fields = @{$fieldsref};
 8793:     } else {
 8794:         @fields = ('lastname','firstname','middlename','generation',
 8795:                    'permanentemail','id');
 8796:     }
 8797:     if ((ref($titlesref) eq 'HASH')) {
 8798:         %fieldtitles = %{$titlesref};
 8799:     } else {
 8800:         %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 8801:     }
 8802:     my $output;
 8803:     my $css_class;
 8804:     if ($rowcount%2) {
 8805:         $css_class = 'LC_odd_row';
 8806:     }
 8807:     if ($customcss) {
 8808:         $css_class .= " $customcss";
 8809:     }
 8810:     $css_class =~ s/^\s+//;
 8811:     if ($css_class) {
 8812:         $css_class = ' class="'.$css_class.'"';
 8813:     }
 8814:     if ($rowstyle) {
 8815:         $css_class .= ' style="'.$rowstyle.'"';
 8816:     }
 8817:     if ($rowid) {
 8818:         $rowid = ' id="'.$rowid.'"';
 8819:     }
 8820: 
 8821:     $output = '<tr '.$css_class.$rowid.'>'.
 8822:               '<td><span class="LC_nobreak">'.$rolename.'</span></td>'.
 8823:               '<td class="LC_left_item" colspan="2"><table>';
 8824:     my $rem;
 8825:     my %checks;
 8826:     if (ref($settings) eq 'HASH') {
 8827:         if (ref($settings->{$context}) eq 'HASH') {
 8828:             if (ref($settings->{$context}->{$role}) eq 'HASH') {
 8829:                 my $hashref = $settings->{$context}->{$role};
 8830:                 if ($role eq 'emailusername') {
 8831:                     if ($statustype) {
 8832:                         if (ref($settings->{$context}->{$role}->{$statustype}) eq 'HASH') {
 8833:                             $hashref = $settings->{$context}->{$role}->{$statustype};
 8834:                             if (ref($hashref) eq 'HASH') { 
 8835:                                 foreach my $field (@fields) {
 8836:                                     if ($hashref->{$field}) {
 8837:                                         $checks{$field} = $hashref->{$field};
 8838:                                     }
 8839:                                 }
 8840:                             }
 8841:                         }
 8842:                     }
 8843:                 } else {
 8844:                     if (ref($hashref) eq 'HASH') {
 8845:                         foreach my $field (@fields) {
 8846:                             if ($hashref->{$field}) {
 8847:                                 $checks{$field} = ' checked="checked" ';
 8848:                             }
 8849:                         }
 8850:                     }
 8851:                 }
 8852:             }
 8853:         }
 8854:     }
 8855: 
 8856:     my $total = scalar(@fields);
 8857:     for (my $i=0; $i<$total; $i++) {
 8858:         $rem = $i%($numinrow);
 8859:         if ($rem == 0) {
 8860:             if ($i > 0) {
 8861:                 $output .= '</tr>';
 8862:             }
 8863:             $output .= '<tr>';
 8864:         }
 8865:         my $check = ' ';
 8866:         unless ($role eq 'emailusername') {
 8867:             if (exists($checks{$fields[$i]})) {
 8868:                 $check = $checks{$fields[$i]};
 8869:             } else {
 8870:                 if ($role eq 'st') {
 8871:                     if (ref($settings) ne 'HASH') {
 8872:                         $check = ' checked="checked" '; 
 8873:                     }
 8874:                 }
 8875:             }
 8876:         }
 8877:         $output .= '<td class="LC_left_item">'.
 8878:                    '<span class="LC_nobreak">';
 8879:         if ($role eq 'emailusername') {
 8880:             unless ($checks{$fields[$i]} =~ /^(required|optional)$/) {
 8881:                 $checks{$fields[$i]} = 'omit';
 8882:             }
 8883:             foreach my $option ('required','optional','omit') {
 8884:                 my $checked='';
 8885:                 if ($checks{$fields[$i]} eq $option) {
 8886:                     $checked='checked="checked" ';
 8887:                 }
 8888:                 $output .= '<label>'.
 8889:                            '<input type="radio" name="canmodify_'.$item.'_'.$fields[$i].'" value="'.$option.'" '.$checked.'/>'.
 8890:                            &mt($option).'</label>'.('&nbsp;' x2);
 8891:             }
 8892:             $output .= '<i>'.$fieldtitles{$fields[$i]}.'</i>';
 8893:         } else {
 8894:             $output .= '<label>'.
 8895:                        '<input type="checkbox" name="canmodify_'.$role.'" '.
 8896:                        'value="'.$fields[$i].'"'.$check.'/>'.$fieldtitles{$fields[$i]}.
 8897:                        '</label>';
 8898:         }
 8899:         $output .= '</span></td>';
 8900:     }
 8901:     $rem = $total%$numinrow;
 8902:     my $colsleft;
 8903:     if ($rem) {
 8904:         $colsleft = $numinrow - $rem;
 8905:     }
 8906:     if ($colsleft > 1) {
 8907:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 8908:                    '&nbsp;</td>';
 8909:     } elsif ($colsleft == 1) {
 8910:         $output .= '<td class="LC_left_item">&nbsp;</td>';
 8911:     }
 8912:     $output .= '</tr></table></td></tr>';
 8913:     return $output;
 8914: }
 8915: 
 8916: sub insttypes_row {
 8917:     my ($settings,$types,$usertypes,$dom,$numinrow,$othertitle,$context,$rowtotal,$onclick,
 8918:         $customcss,$rowstyle) = @_;
 8919:     my %lt = &Apache::lonlocal::texthash (
 8920:                       cansearch => 'Users allowed to search',
 8921:                       statustocreate => 'Institutional affiliation(s) able to create own account (login/SSO)',
 8922:                       lockablenames => 'User preference to lock name',
 8923:                       selfassign    => 'Self-reportable affiliations',
 8924:                       overrides     => "Override domain's helpdesk settings based on requester's affiliation",
 8925:              );
 8926:     my $showdom;
 8927:     if ($context eq 'cansearch') {
 8928:         $showdom = ' ('.$dom.')';
 8929:     }
 8930:     my $class = 'LC_left_item';
 8931:     if ($context eq 'statustocreate') {
 8932:         $class = 'LC_right_item';
 8933:     }
 8934:     my $css_class;
 8935:     if ($$rowtotal%2) {
 8936:         $css_class = 'LC_odd_row';
 8937:     }
 8938:     if ($customcss) {
 8939:         $css_class .= ' '.$customcss;
 8940:     }
 8941:     $css_class =~ s/^\s+//;
 8942:     if ($css_class) {
 8943:         $css_class = ' class="'.$css_class.'"';
 8944:     }
 8945:     if ($rowstyle) {
 8946:         $css_class .= ' style="'.$rowstyle.'"';
 8947:     }
 8948:     if ($onclick) {
 8949:         $onclick = 'onclick="'.$onclick.'" ';
 8950:     }
 8951:     my $output = '<tr'.$css_class.'>'.
 8952:                  '<td>'.$lt{$context}.$showdom.
 8953:                  '</td><td class="'.$class.'" colspan="2"><table>';
 8954:     my $rem;
 8955:     if (ref($types) eq 'ARRAY') {
 8956:         for (my $i=0; $i<@{$types}; $i++) {
 8957:             if (defined($usertypes->{$types->[$i]})) {
 8958:                 my $rem = $i%($numinrow);
 8959:                 if ($rem == 0) {
 8960:                     if ($i > 0) {
 8961:                         $output .= '</tr>';
 8962:                     }
 8963:                     $output .= '<tr>';
 8964:                 }
 8965:                 my $check = ' ';
 8966:                 if (ref($settings) eq 'HASH') {
 8967:                     if (ref($settings->{$context}) eq 'ARRAY') {
 8968:                         if (grep(/^\Q$types->[$i]\E$/,@{$settings->{$context}})) {
 8969:                             $check = ' checked="checked" ';
 8970:                         }
 8971:                     } elsif (ref($settings->{$context}) eq 'HASH') {
 8972:                         if (ref($settings->{$context}->{$types->[$i]}) eq 'HASH') {
 8973:                             $check = ' checked="checked" ';
 8974:                         }
 8975:                     } elsif ($context eq 'statustocreate') {
 8976:                         $check = ' checked="checked" ';
 8977:                     }
 8978:                 }
 8979:                 $output .= '<td class="LC_left_item">'.
 8980:                            '<span class="LC_nobreak"><label>'.
 8981:                            '<input type="checkbox" name="'.$context.'" '.
 8982:                            'value="'.$types->[$i].'"'.$check.$onclick.'/>'.
 8983:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 8984:             }
 8985:         }
 8986:         $rem = @{$types}%($numinrow);
 8987:     }
 8988:     my $colsleft = $numinrow - $rem;
 8989:     if ($context eq 'overrides') {
 8990:         if ($colsleft > 1) {
 8991:             $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 8992:         } else {
 8993:             $output .= '<td class="LC_left_item">';
 8994:         }
 8995:         $output .= '&nbsp;';
 8996:     } else {
 8997:         if ($rem == 0) {
 8998:             $output .= '<tr>';
 8999:         }
 9000:         if ($colsleft > 1) {
 9001:             $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 9002:         } else {
 9003:             $output .= '<td class="LC_left_item">';
 9004:         }
 9005:         my $defcheck = ' ';
 9006:         if (ref($settings) eq 'HASH') {  
 9007:             if (ref($settings->{$context}) eq 'ARRAY') {
 9008:                 if (grep(/^default$/,@{$settings->{$context}})) {
 9009:                     $defcheck = ' checked="checked" ';
 9010:                 }
 9011:             } elsif ($context eq 'statustocreate') {
 9012:                 $defcheck = ' checked="checked" ';
 9013:             }
 9014:         }
 9015:         $output .= '<span class="LC_nobreak"><label>'.
 9016:                    '<input type="checkbox" name="'.$context.'" '.
 9017:                    'value="default"'.$defcheck.$onclick.' />'.
 9018:                    $othertitle.'</label></span>';
 9019:     }
 9020:     $output .= '</td></tr></table></td></tr>';
 9021:     return $output;
 9022: }
 9023: 
 9024: sub sorted_searchtitles {
 9025:     my %searchtitles = &Apache::lonlocal::texthash(
 9026:                          'uname' => 'username',
 9027:                          'lastname' => 'last name',
 9028:                          'lastfirst' => 'last name, first name',
 9029:                      );
 9030:     my @titleorder = ('uname','lastname','lastfirst');
 9031:     return (\%searchtitles,\@titleorder);
 9032: }
 9033: 
 9034: sub sorted_searchtypes {
 9035:     my %srchtypes_desc = (
 9036:                            exact    => 'is exact match',
 9037:                            contains => 'contains ..',
 9038:                            begins   => 'begins with ..',
 9039:                          );
 9040:     my @srchtypeorder = ('exact','begins','contains');
 9041:     return (\%srchtypes_desc,\@srchtypeorder);
 9042: }
 9043: 
 9044: sub usertype_update_row {
 9045:     my ($settings,$usertypes,$fieldtitles,$fields,$types,$rownums) = @_;
 9046:     my $datatable;
 9047:     my $numinrow = 4;
 9048:     foreach my $type (@{$types}) {
 9049:         if (defined($usertypes->{$type})) {
 9050:             $$rownums ++;
 9051:             my $css_class = $$rownums%2?' class="LC_odd_row"':'';
 9052:             $datatable .= '<tr'.$css_class.'><td>'.$usertypes->{$type}.
 9053:                           '</td><td class="LC_left_item"><table>';
 9054:             for (my $i=0; $i<@{$fields}; $i++) {
 9055:                 my $rem = $i%($numinrow);
 9056:                 if ($rem == 0) {
 9057:                     if ($i > 0) {
 9058:                         $datatable .= '</tr>';
 9059:                     }
 9060:                     $datatable .= '<tr>';
 9061:                 }
 9062:                 my $check = ' ';
 9063:                 if (ref($settings) eq 'HASH') {
 9064:                     if (ref($settings->{'fields'}) eq 'HASH') {
 9065:                         if (ref($settings->{'fields'}{$type}) eq 'ARRAY') {
 9066:                             if (grep(/^\Q$fields->[$i]\E$/,@{$settings->{'fields'}{$type}})) {
 9067:                                 $check = ' checked="checked" ';
 9068:                             }
 9069:                         }
 9070:                     }
 9071:                 }
 9072: 
 9073:                 if ($i == @{$fields}-1) {
 9074:                     my $colsleft = $numinrow - $rem;
 9075:                     if ($colsleft > 1) {
 9076:                         $datatable .= '<td colspan="'.$colsleft.'">';
 9077:                     } else {
 9078:                         $datatable .= '<td>';
 9079:                     }
 9080:                 } else {
 9081:                     $datatable .= '<td>';
 9082:                 }
 9083:                 $datatable .= '<span class="LC_nobreak"><label>'.
 9084:                               '<input type="checkbox" name="updateable_'.$type.
 9085:                               '_'.$fields->[$i].'" value="1"'.$check.'/>'.
 9086:                               $fieldtitles->{$fields->[$i]}.'</label></span></td>';
 9087:             }
 9088:             $datatable .= '</tr></table></td></tr>';
 9089:         }
 9090:     }
 9091:     return $datatable;
 9092: }
 9093: 
 9094: sub modify_login {
 9095:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
 9096:     my ($resulttext,$errors,$colchgtext,%changes,%colchanges,%newfile,%newurl,
 9097:         %curr_loginvia,%loginhash,@currlangs,@newlangs,$addedfile,%title,@offon,
 9098:         %currsaml,%saml,%samltext,%samlimg,%samlalt,%samlurl,%samltitle,%samlnotsso);
 9099:     %title = ( coursecatalog => 'Display course catalog',
 9100:                adminmail => 'Display administrator E-mail address',
 9101:                helpdesk  => 'Display "Contact Helpdesk" link',
 9102:                newuser => 'Link for visitors to create a user account',
 9103:                loginheader => 'Log-in box header',
 9104:                saml => 'Dual SSO and non-SSO login');
 9105:     @offon = ('off','on');
 9106:     if (ref($domconfig{login}) eq 'HASH') {
 9107:         if (ref($domconfig{login}{loginvia}) eq 'HASH') {
 9108:             foreach my $lonhost (keys(%{$domconfig{login}{loginvia}})) {
 9109:                 $curr_loginvia{$lonhost} = $domconfig{login}{loginvia}{$lonhost};
 9110:             }
 9111:         }
 9112:         if (ref($domconfig{login}{'saml'}) eq 'HASH') {
 9113:             foreach my $lonhost (keys(%{$domconfig{login}{'saml'}})) {
 9114:                 if (ref($domconfig{login}{'saml'}{$lonhost}) eq 'HASH') {
 9115:                     $currsaml{$lonhost} = $domconfig{login}{'saml'}{$lonhost};
 9116:                     $saml{$lonhost} = 1;
 9117:                     $samltext{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'text'};
 9118:                     $samlurl{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'url'};
 9119:                     $samlalt{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'alt'};
 9120:                     $samlimg{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'img'};
 9121:                     $samltitle{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'title'};
 9122:                     $samlnotsso{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'notsso'};
 9123:                 }
 9124:             }
 9125:         }
 9126:     }
 9127:     ($errors,%colchanges) = &modify_colors($r,$dom,$confname,['login'],
 9128:                                            \%domconfig,\%loginhash);
 9129:     my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
 9130:     foreach my $item (@toggles) {
 9131:         $loginhash{login}{$item} = $env{'form.'.$item};
 9132:     }
 9133:     $loginhash{login}{loginheader} = $env{'form.loginheader'};
 9134:     if (ref($colchanges{'login'}) eq 'HASH') {  
 9135:         $colchgtext = &display_colorchgs($dom,\%colchanges,['login'],
 9136:                                          \%loginhash);
 9137:     }
 9138: 
 9139:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 9140:     my %domservers = &Apache::lonnet::get_servers($dom);
 9141:     my @loginvia_attribs = ('serverpath','custompath','exempt');
 9142:     if (keys(%servers) > 1) {
 9143:         foreach my $lonhost (keys(%servers)) {
 9144:             next if ($env{'form.'.$lonhost.'_server'} eq $lonhost);
 9145:             if (ref($curr_loginvia{$lonhost}) eq 'HASH') {
 9146:                 if ($env{'form.'.$lonhost.'_server'} eq $curr_loginvia{$lonhost}{'server'}) {
 9147:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $curr_loginvia{$lonhost}{'server'};
 9148:                 } elsif ($curr_loginvia{$lonhost}{'server'} ne '') {
 9149:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
 9150:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
 9151:                         $changes{'loginvia'}{$lonhost} = 1;
 9152:                     } else {
 9153:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = '';
 9154:                         $changes{'loginvia'}{$lonhost} = 1;
 9155:                     }
 9156:                 } else {
 9157:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
 9158:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
 9159:                         $changes{'loginvia'}{$lonhost} = 1;
 9160:                     }
 9161:                 }
 9162:                 if ($loginhash{login}{loginvia}{$lonhost}{'server'} eq '') {
 9163:                     foreach my $item (@loginvia_attribs) {
 9164:                         $loginhash{login}{loginvia}{$lonhost}{$item} = '';
 9165:                     }
 9166:                 } else {
 9167:                     foreach my $item (@loginvia_attribs) {
 9168:                         my $new = $env{'form.'.$lonhost.'_'.$item};
 9169:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
 9170:                             $env{'form.'.$lonhost.'_custompath'} =~ s/\s+//g;
 9171:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
 9172:                                 $new = '/';
 9173:                             }
 9174:                         }
 9175:                         if (($item eq 'custompath') && 
 9176:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
 9177:                             $new = '';
 9178:                         }
 9179:                         if ($new ne $curr_loginvia{$lonhost}{$item}) {
 9180:                             $changes{'loginvia'}{$lonhost} = 1;
 9181:                         }
 9182:                         if ($item eq 'exempt') {
 9183:                             $new = &check_exempt_addresses($new);
 9184:                         }
 9185:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
 9186:                     }
 9187:                 }
 9188:             } else {
 9189:                 if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
 9190:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
 9191:                     $changes{'loginvia'}{$lonhost} = 1;
 9192:                     foreach my $item (@loginvia_attribs) {
 9193:                         my $new = $env{'form.'.$lonhost.'_'.$item};
 9194:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
 9195:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
 9196:                                 $new = '/';
 9197:                             }
 9198:                         }
 9199:                         if (($item eq 'custompath') && 
 9200:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
 9201:                             $new = '';
 9202:                         }
 9203:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
 9204:                     }
 9205:                 }
 9206:             }
 9207:         }
 9208:     }
 9209: 
 9210:     my $servadm = $r->dir_config('lonAdmEMail');
 9211:     my %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
 9212:     if (ref($domconfig{'login'}) eq 'HASH') {
 9213:         if (ref($domconfig{'login'}{'helpurl'}) eq 'HASH') {
 9214:             foreach my $lang (sort(keys(%{$domconfig{'login'}{'helpurl'}}))) {
 9215:                 if ($lang eq 'nolang') {
 9216:                     push(@currlangs,$lang);
 9217:                 } elsif (defined($langchoices{$lang})) {
 9218:                     push(@currlangs,$lang);
 9219:                 } else {
 9220:                     next;
 9221:                 }
 9222:             }
 9223:         }
 9224:     }
 9225:     my @delurls = &Apache::loncommon::get_env_multiple('form.loginhelpurl_del');
 9226:     if (@currlangs > 0) {
 9227:         foreach my $lang (@currlangs) {
 9228:             if (grep(/^\Q$lang\E$/,@delurls)) {
 9229:                 $changes{'helpurl'}{$lang} = 1;
 9230:             } elsif ($env{'form.loginhelpurl_'.$lang.'.filename'}) {
 9231:                 $changes{'helpurl'}{$lang} = 1;
 9232:                 $newfile{$lang} = $env{'form.loginhelpurl_'.$lang.'.filename'};
 9233:                 push(@newlangs,$lang);
 9234:             } else {
 9235:                 $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
 9236:             }
 9237:         }
 9238:     }
 9239:     unless (grep(/^nolang$/,@currlangs)) {
 9240:         if ($env{'form.loginhelpurl_nolang.filename'}) {
 9241:             $changes{'helpurl'}{'nolang'} = 1;
 9242:             $newfile{'nolang'} = $env{'form.loginhelpurl_nolang.filename'};
 9243:             push(@newlangs,'nolang');
 9244:         }
 9245:     }
 9246:     if ($env{'form.loginhelpurl_add_lang'}) {
 9247:         if ((defined($langchoices{$env{'form.loginhelpurl_add_lang'}})) &&
 9248:             ($env{'form.loginhelpurl_add_file.filename'})) {
 9249:             $newfile{$env{'form.loginhelpurl_add_lang'}} = $env{'form.loginhelpurl_add_file.filename'};
 9250:             $addedfile = $env{'form.loginhelpurl_add_lang'};
 9251:         }
 9252:     }
 9253:     if ((@newlangs > 0) || ($addedfile)) {
 9254:         my $error;
 9255:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
 9256:         if ($configuserok eq 'ok') {
 9257:             if ($switchserver) {
 9258:                 $error = &mt("Upload of custom help file is not permitted to this server: [_1]",$switchserver);
 9259:             } elsif ($author_ok eq 'ok') {
 9260:                 my @allnew = @newlangs;
 9261:                 if ($addedfile ne '') {
 9262:                     push(@allnew,$addedfile);
 9263:                 }
 9264:                 foreach my $lang (@allnew) {
 9265:                     my $formelem = 'loginhelpurl_'.$lang;
 9266:                     if ($lang eq $env{'form.loginhelpurl_add_lang'}) {
 9267:                         $formelem = 'loginhelpurl_add_file';
 9268:                     }
 9269:                     (my $result,$newurl{$lang}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
 9270:                                                                "help/$lang",'','',$newfile{$lang});
 9271:                     if ($result eq 'ok') {
 9272:                         $loginhash{'login'}{'helpurl'}{$lang} = $newurl{$lang};
 9273:                         $changes{'helpurl'}{$lang} = 1;
 9274:                     } else {
 9275:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$newfile{$lang},$result);
 9276:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
 9277:                         if ((grep(/^\Q$lang\E$/,@currlangs)) &&
 9278:                             (!grep(/^\Q$lang\E$/,@delurls))) {
 9279:                             $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
 9280:                         }
 9281:                     }
 9282:                 }
 9283:             } else {
 9284:                 $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);
 9285:             }
 9286:         } else {
 9287:             $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);
 9288:         }
 9289:         if ($error) {
 9290:             &Apache::lonnet::logthis($error);
 9291:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
 9292:         }
 9293:     }
 9294: 
 9295:     my (%currheadtagurls,%currexempt,@newhosts,%newheadtagurls,%possexempt);
 9296:     if (ref($domconfig{'login'}) eq 'HASH') {
 9297:         if (ref($domconfig{'login'}{'headtag'}) eq 'HASH') {
 9298:             foreach my $lonhost (keys(%{$domconfig{'login'}{'headtag'}})) {
 9299:                 if ($domservers{$lonhost}) {
 9300:                     if (ref($domconfig{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
 9301:                         $currheadtagurls{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'url'};
 9302:                         $currexempt{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'exempt'};
 9303:                     }
 9304:                 }
 9305:             }
 9306:         }
 9307:     }
 9308:     my @delheadtagurls = &Apache::loncommon::get_env_multiple('form.loginheadtag_del');
 9309:     foreach my $lonhost (sort(keys(%domservers))) {
 9310:         if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
 9311:             $changes{'headtag'}{$lonhost} = 1;
 9312:         } else {
 9313:             if ($env{'form.loginheadtagexempt_'.$lonhost}) {
 9314:                 $possexempt{$lonhost} = &check_exempt_addresses($env{'form.loginheadtagexempt_'.$lonhost});
 9315:             }
 9316:             if ($env{'form.loginheadtag_'.$lonhost.'.filename'}) {
 9317:                 push(@newhosts,$lonhost);
 9318:             } elsif ($currheadtagurls{$lonhost}) {
 9319:                 $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $currheadtagurls{$lonhost};
 9320:                 if ($currexempt{$lonhost}) {
 9321:                     if ((!exists($possexempt{$lonhost})) || ($possexempt{$lonhost} ne $currexempt{$lonhost})) {
 9322:                         $changes{'headtag'}{$lonhost} = 1;
 9323:                     }
 9324:                 } elsif ($possexempt{$lonhost}) {
 9325:                     $changes{'headtag'}{$lonhost} = 1;
 9326:                 }
 9327:                 if ($possexempt{$lonhost}) {
 9328:                     $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
 9329:                 }
 9330:             }
 9331:         }
 9332:     }
 9333:     if (@newhosts) {
 9334:         my $error;
 9335:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
 9336:         if ($configuserok eq 'ok') {
 9337:             if ($switchserver) {
 9338:                 $error = &mt("Upload of custom markup is not permitted to this server: [_1]",$switchserver);
 9339:             } elsif ($author_ok eq 'ok') {
 9340:                 foreach my $lonhost (@newhosts) {
 9341:                     my $formelem = 'loginheadtag_'.$lonhost;
 9342:                     (my $result,$newheadtagurls{$lonhost}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
 9343:                                                                           "login/headtag/$lonhost",'','',
 9344:                                                                           $env{'form.loginheadtag_'.$lonhost.'.filename'});
 9345:                     if ($result eq 'ok') {
 9346:                         $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $newheadtagurls{$lonhost};
 9347:                         $changes{'headtag'}{$lonhost} = 1;
 9348:                         if ($possexempt{$lonhost}) {
 9349:                             $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
 9350:                         }
 9351:                     } else {
 9352:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",
 9353:                                            $newheadtagurls{$lonhost},$result);
 9354:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
 9355:                         if ((grep(/^\Q$lonhost\E$/,keys(%currheadtagurls))) &&
 9356:                             (!grep(/^\Q$lonhost\E$/,@delheadtagurls))) {
 9357:                             $loginhash{'login'}{'headtag'}{$lonhost} = $currheadtagurls{$lonhost};
 9358:                         }
 9359:                     }
 9360:                 }
 9361:             } else {
 9362:                 $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);
 9363:             }
 9364:         } else {
 9365:             $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);
 9366:         }
 9367:         if ($error) {
 9368:             &Apache::lonnet::logthis($error);
 9369:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
 9370:         }
 9371:     }
 9372:     my @delsamlimg = &Apache::loncommon::get_env_multiple('form.saml_img_del');
 9373:     my @newsamlimgs;
 9374:     foreach my $lonhost (keys(%domservers)) {
 9375:         if ($env{'form.saml_'.$lonhost}) {
 9376:             if ($env{'form.saml_img_'.$lonhost.'.filename'}) {
 9377:                 push(@newsamlimgs,$lonhost);
 9378:             }
 9379:             foreach my $item ('text','alt','url','title','notsso') {
 9380:                 $env{'form.saml_'.$item.'_'.$lonhost} =~ s/^\s+|\s+$//g;
 9381:             }
 9382:             if ($saml{$lonhost}) {
 9383:                 if (grep(/^\Q$lonhost\E$/,@delsamlimg)) {
 9384: #FIXME Need to obsolete published image
 9385:                     delete($currsaml{$lonhost}{'img'});
 9386:                     $changes{'saml'}{$lonhost} = 1;
 9387:                 }
 9388:                 if ($env{'form.saml_alt_'.$lonhost} ne $samlalt{$lonhost}) {
 9389:                     $changes{'saml'}{$lonhost} = 1;
 9390:                 }
 9391:                 if ($env{'form.saml_text_'.$lonhost} ne $samltext{$lonhost}) {
 9392:                     $changes{'saml'}{$lonhost} = 1;
 9393:                 }
 9394:                 if ($env{'form.saml_url_'.$lonhost} ne $samlurl{$lonhost}) {
 9395:                     $changes{'saml'}{$lonhost} = 1;
 9396:                 }
 9397:                 if ($env{'form.saml_title_'.$lonhost} ne $samltitle{$lonhost}) {
 9398:                     $changes{'saml'}{$lonhost} = 1;
 9399:                 }
 9400:                 if ($env{'form.saml_notsso_'.$lonhost} ne $samlnotsso{$lonhost}) {
 9401:                     $changes{'saml'}{$lonhost} = 1;
 9402:                 }
 9403:             } else {
 9404:                 $changes{'saml'}{$lonhost} = 1;
 9405:             }
 9406:             foreach my $item ('text','alt','url','title','notsso') {
 9407:                 $currsaml{$lonhost}{$item} = $env{'form.saml_'.$item.'_'.$lonhost};
 9408:             }
 9409:         } else {
 9410:             if ($saml{$lonhost}) {
 9411:                 $changes{'saml'}{$lonhost} = 1;
 9412:                 delete($currsaml{$lonhost});
 9413:             }
 9414:         }
 9415:     }
 9416:     foreach my $posshost (keys(%currsaml)) {
 9417:         unless (exists($domservers{$posshost})) {
 9418:             delete($currsaml{$posshost});
 9419:         }
 9420:     }
 9421:     %{$loginhash{'login'}{'saml'}} = %currsaml;
 9422:     if (@newsamlimgs) {
 9423:         my $error;
 9424:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
 9425:         if ($configuserok eq 'ok') {
 9426:             if ($switchserver) {
 9427:                 $error = &mt("Upload of SSO Button Image is not permitted to this server: [_1].",$switchserver);
 9428:             } elsif ($author_ok eq 'ok') {
 9429:                 foreach my $lonhost (@newsamlimgs) {
 9430:                     my $formelem = 'saml_img_'.$lonhost;
 9431:                     my ($result,$imgurl) = &publishlogo($r,'upload',$formelem,$dom,$confname,
 9432:                                                         "login/saml/$lonhost",'','',
 9433:                                                         $env{'form.saml_img_'.$lonhost.'.filename'});
 9434:                     if ($result eq 'ok') {
 9435:                         $currsaml{$lonhost}{'img'} = $imgurl;
 9436:                         $loginhash{'login'}{'saml'}{$lonhost}{'img'} = $imgurl;
 9437:                         $changes{'saml'}{$lonhost} = 1;
 9438:                     } else {
 9439:                         my $puberror = &mt("Upload of SSO button image failed for [_1] because an error occurred publishing the file in RES space. Error was: [_2].",
 9440:                                            $lonhost,$result);
 9441:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
 9442:                     }
 9443:                 }
 9444:             } else {
 9445:                 $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);
 9446:             }
 9447:         } else {
 9448:             $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);
 9449:         }
 9450:         if ($error) {
 9451:             &Apache::lonnet::logthis($error);
 9452:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
 9453:         }
 9454:     }
 9455:     &process_captcha('login',\%changes,$loginhash{'login'},$domconfig{'login'});
 9456: 
 9457:     my $defaulthelpfile = '/adm/loginproblems.html';
 9458:     my $defaulttext = &mt('Default in use');
 9459: 
 9460:     my $putresult = &Apache::lonnet::put_dom('configuration',\%loginhash,
 9461:                                              $dom);
 9462:     if ($putresult eq 'ok') {
 9463:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
 9464:         my %defaultchecked = (
 9465:                     'coursecatalog' => 'on',
 9466:                     'helpdesk'      => 'on',
 9467:                     'adminmail'     => 'off',
 9468:                     'newuser'       => 'off',
 9469:         );
 9470:         if (ref($domconfig{'login'}) eq 'HASH') {
 9471:             foreach my $item (@toggles) {
 9472:                 if ($defaultchecked{$item} eq 'on') { 
 9473:                     if (($domconfig{'login'}{$item} eq '0') &&
 9474:                         ($env{'form.'.$item} eq '1')) {
 9475:                         $changes{$item} = 1;
 9476:                     } elsif (($domconfig{'login'}{$item} eq '' ||
 9477:                               $domconfig{'login'}{$item} eq '1') &&
 9478:                              ($env{'form.'.$item} eq '0')) {
 9479:                         $changes{$item} = 1;
 9480:                     }
 9481:                 } elsif ($defaultchecked{$item} eq 'off') {
 9482:                     if (($domconfig{'login'}{$item} eq '1') &&
 9483:                         ($env{'form.'.$item} eq '0')) {
 9484:                         $changes{$item} = 1;
 9485:                     } elsif (($domconfig{'login'}{$item} eq '' ||
 9486:                               $domconfig{'login'}{$item} eq '0') &&
 9487:                              ($env{'form.'.$item} eq '1')) {
 9488:                         $changes{$item} = 1;
 9489:                     }
 9490:                 }
 9491:             }
 9492:         }
 9493:         if (keys(%changes) > 0 || $colchgtext) {
 9494:             &Apache::loncommon::devalidate_domconfig_cache($dom);
 9495:             if (exists($changes{'saml'})) {
 9496:                 my $hostid_in_use;
 9497:                 my @hosts = &Apache::lonnet::current_machine_ids();
 9498:                 if (@hosts > 1) {
 9499:                     foreach my $hostid (@hosts) {
 9500:                         if (&Apache::lonnet::host_domain($hostid) eq $dom) {
 9501:                             $hostid_in_use = $hostid;
 9502:                             last;
 9503:                         }
 9504:                     }
 9505:                 } else {
 9506:                     $hostid_in_use = $r->dir_config('lonHostID');
 9507:                 }
 9508:                 if (($hostid_in_use) &&
 9509:                     (&Apache::lonnet::host_domain($hostid_in_use) eq $dom)) {
 9510:                     &Apache::lonnet::devalidate_cache_new('samllanding',$hostid_in_use);
 9511:                 }
 9512:                 if (ref($lastactref) eq 'HASH') {
 9513:                     if (ref($changes{'saml'}) eq 'HASH') {
 9514:                         my %updates;
 9515:                         map { $updates{$_} = 1; } keys(%{$changes{'saml'}});
 9516:                         $lastactref->{'samllanding'} = \%updates;
 9517:                     }
 9518:                 }
 9519:             }
 9520:             if (ref($lastactref) eq 'HASH') {
 9521:                 $lastactref->{'domainconfig'} = 1;
 9522:             }
 9523:             $resulttext = &mt('Changes made:').'<ul>';
 9524:             foreach my $item (sort(keys(%changes))) {
 9525:                 if ($item eq 'loginvia') {
 9526:                     if (ref($changes{$item}) eq 'HASH') {
 9527:                         $resulttext .= '<li>'.&mt('Log-in page availability:').'<ul>';
 9528:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
 9529:                             if (defined($servers{$loginhash{login}{loginvia}{$lonhost}{'server'}})) {
 9530:                                 if (ref($loginhash{login}{loginvia}{$lonhost}) eq 'HASH') {
 9531:                                     my $protocol = $Apache::lonnet::protocol{$env{'form.'.$lonhost.'_server'}};
 9532:                                     $protocol = 'http' if ($protocol ne 'https');
 9533:                                     my $target = $protocol.'://'.$servers{$env{'form.'.$lonhost.'_server'}};
 9534: 
 9535:                                     if ($loginhash{login}{loginvia}{$lonhost}{'serverpath'} eq 'custom') {
 9536:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'custompath'};
 9537:                                     } else {
 9538:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'serverpath'}; 
 9539:                                     }
 9540:                                     $resulttext .= '<li>'.&mt('Server: [_1] log-in page redirects to [_2].',$servers{$lonhost},'<a href="'.$target.'">'.$target.'</a>');
 9541:                                     if ($loginhash{login}{loginvia}{$lonhost}{'exempt'} ne '') {
 9542:                                         $resulttext .= '&nbsp;'.&mt('No redirection for clients from following IPs:').'&nbsp;'.$loginhash{login}{loginvia}{$lonhost}{'exempt'};
 9543:                                     }
 9544:                                     $resulttext .= '</li>';
 9545:                                 } else {
 9546:                                     $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$lonhost).'</li>';
 9547:                                 }
 9548:                             } else {
 9549:                                 $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$servers{$lonhost}).'</li>';
 9550:                             }
 9551:                         }
 9552:                         $resulttext .= '</ul></li>';
 9553:                     }
 9554:                 } elsif ($item eq 'helpurl') {
 9555:                     if (ref($changes{$item}) eq 'HASH') {
 9556:                         foreach my $lang (sort(keys(%{$changes{$item}}))) {
 9557:                             if (grep(/^\Q$lang\E$/,@delurls)) {
 9558:                                 my ($chg,$link);
 9559:                                 $link = &Apache::loncommon::modal_link($defaulthelpfile,$defaulttext,600,500);
 9560:                                 if ($lang eq 'nolang') {
 9561:                                     $chg = &mt('custom log-in help file removed for no preferred language; [_1]',$link);
 9562:                                 } else {
 9563:                                     $chg = &mt('custom log-in help file removed for specific language: [_1]; [_2]',$langchoices{$lang},$link);
 9564:                                 }
 9565:                                 $resulttext .= '<li>'.$chg.'</li>';
 9566:                             } else {
 9567:                                 my $chg;
 9568:                                 if ($lang eq 'nolang') {
 9569:                                     $chg = &mt('custom log-in help file for no preferred language');
 9570:                                 } else {
 9571:                                     $chg = &mt('custom log-in help file for specific language: [_1]',$langchoices{$lang});
 9572:                                 }
 9573:                                 $resulttext .= '<li>'.&Apache::loncommon::modal_link(
 9574:                                                       $loginhash{'login'}{'helpurl'}{$lang}.
 9575:                                                       '?inhibitmenu=yes',$chg,600,500).
 9576:                                                '</li>';
 9577:                             }
 9578:                         }
 9579:                     }
 9580:                 } elsif ($item eq 'headtag') {
 9581:                     if (ref($changes{$item}) eq 'HASH') {
 9582:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
 9583:                             if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
 9584:                                 $resulttext .= '<li>'.&mt('custom markup file removed for [_1]',$domservers{$lonhost}).'</li>';
 9585:                             } elsif (ref($loginhash{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
 9586:                                 $resulttext .= '<li><a href="'.
 9587:                                                "javascript:void(open('$loginhash{'login'}{'headtag'}{$lonhost}{'url'}?inhibitmenu=yes','Custom_HeadTag',
 9588:                                                'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
 9589:                                                '">'.&mt('custom markup').'</a> '.&mt('(for [_1])',$servers{$lonhost}).' ';
 9590:                                 if ($possexempt{$lonhost}) {
 9591:                                     $resulttext .= &mt('not included for client IP(s): [_1]',$possexempt{$lonhost});
 9592:                                 } else {
 9593:                                     $resulttext .= &mt('included for any client IP');
 9594:                                 }
 9595:                                 $resulttext .= '</li>';
 9596:                             }
 9597:                         }
 9598:                     }
 9599:                 } elsif ($item eq 'saml') {
 9600:                     if (ref($changes{$item}) eq 'HASH') {
 9601:                         my %notlt = (
 9602:                                        text   => 'Text for log-in by SSO',
 9603:                                        img    => 'SSO button image',
 9604:                                        alt    => 'Alt text for button image',
 9605:                                        url    => 'SSO URL',
 9606:                                        title  => 'Tooltip for SSO link',
 9607:                                        notsso => 'Text for non-SSO log-in',
 9608:                                     );
 9609:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
 9610:                             if (ref($currsaml{$lonhost}) eq 'HASH') {
 9611:                                 $resulttext .= '<li>'.&mt("$title{$item} in use for [_1]","<b>$lonhost</b>").
 9612:                                                '<ul>';
 9613:                                 foreach my $key ('text','img','alt','url','title','notsso') {
 9614:                                     if ($currsaml{$lonhost}{$key} eq '') {
 9615:                                         $resulttext .= '<li>'.&mt("$notlt{$key} not in use").'</li>';
 9616:                                     } else {
 9617:                                         my $value = "'$currsaml{$lonhost}{$key}'";
 9618:                                         if ($key eq 'img') {
 9619:                                             $value = '<img src="'.$currsaml{$lonhost}{$key}.'" />';
 9620:                                         }
 9621:                                         $resulttext .= '<li>'.&mt("$notlt{$key} set to: [_1]",
 9622:                                                                   $value).'</li>';
 9623:                                     }
 9624:                                 }
 9625:                                 $resulttext .= '</ul></li>';
 9626:                             } else {
 9627:                                 $resulttext .= '<li>'.&mt("$title{$item} not in use for [_1]",$lonhost).'</li>';
 9628:                             }
 9629:                         }
 9630:                     }
 9631:                 } elsif ($item eq 'captcha') {
 9632:                     if (ref($loginhash{'login'}) eq 'HASH') {
 9633:                         my $chgtxt;
 9634:                         if ($loginhash{'login'}{$item} eq 'notused') {
 9635:                             $chgtxt .= &mt('No CAPTCHA validation in use for helpdesk form.');
 9636:                         } else {
 9637:                             my %captchas = &captcha_phrases();
 9638:                             if ($captchas{$loginhash{'login'}{$item}}) {
 9639:                                 $chgtxt .= &mt("Validation for helpdesk form set to $captchas{$loginhash{'login'}{$item}}.");
 9640:                             } else {
 9641:                                 $chgtxt .= &mt('Validation for helpdesk form set to unknown type.');
 9642:                             }
 9643:                         }
 9644:                         $resulttext .= '<li>'.$chgtxt.'</li>';
 9645:                     }
 9646:                 } elsif ($item eq 'recaptchakeys') {
 9647:                     if (ref($loginhash{'login'}) eq 'HASH') {
 9648:                         my ($privkey,$pubkey);
 9649:                         if (ref($loginhash{'login'}{$item}) eq 'HASH') {
 9650:                             $pubkey = $loginhash{'login'}{$item}{'public'};
 9651:                             $privkey = $loginhash{'login'}{$item}{'private'};
 9652:                         }
 9653:                         my $chgtxt .= &mt('ReCAPTCHA keys changes').'<ul>';
 9654:                         if (!$pubkey) {
 9655:                             $chgtxt .= '<li>'.&mt('Public key deleted').'</li>';
 9656:                         } else {
 9657:                             $chgtxt .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
 9658:                         }
 9659:                         if (!$privkey) {
 9660:                             $chgtxt .= '<li>'.&mt('Private key deleted').'</li>';
 9661:                         } else {
 9662:                             $chgtxt .= '<li>'.&mt('Private key set to [_1]',$privkey).'</li>';
 9663:                         }
 9664:                         $chgtxt .= '</ul>';
 9665:                         $resulttext .= '<li>'.$chgtxt.'</li>';
 9666:                     }
 9667:                 } elsif ($item eq 'recaptchaversion') {
 9668:                     if (ref($loginhash{'login'}) eq 'HASH') {
 9669:                         if ($loginhash{'login'}{'captcha'} eq 'recaptcha') {
 9670:                             $resulttext .= '<li>'.&mt('ReCAPTCHA for helpdesk form set to version [_1]',$loginhash{'login'}{'recaptchaversion'}).
 9671:                                            '</li>';
 9672:                         }
 9673:                     }
 9674:                 } else {
 9675:                     $resulttext .= '<li>'.&mt("$title{$item} set to $offon[$env{'form.'.$item}]").'</li>';
 9676:                 }
 9677:             }
 9678:             $resulttext .= $colchgtext.'</ul>';
 9679:         } else {
 9680:             $resulttext = &mt('No changes made to log-in page settings');
 9681:         }
 9682:     } else {
 9683:         $resulttext = '<span class="LC_error">'.
 9684: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
 9685:     }
 9686:     if ($errors) {
 9687:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
 9688:                        $errors.'</ul>';
 9689:     }
 9690:     return $resulttext;
 9691: }
 9692: 
 9693: sub check_exempt_addresses {
 9694:     my ($iplist) = @_;
 9695:     $iplist =~ s/^\s+//;
 9696:     $iplist =~ s/\s+$//;
 9697:     my @poss_ips = split(/\s*[,:]\s*/,$iplist);
 9698:     my (@okips,$new);
 9699:     foreach my $ip (@poss_ips) {
 9700:         if ($ip =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) {
 9701:             if (($1 <= 255) && ($2 <= 255) && ($3 <= 255) && ($4 <= 255)) {
 9702:                 push(@okips,$ip);
 9703:             }
 9704:         }
 9705:     }
 9706:     if (@okips > 0) {
 9707:         $new = join(',',@okips);
 9708:     } else {
 9709:         $new = '';
 9710:     }
 9711:     return $new;
 9712: }
 9713: 
 9714: sub color_font_choices {
 9715:     my %choices =
 9716:         &Apache::lonlocal::texthash (
 9717:             img => "Header",
 9718:             bgs => "Background colors",
 9719:             links => "Link colors",
 9720:             images => "Images",
 9721:             font => "Font color",
 9722:             fontmenu => "Font menu",
 9723:             pgbg => "Page",
 9724:             tabbg => "Header",
 9725:             sidebg => "Border",
 9726:             link => "Link",
 9727:             alink => "Active link",
 9728:             vlink => "Visited link",
 9729:         );
 9730:     return %choices;
 9731: }
 9732: 
 9733: sub modify_ipaccess {
 9734:     my ($dom,$lastactref,%domconfig) = @_;
 9735:     my (@allpos,%changes,%confhash,$errors,$resulttext);
 9736:     my (@items,%deletions,%itemids,@warnings);
 9737:     my ($typeorder,$types) = &commblocktype_text();
 9738:     if ($env{'form.ipaccess_add'}) {
 9739:         my $name = $env{'form.ipaccess_name_add'};
 9740:         my ($newid,$error) = &get_ipaccess_id($dom,$name);
 9741:         if ($newid) {
 9742:             $itemids{'add'} = $newid;
 9743:             push(@items,'add');
 9744:             $changes{$newid} = 1;
 9745:         } else {
 9746:             $error = &mt('Failed to acquire unique ID for new IP access control item');
 9747:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
 9748:         }
 9749:     }
 9750:     if (ref($domconfig{'ipaccess'}) eq 'HASH') {
 9751:         my @todelete = &Apache::loncommon::get_env_multiple('form.ipaccess_del');
 9752:         if (@todelete) {
 9753:             map { $deletions{$_} = 1; } @todelete;
 9754:         }
 9755:         my $maxnum = $env{'form.ipaccess_maxnum'};
 9756:         for (my $i=0; $i<$maxnum; $i++) {
 9757:             my $itemid = $env{'form.ipaccess_id_'.$i};
 9758:             $itemid =~ s/\D+//g;
 9759:             if (ref($domconfig{'ipaccess'}{$itemid}) eq 'HASH') {
 9760:                 if ($deletions{$itemid}) {
 9761:                     $changes{$itemid} = $domconfig{'ipaccess'}{$itemid}{'name'};
 9762:                 } else {
 9763:                     push(@items,$i);
 9764:                     $itemids{$i} = $itemid;
 9765:                 }
 9766:             }
 9767:         }
 9768:     }
 9769:     foreach my $idx (@items) {
 9770:         my $itemid = $itemids{$idx};
 9771:         next unless ($itemid);
 9772:         my %current;
 9773:         unless ($idx eq 'add') {
 9774:             if (ref($domconfig{'ipaccess'}{$itemid}) eq 'HASH') {
 9775:                 %current = %{$domconfig{'ipaccess'}{$itemid}};
 9776:             }
 9777:         }
 9778:         my $position = $env{'form.ipaccess_pos_'.$itemid};
 9779:         $position =~ s/\D+//g;
 9780:         if ($position ne '') {
 9781:             $allpos[$position] = $itemid;
 9782:         }
 9783:         my $name = $env{'form.ipaccess_name_'.$idx};
 9784:         $name =~ s/^\s+|\s+$//g;
 9785:         $confhash{$itemid}{'name'} = $name;
 9786:         my $possrange = $env{'form.ipaccess_range_'.$idx};
 9787:         $possrange =~ s/^\s+|\s+$//g;
 9788:         unless ($possrange eq '') {
 9789:             $possrange =~ s/[\r\n]+/\s/g;
 9790:             $possrange =~ s/\s*-\s*/-/g;
 9791:             $possrange =~ s/\s+/,/g;
 9792:             $possrange =~ s/,+/,/g;
 9793:             if ($possrange ne '') {
 9794:                 my (@ok,$count);
 9795:                 $count = 0;
 9796:                 foreach my $poss (split(/\,/,$possrange)) {
 9797:                     $count ++;
 9798:                     $poss = &validate_ip_pattern($poss);
 9799:                     if ($poss ne '') {
 9800:                         push(@ok,$poss);
 9801:                     }
 9802:                 }
 9803:                 my $diff = $count - scalar(@ok);
 9804:                 if ($diff) {
 9805:                     $errors .= '<li><span class="LC_error">'.
 9806:                                &mt('[quant,_1,IP] invalid and excluded from saved value for IP range(s) for [_2]',
 9807:                                    $diff,$name).
 9808:                                '</span></li>';
 9809:                 }
 9810:                 if (@ok) {
 9811:                     my @cidr_list;
 9812:                     foreach my $item (@ok) {
 9813:                         @cidr_list = &Net::CIDR::cidradd($item,@cidr_list);
 9814:                     }
 9815:                     $confhash{$itemid}{'ip'} = join(',',@cidr_list);
 9816:                 }
 9817:             }
 9818:         }
 9819:         foreach my $field ('name','ip') {
 9820:             unless (($idx eq 'add') || ($changes{$itemid})) {
 9821:                 if ($current{$field} ne $confhash{$itemid}{$field}) {
 9822:                     $changes{$itemid} = 1;
 9823:                     last;
 9824:                 }
 9825:             }
 9826:         }
 9827:         $confhash{$itemid}{'commblocks'} = {};
 9828: 
 9829:         my %commblocks;
 9830:         map { $commblocks{$_} = 1; } &Apache::loncommon::get_env_multiple('form.ipaccess_block_'.$idx);
 9831:         foreach my $type (@{$typeorder}) {
 9832:             if ($commblocks{$type}) {
 9833:                 $confhash{$itemid}{'commblocks'}{$type} = 'on';
 9834:             }
 9835:             unless (($idx eq 'add') || ($changes{$itemid})) {
 9836:                 if (ref($current{'commblocks'}) eq 'HASH') {
 9837:                     if ($confhash{$itemid}{'commblocks'}{$type} ne $current{'commblocks'}{$type}) {
 9838:                         $changes{$itemid} = 1;
 9839:                     }
 9840:                 } elsif ($confhash{$itemid}{'commblocks'}{$type}) {
 9841:                     $changes{$itemid} = 1;
 9842:                 }
 9843:             }
 9844:         }
 9845:         $confhash{$itemid}{'courses'} = {};
 9846:         my %crsdeletions;
 9847:         my @delcrs = &Apache::loncommon::get_env_multiple('form.ipaccess_course_delete_'.$idx);
 9848:         if (@delcrs) {
 9849:             map { $crsdeletions{$_} = 1; } @delcrs;
 9850:         }
 9851:         if (ref($current{'courses'}) eq 'HASH') {
 9852:             foreach my $cid (sort(keys(%{$current{'courses'}}))) {
 9853:                 if ($crsdeletions{$cid}) {
 9854:                     $changes{$itemid} = 1;
 9855:                 } else {
 9856:                     $confhash{$itemid}{'courses'}{$cid} = 1;
 9857:                 }
 9858:             }
 9859:         }
 9860:         $env{'form.ipaccess_cnum_'.$idx} =~ s/^\s+|\s+$//g;
 9861:         $env{'form.ipaccess_cdom_'.$idx} =~ s/^\s+|\s+$//g;
 9862:         if (($env{'form.ipaccess_cnum_'.$idx} =~ /^$match_courseid$/) &&
 9863:             ($env{'form.ipaccess_cdom_'.$idx} =~ /^$match_domain$/)) {
 9864:             if (&Apache::lonnet::homeserver($env{'form.ipaccess_cnum_'.$idx},
 9865:                                             $env{'form.ipaccess_cdom_'.$idx}) eq 'no_host') {
 9866:                 $errors .= '<li><span class="LC_error">'.
 9867:                            &mt('Invalid courseID [_1] omitted from list of allowed courses',
 9868:                                $env{'form.ipaccess_cdom_'.$idx}.'_'.$env{'form.ipaccess_cnum_'.$idx}).
 9869:                            '</span></li>';
 9870:             } else {
 9871:                 $confhash{$itemid}{'courses'}{$env{'form.ipaccess_cdom_'.$idx}.'_'.$env{'form.ipaccess_cnum_'.$idx}} = 1;
 9872:                 $changes{$itemid} = 1;
 9873:             }
 9874:         }
 9875:     }
 9876:     if (@allpos > 0) {
 9877:         my $idx = 0;
 9878:         foreach my $itemid (@allpos) {
 9879:             if ($itemid ne '') {
 9880:                 $confhash{$itemid}{'order'} = $idx;
 9881:                 unless ($changes{$itemid}) {
 9882:                     if (ref($domconfig{'ipaccess'}) eq 'HASH') {
 9883:                         if (ref($domconfig{'ipaccess'}{$itemid}) eq 'HASH') {
 9884:                             if ($domconfig{'ipaccess'}{$itemid}{'order'} ne $idx) {
 9885:                                 $changes{$itemid} = 1;
 9886:                             }
 9887:                         }
 9888:                     }
 9889:                 }
 9890:                 $idx ++;
 9891:             }
 9892:         }
 9893:     }
 9894:     if (keys(%changes)) {
 9895:         my %defaultshash = (
 9896:                               ipaccess => \%confhash,
 9897:                            );
 9898:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
 9899:                                                  $dom);
 9900:         if ($putresult eq 'ok') {
 9901:             my $cachetime = 1800;
 9902:             &Apache::lonnet::do_cache_new('ipaccess',$dom,\%confhash,$cachetime);
 9903:             if (ref($lastactref) eq 'HASH') {
 9904:                 $lastactref->{'ipaccess'} = 1;
 9905:             }
 9906:             $resulttext = &mt('Changes made:').'<ul>';
 9907:             my %bynum;
 9908:             foreach my $itemid (sort(keys(%changes))) {
 9909:                 if (ref($confhash{$itemid}) eq 'HASH') {
 9910:                     my $position = $confhash{$itemid}{'order'};
 9911:                     if ($position =~ /^\d+$/) {
 9912:                         $bynum{$position} = $itemid;
 9913:                     }
 9914:                 }
 9915:             }
 9916:             if (keys(%deletions)) {
 9917:                 foreach my $itemid (sort { $a <=> $b } keys(%deletions)) {
 9918:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
 9919:                 }
 9920:             }
 9921:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
 9922:                 my $itemid = $bynum{$pos};
 9923:                 if (ref($confhash{$itemid}) eq 'HASH') {
 9924:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'name'}.'</b><ul>';
 9925:                     my $position = $pos + 1;
 9926:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
 9927:                     if ($confhash{$itemid}{'ip'} eq '') {
 9928:                         $resulttext .= '<li>'.&mt('No IP Range(s) set').'</li>';
 9929:                     } else {
 9930:                         $resulttext .= '<li>'.&mt('IP Range(s): [_1]',$confhash{$itemid}{'ip'}).'</li>';
 9931:                     }
 9932:                     if (keys(%{$confhash{$itemid}{'commblocks'}})) {
 9933:                         $resulttext .= '<li>'.&mt('Functionality Blocked: [_1]',
 9934:                                                   join(', ', map { $types->{$_}; } sort(keys(%{$confhash{$itemid}{'commblocks'}})))).
 9935:                                        '</li>';
 9936:                     } else {
 9937:                         $resulttext .= '<li>'.&mt('No functionality blocked').'</li>';
 9938:                     }
 9939:                     if (keys(%{$confhash{$itemid}{'courses'}})) {
 9940:                         my @courses;
 9941:                         foreach my $cid (sort(keys(%{$confhash{$itemid}{'courses'}}))) {
 9942:                             my %courseinfo = &Apache::lonnet::coursedescription($cid,{'one_time' => 1});
 9943:                             push(@courses,$courseinfo{'description'}.' ('.$cid.')');
 9944:                         }
 9945:                         $resulttext .= '<li>'.&mt('Courses/Communities allowed').':<ul><li>'.
 9946:                                              join('</li><li>',@courses).'</li></ul>';
 9947:                     } else {
 9948:                         $resulttext .= '<li>'.&mt('No courses allowed').'</li>';
 9949:                     }
 9950:                     $resulttext .= '</ul></li>';
 9951:                 }
 9952:             }
 9953:             $resulttext .= '</ul>';
 9954:         } else {
 9955:             $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
 9956:         }
 9957:     } else {
 9958:         $resulttext = &mt('No changes made');
 9959:     }
 9960:     if ($errors) {
 9961:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
 9962:                        $errors.'</ul></p>';
 9963:     }
 9964:     return $resulttext;
 9965: }
 9966: 
 9967: sub get_ipaccess_id {
 9968:     my ($domain,$location) = @_;
 9969:     # get lock on ipaccess db
 9970:     my $lockhash = {
 9971:                       lock => $env{'user.name'}.
 9972:                               ':'.$env{'user.domain'},
 9973:                    };
 9974:     my $tries = 0;
 9975:     my $gotlock = &Apache::lonnet::newput_dom('ipaccess',$lockhash,$domain);
 9976:     my ($id,$error);
 9977: 
 9978:     while (($gotlock ne 'ok') && ($tries<10)) {
 9979:         $tries ++;
 9980:         sleep (0.1);
 9981:         $gotlock = &Apache::lonnet::newput_dom('ipaccess',$lockhash,$domain);
 9982:     }
 9983:     if ($gotlock eq 'ok') {
 9984:         my %currids = &Apache::lonnet::dump_dom('ipaccess',$domain);
 9985:         if ($currids{'lock'}) {
 9986:             delete($currids{'lock'});
 9987:             if (keys(%currids)) {
 9988:                 my @curr = sort { $a <=> $b } keys(%currids);
 9989:                 if ($curr[-1] =~ /^\d+$/) {
 9990:                     $id = 1 + $curr[-1];
 9991:                 }
 9992:             } else {
 9993:                 $id = 1;
 9994:             }
 9995:             if ($id) {
 9996:                 unless (&Apache::lonnet::newput_dom('ipaccess',{ $id => $location },$domain) eq 'ok') {
 9997:                     $error = 'nostore';
 9998:                 }
 9999:             } else {
10000:                 $error = 'nonumber';
10001:             }
10002:         }
10003:         my $dellockoutcome = &Apache::lonnet::del_dom('ipaccess',['lock'],$domain);
10004:     } else {
10005:         $error = 'nolock';
10006:     }
10007:     return ($id,$error);
10008: }
10009: 
10010: sub modify_rolecolors {
10011:     my ($r,$dom,$confname,$roles,$lastactref,%domconfig) = @_;
10012:     my ($resulttext,%rolehash);
10013:     $rolehash{'rolecolors'} = {};
10014:     if (ref($domconfig{'rolecolors'}) ne 'HASH') {
10015:         if ($domconfig{'rolecolors'} eq '') {
10016:             $domconfig{'rolecolors'} = {};
10017:         }
10018:     }
10019:     my ($errors,%changes) = &modify_colors($r,$dom,$confname,$roles,
10020:                          $domconfig{'rolecolors'},$rolehash{'rolecolors'});
10021:     my $putresult = &Apache::lonnet::put_dom('configuration',\%rolehash,
10022:                                              $dom);
10023:     if ($putresult eq 'ok') {
10024:         if (keys(%changes) > 0) {
10025:             &Apache::loncommon::devalidate_domconfig_cache($dom);
10026:             if (ref($lastactref) eq 'HASH') {
10027:                 $lastactref->{'domainconfig'} = 1;
10028:             }
10029:             $resulttext = &display_colorchgs($dom,\%changes,$roles,
10030:                                              $rolehash{'rolecolors'});
10031:         } else {
10032:             $resulttext = &mt('No changes made to default color schemes');
10033:         }
10034:     } else {
10035:         $resulttext = '<span class="LC_error">'.
10036: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
10037:     }
10038:     if ($errors) {
10039:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
10040:                        $errors.'</ul>';
10041:     }
10042:     return $resulttext;
10043: }
10044: 
10045: sub modify_colors {
10046:     my ($r,$dom,$confname,$roles,$domconfig,$confhash) = @_;
10047:     my (%changes,%choices);
10048:     my @bgs;
10049:     my @links = ('link','alink','vlink');
10050:     my @logintext;
10051:     my @images;
10052:     my $servadm = $r->dir_config('lonAdmEMail');
10053:     my $errors;
10054:     my %defaults;
10055:     foreach my $role (@{$roles}) {
10056:         if ($role eq 'login') {
10057:             %choices = &login_choices();
10058:             @logintext = ('textcol','bgcol');
10059:         } else {
10060:             %choices = &color_font_choices();
10061:         }
10062:         if ($role eq 'login') {
10063:             @images = ('img','logo','domlogo','login');
10064:             @bgs = ('pgbg','mainbg','sidebg');
10065:         } else {
10066:             @images = ('img');
10067:             @bgs = ('pgbg','tabbg','sidebg');
10068:         }
10069:         my %defaults = &role_defaults($role,\@bgs,\@links,\@images,\@logintext);
10070:         unless ($env{'form.'.$role.'_font'} eq $defaults{'font'}) {
10071:             $confhash->{$role}{'font'} = $env{'form.'.$role.'_font'};
10072:         }
10073:         if ($role eq 'login') {
10074:             foreach my $item (@logintext) {
10075:                 $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
10076:                 if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
10077:                     $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
10078:                 }
10079:                 unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'logintext'}{$item})) {
10080:                     $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
10081:                 }
10082:             }
10083:         } else {
10084:             $env{'form.'.$role.'_fontmenu'} = lc($env{'form.'.$role.'_fontmenu'});
10085:             if ($env{'form.'.$role.'_fontmenu'} =~ /^\w+/) {
10086:                 $env{'form.'.$role.'_fontmenu'} = '#'.$env{'form.'.$role.'_fontmenu'};
10087:             }
10088:             unless($env{'form.'.$role.'_fontmenu'} eq lc($defaults{'fontmenu'})) {
10089:                 $confhash->{$role}{'fontmenu'} = $env{'form.'.$role.'_fontmenu'};
10090:             }
10091:         }
10092:         foreach my $item (@bgs) {
10093:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
10094:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
10095:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
10096:             }
10097:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'bgs'}{$item})) {
10098:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
10099:             }
10100:         }
10101:         foreach my $item (@links) {
10102:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
10103:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
10104:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
10105:             }
10106:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'links'}{$item})) {
10107:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
10108:             }
10109:         }
10110:         my ($configuserok,$author_ok,$switchserver) = 
10111:             &config_check($dom,$confname,$servadm);
10112:         my ($width,$height) = &thumb_dimensions();
10113:         if (ref($domconfig->{$role}) ne 'HASH') {
10114:             $domconfig->{$role} = {};
10115:         }
10116:         foreach my $img (@images) {
10117:             if ($role eq 'login') { 
10118:                 if (($img eq 'img') || ($img eq 'logo')) {  
10119:                     if (defined($env{'form.login_showlogo_'.$img})) {
10120:                         $confhash->{$role}{'showlogo'}{$img} = 1;
10121:                     } else { 
10122:                         $confhash->{$role}{'showlogo'}{$img} = 0;
10123:                     }
10124:                 }
10125:                 if ($env{'form.login_alt_'.$img} ne '') {
10126:                     $confhash->{$role}{'alttext'}{$img} = $env{'form.login_alt_'.$img};
10127:                 }
10128:             }
10129: 	    if ( ! $env{'form.'.$role.'_'.$img.'.filename'} 
10130: 		 && !defined($domconfig->{$role}{$img})
10131: 		 && !$env{'form.'.$role.'_del_'.$img}
10132: 		 && $env{'form.'.$role.'_import_'.$img}) {
10133: 		# import the old configured image from the .tab setting
10134: 		# if they haven't provided a new one 
10135: 		$domconfig->{$role}{$img} = 
10136: 		    $env{'form.'.$role.'_import_'.$img};
10137: 	    }
10138:             if ($env{'form.'.$role.'_'.$img.'.filename'} ne '') {
10139:                 my $error;
10140:                 if ($configuserok eq 'ok') {
10141:                     if ($switchserver) {
10142:                         $error = &mt("Upload of [_1] image for $role page(s) is not permitted to this server: [_2]",$choices{$img},$switchserver);
10143:                     } else {
10144:                         if ($author_ok eq 'ok') {
10145:                             my ($result,$logourl) = 
10146:                                 &publishlogo($r,'upload',$role.'_'.$img,
10147:                                            $dom,$confname,$img,$width,$height);
10148:                             if ($result eq 'ok') {
10149:                                 $confhash->{$role}{$img} = $logourl;
10150:                                 $changes{$role}{'images'}{$img} = 1;
10151:                             } else {
10152:                                 $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);
10153:                             }
10154:                         } else {
10155:                             $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);
10156:                         }
10157:                     }
10158:                 } else {
10159:                     $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);
10160:                 }
10161:                 if ($error) {
10162:                     &Apache::lonnet::logthis($error);
10163:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
10164:                 }
10165:             } elsif ($domconfig->{$role}{$img} ne '') {
10166:                 if ($domconfig->{$role}{$img} !~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
10167:                     my $error;
10168:                     if ($configuserok eq 'ok') {
10169: # is confname an author?
10170:                         if ($switchserver eq '') {
10171:                             if ($author_ok eq 'ok') {
10172:                                 my ($result,$logourl) = 
10173:                                &publishlogo($r,'copy',$domconfig->{$role}{$img},
10174:                                             $dom,$confname,$img,$width,$height);
10175:                                 if ($result eq 'ok') {
10176:                                     $confhash->{$role}{$img} = $logourl;
10177: 				    $changes{$role}{'images'}{$img} = 1;
10178:                                 }
10179:                             }
10180:                         }
10181:                     }
10182:                 }
10183:             }
10184:         }
10185:         if (ref($domconfig) eq 'HASH') {
10186:             if (ref($domconfig->{$role}) eq 'HASH') {
10187:                 foreach my $img (@images) {
10188:                     if ($domconfig->{$role}{$img} ne '') {
10189:                         if ($env{'form.'.$role.'_del_'.$img}) {
10190:                             $confhash->{$role}{$img} = '';
10191:                             $changes{$role}{'images'}{$img} = 1;
10192:                         } else {
10193:                             if ($confhash->{$role}{$img} eq '') {
10194:                                 $confhash->{$role}{$img} = $domconfig->{$role}{$img};
10195:                             }
10196:                         }
10197:                     } else {
10198:                         if ($env{'form.'.$role.'_del_'.$img}) {
10199:                             $confhash->{$role}{$img} = '';
10200:                             $changes{$role}{'images'}{$img} = 1;
10201:                         } 
10202:                     }
10203:                     if ($role eq 'login') {
10204:                         if (($img eq 'logo') || ($img eq 'img')) {
10205:                             if (ref($domconfig->{'login'}{'showlogo'}) eq 'HASH') {
10206:                                 if ($confhash->{$role}{'showlogo'}{$img} ne 
10207:                                     $domconfig->{$role}{'showlogo'}{$img}) {
10208:                                     $changes{$role}{'showlogo'}{$img} = 1; 
10209:                                 }
10210:                             } else {
10211:                                 if ($confhash->{$role}{'showlogo'}{$img} == 0) {
10212:                                     $changes{$role}{'showlogo'}{$img} = 1;
10213:                                 }
10214:                             }
10215:                         }
10216:                         if ($img ne 'login') {
10217:                             if (ref($domconfig->{$role}{'alttext'}) eq 'HASH') {
10218:                                 if ($confhash->{$role}{'alttext'}{$img} ne
10219:                                     $domconfig->{$role}{'alttext'}{$img}) {
10220:                                     $changes{$role}{'alttext'}{$img} = 1;
10221:                                 }
10222:                             } else {
10223:                                 if ($confhash->{$role}{'alttext'}{$img} ne '') {
10224:                                     $changes{$role}{'alttext'}{$img} = 1;
10225:                                 }
10226:                             }
10227:                         }
10228:                     }
10229:                 }
10230:                 if ($domconfig->{$role}{'font'} ne '') {
10231:                     if ($confhash->{$role}{'font'} ne $domconfig->{$role}{'font'}) {
10232:                         $changes{$role}{'font'} = 1;
10233:                     }
10234:                 } else {
10235:                     if ($confhash->{$role}{'font'}) {
10236:                         $changes{$role}{'font'} = 1;
10237:                     }
10238:                 }
10239:                 if ($role ne 'login') {
10240:                     if ($domconfig->{$role}{'fontmenu'} ne '') {
10241:                         if ($confhash->{$role}{'fontmenu'} ne $domconfig->{$role}{'fontmenu'}) {
10242:                             $changes{$role}{'fontmenu'} = 1;
10243:                         }
10244:                     } else {
10245:                         if ($confhash->{$role}{'fontmenu'}) {
10246:                             $changes{$role}{'fontmenu'} = 1;
10247:                         }
10248:                     }
10249:                 }
10250:                 foreach my $item (@bgs) {
10251:                     if ($domconfig->{$role}{$item} ne '') {
10252:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
10253:                             $changes{$role}{'bgs'}{$item} = 1;
10254:                         } 
10255:                     } else {
10256:                         if ($confhash->{$role}{$item}) {
10257:                             $changes{$role}{'bgs'}{$item} = 1;
10258:                         }
10259:                     }
10260:                 }
10261:                 foreach my $item (@links) {
10262:                     if ($domconfig->{$role}{$item} ne '') {
10263:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
10264:                             $changes{$role}{'links'}{$item} = 1;
10265:                         }
10266:                     } else {
10267:                         if ($confhash->{$role}{$item}) {
10268:                             $changes{$role}{'links'}{$item} = 1;
10269:                         }
10270:                     }
10271:                 }
10272:                 foreach my $item (@logintext) {
10273:                     if ($domconfig->{$role}{$item} ne '') {
10274:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
10275:                             $changes{$role}{'logintext'}{$item} = 1;
10276:                         }
10277:                     } else {
10278:                         if ($confhash->{$role}{$item}) {
10279:                             $changes{$role}{'logintext'}{$item} = 1;
10280:                         }
10281:                     }
10282:                 }
10283:             } else {
10284:                 &default_change_checker($role,\@images,\@links,\@bgs,
10285:                                         \@logintext,$confhash,\%changes); 
10286:             }
10287:         } else {
10288:             &default_change_checker($role,\@images,\@links,\@bgs,
10289:                                     \@logintext,$confhash,\%changes); 
10290:         }
10291:     }
10292:     return ($errors,%changes);
10293: }
10294: 
10295: sub config_check {
10296:     my ($dom,$confname,$servadm) = @_;
10297:     my ($configuserok,$author_ok,$switchserver,%currroles);
10298:     my $uhome = &Apache::lonnet::homeserver($confname,$dom,1);
10299:     ($configuserok,%currroles) = &check_configuser($uhome,$dom,
10300:                                                    $confname,$servadm);
10301:     if ($configuserok eq 'ok') {
10302:         $switchserver = &check_switchserver($dom,$confname);
10303:         if ($switchserver eq '') {
10304:             $author_ok = &check_authorstatus($dom,$confname,%currroles);
10305:         }
10306:     }
10307:     return ($configuserok,$author_ok,$switchserver);
10308: }
10309: 
10310: sub default_change_checker {
10311:     my ($role,$images,$links,$bgs,$logintext,$confhash,$changes) = @_;
10312:     foreach my $item (@{$links}) {
10313:         if ($confhash->{$role}{$item}) {
10314:             $changes->{$role}{'links'}{$item} = 1;
10315:         }
10316:     }
10317:     foreach my $item (@{$bgs}) {
10318:         if ($confhash->{$role}{$item}) {
10319:             $changes->{$role}{'bgs'}{$item} = 1;
10320:         }
10321:     }
10322:     foreach my $item (@{$logintext}) {
10323:         if ($confhash->{$role}{$item}) {
10324:             $changes->{$role}{'logintext'}{$item} = 1;
10325:         }
10326:     }
10327:     foreach my $img (@{$images}) {
10328:         if ($env{'form.'.$role.'_del_'.$img}) {
10329:             $confhash->{$role}{$img} = '';
10330:             $changes->{$role}{'images'}{$img} = 1;
10331:         }
10332:         if ($role eq 'login') {
10333:             if ($confhash->{$role}{'showlogo'}{$img} == 0) {
10334:                 $changes->{$role}{'showlogo'}{$img} = 1;
10335:             }
10336:             if (ref($confhash->{$role}{'alttext'}) eq 'HASH') {
10337:                 if ($confhash->{$role}{'alttext'}{$img} ne '') {
10338:                     $changes->{$role}{'alttext'}{$img} = 1;
10339:                 }
10340:             }
10341:         }
10342:     }
10343:     if ($confhash->{$role}{'font'}) {
10344:         $changes->{$role}{'font'} = 1;
10345:     }
10346: }
10347: 
10348: sub display_colorchgs {
10349:     my ($dom,$changes,$roles,$confhash) = @_;
10350:     my (%choices,$resulttext);
10351:     if (!grep(/^login$/,@{$roles})) {
10352:         $resulttext = &mt('Changes made:').'<br />';
10353:     }
10354:     foreach my $role (@{$roles}) {
10355:         if ($role eq 'login') {
10356:             %choices = &login_choices();
10357:         } else {
10358:             %choices = &color_font_choices();
10359:         }
10360:         if (ref($changes->{$role}) eq 'HASH') {
10361:             if ($role ne 'login') {
10362:                 $resulttext .= '<h4>'.&mt($role).'</h4>';
10363:             }
10364:             foreach my $key (sort(keys(%{$changes->{$role}}))) {
10365:                 if ($role ne 'login') {
10366:                     $resulttext .= '<ul>';
10367:                 }
10368:                 if (ref($changes->{$role}{$key}) eq 'HASH') {
10369:                     if ($role ne 'login') {
10370:                         $resulttext .= '<li>'.&mt($choices{$key}).':<ul>';
10371:                     }
10372:                     foreach my $item (sort(keys(%{$changes->{$role}{$key}}))) {
10373:                         if (($role eq 'login') && ($key eq 'showlogo')) {
10374:                             if ($confhash->{$role}{$key}{$item}) {
10375:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to be displayed").'</li>';
10376:                             } else {
10377:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to not be displayed").'</li>';
10378:                             }
10379:                         } elsif (($role eq 'login') && ($key eq 'alttext')) {
10380:                             if ($confhash->{$role}{$key}{$item} ne '') {
10381:                                 $resulttext .= '<li>'.&mt("$choices{$key} for $choices{$item} set to [_1].",
10382:                                                $confhash->{$role}{$key}{$item}).'</li>';
10383:                             } else {
10384:                                 $resulttext .= '<li>'.&mt("$choices{$key} for $choices{$item} deleted.").'</li>';
10385:                             }
10386:                         } elsif ($confhash->{$role}{$item} eq '') {
10387:                             $resulttext .= '<li>'.&mt("$choices{$item} set to default").'</li>';
10388:                         } else {
10389:                             my $newitem = $confhash->{$role}{$item};
10390:                             if ($key eq 'images') {
10391:                                 $newitem = '<img src="'.$confhash->{$role}{$item}.'" alt="'.$choices{$item}.'" valign="bottom" />';
10392:                             }
10393:                             $resulttext .= '<li>'.&mt("$choices{$item} set to [_1]",$newitem).'</li>';
10394:                         }
10395:                     }
10396:                     if ($role ne 'login') {
10397:                         $resulttext .= '</ul></li>';
10398:                     }
10399:                 } else {
10400:                     if ($confhash->{$role}{$key} eq '') {
10401:                         $resulttext .= '<li>'.&mt("$choices{$key} set to default").'</li>';
10402:                     } else {
10403:                         $resulttext .= '<li>'.&mt("$choices{$key} set to [_1]",$confhash->{$role}{$key}).'</li>';
10404:                     }
10405:                 }
10406:                 if ($role ne 'login') {
10407:                     $resulttext .= '</ul>';
10408:                 }
10409:             }
10410:         }
10411:     }
10412:     return $resulttext;
10413: }
10414: 
10415: sub thumb_dimensions {
10416:     return ('200','50');
10417: }
10418: 
10419: sub check_dimensions {
10420:     my ($inputfile) = @_;
10421:     my ($fullwidth,$fullheight);
10422:     if ($inputfile =~ m|^[/\w.\-]+$|) {
10423:         if (open(PIPE,"identify $inputfile 2>&1 |")) {
10424:             my $imageinfo = <PIPE>;
10425:             if (!close(PIPE)) {
10426:                 &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
10427:             }
10428:             chomp($imageinfo);
10429:             my ($fullsize) = 
10430:                 ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
10431:             if ($fullsize) {
10432:                 ($fullwidth,$fullheight) = split(/x/,$fullsize);
10433:             }
10434:         }
10435:     }
10436:     return ($fullwidth,$fullheight);
10437: }
10438: 
10439: sub check_configuser {
10440:     my ($uhome,$dom,$confname,$servadm) = @_;
10441:     my ($configuserok,%currroles);
10442:     if ($uhome eq 'no_host') {
10443:         srand( time() ^ ($$ + ($$ << 15))  ); # Seed rand.
10444:         my $configpass = &LONCAPA::Enrollment::create_password($dom);
10445:         $configuserok = 
10446:             &Apache::lonnet::modifyuser($dom,$confname,'','internal',
10447:                              $configpass,'','','','','',undef,$servadm);
10448:     } else {
10449:         $configuserok = 'ok';
10450:         %currroles = 
10451:             &Apache::lonnet::get_my_roles($confname,$dom,'userroles');
10452:     }
10453:     return ($configuserok,%currroles);
10454: }
10455: 
10456: sub check_authorstatus {
10457:     my ($dom,$confname,%currroles) = @_;
10458:     my $author_ok;
10459:     if (!$currroles{':'.$dom.':au'}) {
10460:         my $start = time;
10461:         my $end = 0;
10462:         $author_ok = 
10463:             &Apache::lonnet::assignrole($dom,$confname,'/'.$dom.'/',
10464:                                         'au',$end,$start,'','','domconfig');
10465:     } else {
10466:         $author_ok = 'ok';
10467:     }
10468:     return $author_ok;
10469: }
10470: 
10471: sub publishlogo {
10472:     my ($r,$action,$formname,$dom,$confname,$subdir,$thumbwidth,$thumbheight,$savefileas) = @_;
10473:     my ($output,$fname,$logourl);
10474:     if ($action eq 'upload') {
10475:         $fname=$env{'form.'.$formname.'.filename'};
10476:         chop($env{'form.'.$formname});
10477:     } else {
10478:         ($fname) = ($formname =~ /([^\/]+)$/);
10479:     }
10480:     if ($savefileas ne '') {
10481:         $fname = $savefileas;
10482:     }
10483:     $fname=&Apache::lonnet::clean_filename($fname);
10484: # See if there is anything left
10485:     unless ($fname) { return ('error: no uploaded file'); }
10486:     $fname="$subdir/$fname";
10487:     my $docroot=$r->dir_config('lonDocRoot');
10488:     my $filepath="$docroot/priv";
10489:     my $relpath = "$dom/$confname";
10490:     my ($fnamepath,$file,$fetchthumb);
10491:     $file=$fname;
10492:     if ($fname=~m|/|) {
10493:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
10494:     }
10495:     my @parts=split(/\//,"$filepath/$relpath/$fnamepath");
10496:     my $count;
10497:     for ($count=5;$count<=$#parts;$count++) {
10498:         $filepath.="/$parts[$count]";
10499:         if ((-e $filepath)!=1) {
10500:             mkdir($filepath,02770);
10501:         }
10502:     }
10503:     # Check for bad extension and disallow upload
10504:     if ($file=~/\.(\w+)$/ &&
10505:         (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
10506:         $output = 
10507:             &mt('Invalid file extension ([_1]) - reserved for internal use.',$1); 
10508:     } elsif ($file=~/\.(\w+)$/ &&
10509:         !defined(&Apache::loncommon::fileembstyle($1))) {
10510:         $output = &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
10511:     } elsif ($file=~/\.(\d+)\.(\w+)$/) {
10512:         $output = &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
10513:     } elsif (-d "$filepath/$file") {
10514:         $output = &mt('Filename is a directory name - rename the file and re-upload');
10515:     } else {
10516:         my $source = $filepath.'/'.$file;
10517:         my $logfile;
10518:         if (!open($logfile,">>",$source.'.log')) {
10519:             return (&mt('No write permission to Authoring Space'));
10520:         }
10521:         print $logfile
10522: "\n================= Publish ".localtime()." ================\n".
10523: $env{'user.name'}.':'.$env{'user.domain'}."\n";
10524: # Save the file
10525:         if (!open(FH,">",$source)) {
10526:             &Apache::lonnet::logthis('Failed to create '.$source);
10527:             return (&mt('Failed to create file'));
10528:         }
10529:         if ($action eq 'upload') {
10530:             if (!print FH ($env{'form.'.$formname})) {
10531:                 &Apache::lonnet::logthis('Failed to write to '.$source);
10532:                 return (&mt('Failed to write file'));
10533:             }
10534:         } else {
10535:             my $original = &Apache::lonnet::filelocation('',$formname);
10536:             if(!copy($original,$source)) {
10537:                 &Apache::lonnet::logthis('Failed to copy '.$original.' to '.$source);
10538:                 return (&mt('Failed to write file'));
10539:             }
10540:         }
10541:         close(FH);
10542:         chmod(0660, $source); # Permissions to rw-rw---.
10543: 
10544:         my $targetdir=$docroot.'/res/'.$dom.'/'.$confname .'/'.$fnamepath;
10545:         my $copyfile=$targetdir.'/'.$file;
10546: 
10547:         my @parts=split(/\//,$targetdir);
10548:         my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
10549:         for (my $count=5;$count<=$#parts;$count++) {
10550:             $path.="/$parts[$count]";
10551:             if (!-e $path) {
10552:                 print $logfile "\nCreating directory ".$path;
10553:                 mkdir($path,02770);
10554:             }
10555:         }
10556:         my $versionresult;
10557:         if (-e $copyfile) {
10558:             $versionresult = &logo_versioning($targetdir,$file,$logfile);
10559:         } else {
10560:             $versionresult = 'ok';
10561:         }
10562:         if ($versionresult eq 'ok') {
10563:             if (copy($source,$copyfile)) {
10564:                 print $logfile "\nCopied original source to ".$copyfile."\n";
10565:                 $output = 'ok';
10566:                 $logourl = '/res/'.$dom.'/'.$confname.'/'.$fname;
10567:                 push(@{$modified_urls},[$copyfile,$source]);
10568:                 my $metaoutput = 
10569:                     &write_metadata($dom,$confname,$formname,$targetdir,$file,$logfile);
10570:                 unless ($registered_cleanup) {
10571:                     my $handlers = $r->get_handlers('PerlCleanupHandler');
10572:                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
10573:                     $registered_cleanup=1;
10574:                 }
10575:             } else {
10576:                 print $logfile "\nUnable to write ".$copyfile.':'.$!."\n";
10577:                 $output = &mt('Failed to copy file to RES space').", $!";
10578:             }
10579:             if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
10580:                 my $inputfile = $filepath.'/'.$file;
10581:                 my $outfile = $filepath.'/'.'tn-'.$file;
10582:                 my ($fullwidth,$fullheight) = &check_dimensions($inputfile);
10583:                 if ($fullwidth ne '' && $fullheight ne '') { 
10584:                     if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
10585:                         my $thumbsize = $thumbwidth.'x'.$thumbheight;
10586:                         my @args = ('convert','-sample',$thumbsize,$inputfile,$outfile);
10587:                         system({$args[0]} @args);
10588:                         chmod(0660, $filepath.'/tn-'.$file);
10589:                         if (-e $outfile) {
10590:                             my $copyfile=$targetdir.'/tn-'.$file;
10591:                             if (copy($outfile,$copyfile)) {
10592:                                 print $logfile "\nCopied source to ".$copyfile."\n";
10593:                                 my $thumb_metaoutput = 
10594:                                     &write_metadata($dom,$confname,$formname,
10595:                                                     $targetdir,'tn-'.$file,$logfile);
10596:                                 push(@{$modified_urls},[$copyfile,$outfile]);
10597:                                 unless ($registered_cleanup) {
10598:                                     my $handlers = $r->get_handlers('PerlCleanupHandler');
10599:                                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
10600:                                     $registered_cleanup=1;
10601:                                 }
10602:                             } else {
10603:                                 print $logfile "\nUnable to write ".$copyfile.
10604:                                                ':'.$!."\n";
10605:                             }
10606:                         }
10607:                     }
10608:                 }
10609:             }
10610:         } else {
10611:             $output = $versionresult;
10612:         }
10613:     }
10614:     return ($output,$logourl);
10615: }
10616: 
10617: sub logo_versioning {
10618:     my ($targetdir,$file,$logfile) = @_;
10619:     my $target = $targetdir.'/'.$file;
10620:     my ($maxversion,$fn,$extn,$output);
10621:     $maxversion = 0;
10622:     if ($file =~ /^(.+)\.(\w+)$/) {
10623:         $fn=$1;
10624:         $extn=$2;
10625:     }
10626:     opendir(DIR,$targetdir);
10627:     while (my $filename=readdir(DIR)) {
10628:         if ($filename=~/\Q$fn\E\.(\d+)\.\Q$extn\E$/) {
10629:             $maxversion=($1>$maxversion)?$1:$maxversion;
10630:         }
10631:     }
10632:     $maxversion++;
10633:     print $logfile "\nCreating old version ".$maxversion."\n";
10634:     my $copyfile=$targetdir.'/'.$fn.'.'.$maxversion.'.'.$extn;
10635:     if (copy($target,$copyfile)) {
10636:         print $logfile "Copied old target to ".$copyfile."\n";
10637:         $copyfile=$copyfile.'.meta';
10638:         if (copy($target.'.meta',$copyfile)) {
10639:             print $logfile "Copied old target metadata to ".$copyfile."\n";
10640:             $output = 'ok';
10641:         } else {
10642:             print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
10643:             $output = &mt('Failed to copy old meta').", $!, ";
10644:         }
10645:     } else {
10646:         print $logfile "Unable to write ".$copyfile.':'.$!."\n";
10647:         $output = &mt('Failed to copy old target').", $!, ";
10648:     }
10649:     return $output;
10650: }
10651: 
10652: sub write_metadata {
10653:     my ($dom,$confname,$formname,$targetdir,$file,$logfile) = @_;
10654:     my (%metadatafields,%metadatakeys,$output);
10655:     $metadatafields{'title'}=$formname;
10656:     $metadatafields{'creationdate'}=time;
10657:     $metadatafields{'lastrevisiondate'}=time;
10658:     $metadatafields{'copyright'}='public';
10659:     $metadatafields{'modifyinguser'}=$env{'user.name'}.':'.
10660:                                          $env{'user.domain'};
10661:     $metadatafields{'authorspace'}=$confname.':'.$dom;
10662:     $metadatafields{'domain'}=$dom;
10663:     {
10664:         print $logfile "\nWrite metadata file for ".$targetdir.'/'.$file;
10665:         my $mfh;
10666:         if (open($mfh,">",$targetdir.'/'.$file.'.meta')) {
10667:             foreach (sort(keys(%metadatafields))) {
10668:                 unless ($_=~/\./) {
10669:                     my $unikey=$_;
10670:                     $unikey=~/^([A-Za-z]+)/;
10671:                     my $tag=$1;
10672:                     $tag=~tr/A-Z/a-z/;
10673:                     print $mfh "\n\<$tag";
10674:                     foreach (split(/\,/,$metadatakeys{$unikey})) {
10675:                         my $value=$metadatafields{$unikey.'.'.$_};
10676:                         $value=~s/\"/\'\'/g;
10677:                         print $mfh ' '.$_.'="'.$value.'"';
10678:                     }
10679:                     print $mfh '>'.
10680:                         &HTML::Entities::encode($metadatafields{$unikey},'<>&"')
10681:                             .'</'.$tag.'>';
10682:                 }
10683:             }
10684:             $output = 'ok';
10685:             print $logfile "\nWrote metadata";
10686:             close($mfh);
10687:         } else {
10688:             print $logfile "\nFailed to open metadata file";
10689:             $output = &mt('Could not write metadata');
10690:         }
10691:     }
10692:     return $output;
10693: }
10694: 
10695: sub notifysubscribed {
10696:     foreach my $targetsource (@{$modified_urls}){
10697:         next unless (ref($targetsource) eq 'ARRAY');
10698:         my ($target,$source)=@{$targetsource};
10699:         if ($source ne '') {
10700:             if (open(my $logfh,">>",$source.'.log')) {
10701:                 print $logfh "\nCleanup phase: Notifications\n";
10702:                 my @subscribed=&subscribed_hosts($target);
10703:                 foreach my $subhost (@subscribed) {
10704:                     print $logfh "\nNotifying host ".$subhost.':';
10705:                     my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
10706:                     print $logfh $reply;
10707:                 }
10708:                 my @subscribedmeta=&subscribed_hosts("$target.meta");
10709:                 foreach my $subhost (@subscribedmeta) {
10710:                     print $logfh "\nNotifying host for metadata only ".$subhost.':';
10711:                     my $reply=&Apache::lonnet::critical('update:'.$target.'.meta',
10712:                                                         $subhost);
10713:                     print $logfh $reply;
10714:                 }
10715:                 print $logfh "\n============ Done ============\n";
10716:                 close($logfh);
10717:             }
10718:         }
10719:     }
10720:     return OK;
10721: }
10722: 
10723: sub subscribed_hosts {
10724:     my ($target) = @_;
10725:     my @subscribed;
10726:     if (open(my $fh,"<","$target.subscription")) {
10727:         while (my $subline=<$fh>) {
10728:             if ($subline =~ /^($match_lonid):/) {
10729:                 my $host = $1;
10730:                 if ($host ne $Apache::lonnet::perlvar{'lonHostID'}) {
10731:                     unless (grep(/^\Q$host\E$/,@subscribed)) {
10732:                         push(@subscribed,$host);
10733:                     }
10734:                 }
10735:             }
10736:         }
10737:     }
10738:     return @subscribed;
10739: }
10740: 
10741: sub check_switchserver {
10742:     my ($dom,$confname) = @_;
10743:     my ($allowed,$switchserver);
10744:     my $home = &Apache::lonnet::homeserver($confname,$dom);
10745:     if ($home eq 'no_host') {
10746:         $home = &Apache::lonnet::domain($dom,'primary');
10747:     }
10748:     my @ids=&Apache::lonnet::current_machine_ids();
10749:     foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
10750:     if (!$allowed) {
10751: 	$switchserver='<a href="/adm/switchserver?otherserver='.$home.'&amp;role=dc./'.$dom.'/&amp;destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
10752:     }
10753:     return $switchserver;
10754: }
10755: 
10756: sub modify_quotas {
10757:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
10758:     my ($context,@usertools,@options,%validations,%titles,%confhash,%toolshash,
10759:         %limithash,$toolregexp,%conditions,$resulttext,%changes,$confname,$configuserok,
10760:         $author_ok,$switchserver,$errors,$validationitemsref,$validationnamesref,
10761:         $validationfieldsref);
10762:     if ($action eq 'quotas') {
10763:         $context = 'tools'; 
10764:     } else {
10765:         $context = $action;
10766:     }
10767:     if ($context eq 'requestcourses') {
10768:         @usertools = ('official','unofficial','community','textbook');
10769:         @options =('norequest','approval','validate','autolimit');
10770:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
10771:         %titles = &courserequest_titles();
10772:         $toolregexp = join('|',@usertools);
10773:         %conditions = &courserequest_conditions();
10774:         $confname = $dom.'-domainconfig';
10775:         my $servadm = $r->dir_config('lonAdmEMail');
10776:         ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
10777:         ($validationitemsref,$validationnamesref,$validationfieldsref) = 
10778:             &Apache::loncoursequeueadmin::requestcourses_validation_types();
10779:     } elsif ($context eq 'requestauthor') {
10780:         @usertools = ('author');
10781:         %titles = &authorrequest_titles();
10782:     } else {
10783:         @usertools = ('aboutme','blog','webdav','portfolio');
10784:         %titles = &tool_titles();
10785:     }
10786:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
10787:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
10788:     foreach my $key (keys(%env)) {
10789:         if ($context eq 'requestcourses') {
10790:             if ($key =~ /^form\.crsreq_($toolregexp)_(.+)$/) {
10791:                 my $item = $1;
10792:                 my $type = $2;
10793:                 if ($type =~ /^limit_(.+)/) {
10794:                     $limithash{$item}{$1} = $env{$key};
10795:                 } else {
10796:                     $confhash{$item}{$type} = $env{$key};
10797:                 }
10798:             }
10799:         } elsif ($context eq 'requestauthor') {
10800:             if ($key =~ /^\Qform.authorreq_\E(.+)$/) {
10801:                 $confhash{$1} = $env{$key};
10802:             }
10803:         } else {
10804:             if ($key =~ /^form\.quota_(.+)$/) {
10805:                 $confhash{'defaultquota'}{$1} = $env{$key};
10806:             } elsif ($key =~ /^form\.authorquota_(.+)$/) {
10807:                 $confhash{'authorquota'}{$1} = $env{$key};
10808:             } elsif ($key =~ /^form\.\Q$context\E_(.+)$/) {
10809:                 @{$toolshash{$1}} = &Apache::loncommon::get_env_multiple($key);
10810:             }
10811:         }
10812:     }
10813:     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
10814:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.'.$context.'notifyapproval');
10815:         @approvalnotify = sort(@approvalnotify);
10816:         $confhash{'notify'}{'approval'} = join(',',@approvalnotify);
10817:         my @crstypes = ('official','unofficial','community','textbook');
10818:         my @hasuniquecode = &Apache::loncommon::get_env_multiple('form.uniquecode');
10819:         foreach my $type (@hasuniquecode) {
10820:             if (grep(/^\Q$type\E$/,@crstypes)) {
10821:                 $confhash{'uniquecode'}{$type} = 1;
10822:             }
10823:         }
10824:         my (%newbook,%allpos);
10825:         if ($context eq 'requestcourses') {
10826:             foreach my $type ('textbooks','templates') {
10827:                 @{$allpos{$type}} = (); 
10828:                 my $invalid;
10829:                 if ($type eq 'textbooks') {
10830:                     $invalid = &mt('Invalid LON-CAPA course for textbook');
10831:                 } else {
10832:                     $invalid = &mt('Invalid LON-CAPA course for template');
10833:                 }
10834:                 if ($env{'form.'.$type.'_addbook'}) {
10835:                     if (($env{'form.'.$type.'_addbook_cnum'} =~ /^$match_courseid$/) &&
10836:                         ($env{'form.'.$type.'_addbook_cdom'} =~ /^$match_domain$/)) {
10837:                         if (&Apache::lonnet::homeserver($env{'form.'.$type.'_addbook_cnum'},
10838:                                                         $env{'form.'.$type.'_addbook_cdom'}) eq 'no_host') {
10839:                             $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
10840:                         } else {
10841:                             $newbook{$type} = $env{'form.'.$type.'_addbook_cdom'}.'_'.$env{'form.'.$type.'_addbook_cnum'};
10842:                             my $position = $env{'form.'.$type.'_addbook_pos'};
10843:                             $position =~ s/\D+//g;
10844:                             if ($position ne '') {
10845:                                 $allpos{$type}[$position] = $newbook{$type};
10846:                             }
10847:                         }
10848:                     } else {
10849:                         $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
10850:                     }
10851:                 }
10852:             } 
10853:         }
10854:         if (ref($domconfig{$action}) eq 'HASH') {
10855:             if (ref($domconfig{$action}{'notify'}) eq 'HASH') {
10856:                 if ($domconfig{$action}{'notify'}{'approval'} ne $confhash{'notify'}{'approval'}) {
10857:                     $changes{'notify'}{'approval'} = 1;
10858:                 }
10859:             } else {
10860:                 if ($confhash{'notify'}{'approval'}) {
10861:                     $changes{'notify'}{'approval'} = 1;
10862:                 }
10863:             }
10864:             if (ref($domconfig{$action}{'uniquecode'}) eq 'HASH') {
10865:                 if (ref($confhash{'uniquecode'}) eq 'HASH') {
10866:                     foreach my $crstype (keys(%{$domconfig{$action}{'uniquecode'}})) {
10867:                         unless ($confhash{'uniquecode'}{$crstype}) {
10868:                             $changes{'uniquecode'} = 1;
10869:                         }
10870:                     }
10871:                     unless ($changes{'uniquecode'}) {
10872:                         foreach my $crstype (keys(%{$confhash{'uniquecode'}})) {
10873:                             unless ($domconfig{$action}{'uniquecode'}{$crstype}) {
10874:                                 $changes{'uniquecode'} = 1;
10875:                             }
10876:                         }
10877:                     }
10878:                } else {
10879:                    $changes{'uniquecode'} = 1;
10880:                }
10881:             } elsif (ref($confhash{'uniquecode'}) eq 'HASH') {
10882:                 $changes{'uniquecode'} = 1;
10883:             }
10884:             if ($context eq 'requestcourses') {
10885:                 foreach my $type ('textbooks','templates') {
10886:                     if (ref($domconfig{$action}{$type}) eq 'HASH') {
10887:                         my %deletions;
10888:                         my @todelete = &Apache::loncommon::get_env_multiple('form.'.$type.'_del');
10889:                         if (@todelete) {
10890:                             map { $deletions{$_} = 1; } @todelete;
10891:                         }
10892:                         my %imgdeletions;
10893:                         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.'.$type.'_image_del');
10894:                         if (@todeleteimages) {
10895:                             map { $imgdeletions{$_} = 1; } @todeleteimages;
10896:                         }
10897:                         my $maxnum = $env{'form.'.$type.'_maxnum'};
10898:                         for (my $i=0; $i<=$maxnum; $i++) {
10899:                             my $itemid = $env{'form.'.$type.'_id_'.$i};
10900:                             my ($key) = ($itemid =~ /^\Q$type\E_(\w+)$/); 
10901:                             if (ref($domconfig{$action}{$type}{$key}) eq 'HASH') {
10902:                                 if ($deletions{$key}) {
10903:                                     if ($domconfig{$action}{$type}{$key}{'image'}) {
10904:                                         #FIXME need to obsolete item in RES space
10905:                                     }
10906:                                     next;
10907:                                 } else {
10908:                                     my $newpos = $env{'form.'.$itemid};
10909:                                     $newpos =~ s/\D+//g;
10910:                                     foreach my $item ('subject','title','publisher','author') {
10911:                                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
10912:                                                  ($type eq 'templates'));
10913:                                         $confhash{$type}{$key}{$item} = $env{'form.'.$type.'_'.$item.'_'.$i};
10914:                                         if ($domconfig{$action}{$type}{$key}{$item} ne $confhash{$type}{$key}{$item}) {
10915:                                             $changes{$type}{$key} = 1;
10916:                                         }
10917:                                     }
10918:                                     $allpos{$type}[$newpos] = $key;
10919:                                 }
10920:                                 if ($imgdeletions{$key}) {
10921:                                     $changes{$type}{$key} = 1;
10922:                                     #FIXME need to obsolete item in RES space
10923:                                 } elsif ($env{'form.'.$type.'_image_'.$i.'.filename'}) {
10924:                                     my ($cdom,$cnum) = split(/_/,$key);
10925:                                     if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
10926:                                         $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
10927:                                     } else {
10928:                                         my ($imgurl,$error) = &process_textbook_image($r,$dom,$confname,$type.'_image_'.$i,
10929:                                                                                       $cdom,$cnum,$type,$configuserok,
10930:                                                                                       $switchserver,$author_ok);
10931:                                         if ($imgurl) {
10932:                                             $confhash{$type}{$key}{'image'} = $imgurl;
10933:                                             $changes{$type}{$key} = 1; 
10934:                                         }
10935:                                         if ($error) {
10936:                                             &Apache::lonnet::logthis($error);
10937:                                             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
10938:                                         }
10939:                                     } 
10940:                                 } elsif ($domconfig{$action}{$type}{$key}{'image'}) {
10941:                                     $confhash{$type}{$key}{'image'} = 
10942:                                         $domconfig{$action}{$type}{$key}{'image'};
10943:                                 }
10944:                             }
10945:                         }
10946:                     }
10947:                 }
10948:             }
10949:         } else {
10950:             if ($confhash{'notify'}{'approval'}) {
10951:                 $changes{'notify'}{'approval'} = 1;
10952:             }
10953:             if (ref($confhash{'uniquecode'} eq 'HASH')) {
10954:                 $changes{'uniquecode'} = 1;
10955:             }
10956:         }
10957:         if ($context eq 'requestcourses') {
10958:             foreach my $type ('textbooks','templates') {
10959:                 if ($newbook{$type}) {
10960:                     $changes{$type}{$newbook{$type}} = 1;
10961:                     foreach my $item ('subject','title','publisher','author') {
10962:                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
10963:                                  ($type eq 'template'));
10964:                         $env{'form.'.$type.'_addbook_'.$item} =~ s/(`)/'/g;
10965:                         if ($env{'form.'.$type.'_addbook_'.$item}) {
10966:                             $confhash{$type}{$newbook{$type}}{$item} = $env{'form.'.$type.'_addbook_'.$item};
10967:                         }
10968:                     }
10969:                     if ($type eq 'textbooks') {
10970:                         if ($env{'form.'.$type.'_addbook_image.filename'} ne '') {
10971:                             my ($cdom,$cnum) = split(/_/,$newbook{$type});
10972:                             if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
10973:                                 $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
10974:                             } else {
10975:                                 my ($imageurl,$error) =
10976:                                     &process_textbook_image($r,$dom,$confname,$type.'_addbook_image',$cdom,$cnum,$type,
10977:                                                             $configuserok,$switchserver,$author_ok);
10978:                                 if ($imageurl) {
10979:                                     $confhash{$type}{$newbook{$type}}{'image'} = $imageurl;
10980:                                 }
10981:                                 if ($error) {
10982:                                     &Apache::lonnet::logthis($error);
10983:                                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
10984:                                 }
10985:                             }
10986:                         }
10987:                     }
10988:                 }
10989:                 if (@{$allpos{$type}} > 0) {
10990:                     my $idx = 0;
10991:                     foreach my $item (@{$allpos{$type}}) {
10992:                         if ($item ne '') {
10993:                             $confhash{$type}{$item}{'order'} = $idx;
10994:                             if (ref($domconfig{$action}) eq 'HASH') {
10995:                                 if (ref($domconfig{$action}{$type}) eq 'HASH') {
10996:                                     if (ref($domconfig{$action}{$type}{$item}) eq 'HASH') {
10997:                                         if ($domconfig{$action}{$type}{$item}{'order'} ne $idx) {
10998:                                             $changes{$type}{$item} = 1;
10999:                                         }
11000:                                     }
11001:                                 }
11002:                             }
11003:                             $idx ++;
11004:                         }
11005:                     }
11006:                 }
11007:             }
11008:             if (ref($validationitemsref) eq 'ARRAY') {
11009:                 foreach my $item (@{$validationitemsref}) {
11010:                     if ($item eq 'fields') {
11011:                         my @changed;
11012:                         @{$confhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.requestcourses_validation_'.$item);
11013:                         if (@{$confhash{'validation'}{$item}} > 0) {
11014:                             @{$confhash{'validation'}{$item}} = sort(@{$confhash{'validation'}{$item}});
11015:                         }
11016:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
11017:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
11018:                                 if (ref($domconfig{'requestcourses'}{'validation'}{$item}) eq 'ARRAY') {
11019:                                     @changed = &Apache::loncommon::compare_arrays($confhash{'validation'}{$item},
11020:                                                                                   $domconfig{'requestcourses'}{'validation'}{$item});
11021:                                 } else {
11022:                                     @changed = @{$confhash{'validation'}{$item}};
11023:                                 }
11024:                             } else {
11025:                                 @changed = @{$confhash{'validation'}{$item}};
11026:                             }
11027:                         } else {
11028:                             @changed = @{$confhash{'validation'}{$item}};
11029:                         }
11030:                         if (@changed) {
11031:                             if ($confhash{'validation'}{$item}) {
11032:                                 $changes{'validation'}{$item} = join(', ',@{$confhash{'validation'}{$item}});
11033:                             } else {
11034:                                 $changes{'validation'}{$item} = &mt('None');
11035:                             }
11036:                         }
11037:                     } else {
11038:                         $confhash{'validation'}{$item} = $env{'form.requestcourses_validation_'.$item};
11039:                         if ($item eq 'markup') {
11040:                             if ($env{'form.requestcourses_validation_'.$item}) {
11041:                                 $env{'form.requestcourses_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
11042:                             }
11043:                         }
11044:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
11045:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
11046:                                 if ($domconfig{'requestcourses'}{'validation'}{$item} ne $confhash{'validation'}{$item}) {
11047:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
11048:                                 }
11049:                             } else {
11050:                                 if ($confhash{'validation'}{$item} ne '') {
11051:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
11052:                                 }
11053:                             }
11054:                         } else {
11055:                             if ($confhash{'validation'}{$item} ne '') {
11056:                                 $changes{'validation'}{$item} = $confhash{'validation'}{$item};
11057:                             }
11058:                         }
11059:                     }
11060:                 }
11061:             }
11062:             if ($env{'form.validationdc'}) {
11063:                 my $newval = $env{'form.validationdc'};
11064:                 my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
11065:                 if (exists($domcoords{$newval})) {
11066:                     $confhash{'validation'}{'dc'} = $newval;
11067:                 }
11068:             }
11069:             if (ref($confhash{'validation'}) eq 'HASH') {
11070:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
11071:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
11072:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
11073:                             unless ($confhash{'validation'}{'dc'} eq $domconfig{'requestcourses'}{'validation'}{'dc'}) {
11074:                                 if ($confhash{'validation'}{'dc'} eq '') {
11075:                                     $changes{'validation'}{'dc'} = &mt('None');
11076:                                 } else {
11077:                                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
11078:                                 }
11079:                             }
11080:                         } elsif ($confhash{'validation'}{'dc'} ne '') {
11081:                             $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
11082:                         }
11083:                     } elsif ($confhash{'validation'}{'dc'} ne '') {
11084:                         $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
11085:                     }
11086:                 } elsif ($confhash{'validation'}{'dc'} ne '') {
11087:                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
11088:                 }
11089:             } else {
11090:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
11091:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
11092:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
11093:                             $changes{'validation'}{'dc'} = &mt('None');
11094:                         }
11095:                     }
11096:                 }
11097:             }
11098:         }
11099:     } else {
11100:         $confhash{'defaultquota'}{'default'} = $env{'form.defaultquota'};
11101:         $confhash{'authorquota'}{'default'} = $env{'form.authorquota'};
11102:     }
11103:     foreach my $item (@usertools) {
11104:         foreach my $type (@{$types},'default','_LC_adv') {
11105:             my $unset; 
11106:             if ($context eq 'requestcourses') {
11107:                 $unset = '0';
11108:                 if ($type eq '_LC_adv') {
11109:                     $unset = '';
11110:                 }
11111:                 if ($confhash{$item}{$type} eq 'autolimit') {
11112:                     $confhash{$item}{$type} .= '=';
11113:                     unless ($limithash{$item}{$type} =~ /\D/) {
11114:                         $confhash{$item}{$type} .= $limithash{$item}{$type};
11115:                     }
11116:                 }
11117:             } elsif ($context eq 'requestauthor') {
11118:                 $unset = '0';
11119:                 if ($type eq '_LC_adv') {
11120:                     $unset = '';
11121:                 }
11122:             } else {
11123:                 if (grep(/^\Q$type\E$/,@{$toolshash{$item}})) {
11124:                     $confhash{$item}{$type} = 1;
11125:                 } else {
11126:                     $confhash{$item}{$type} = 0;
11127:                 }
11128:             }
11129:             if (ref($domconfig{$action}) eq 'HASH') {
11130:                 if ($action eq 'requestauthor') {
11131:                     if ($domconfig{$action}{$type} ne $confhash{$type}) {
11132:                         $changes{$type} = 1;
11133:                     }
11134:                 } elsif (ref($domconfig{$action}{$item}) eq 'HASH') {
11135:                     if ($domconfig{$action}{$item}{$type} ne $confhash{$item}{$type}) {
11136:                         $changes{$item}{$type} = 1;
11137:                     }
11138:                 } else {
11139:                     if ($context eq 'requestcourses') {
11140:                         if ($confhash{$item}{$type} ne $unset) {
11141:                             $changes{$item}{$type} = 1;
11142:                         }
11143:                     } else {
11144:                         if (!$confhash{$item}{$type}) {
11145:                             $changes{$item}{$type} = 1;
11146:                         }
11147:                     }
11148:                 }
11149:             } else {
11150:                 if ($context eq 'requestcourses') {
11151:                     if ($confhash{$item}{$type} ne $unset) {
11152:                         $changes{$item}{$type} = 1;
11153:                     }
11154:                 } elsif ($context eq 'requestauthor') {
11155:                     if ($confhash{$type} ne $unset) {
11156:                         $changes{$type} = 1;
11157:                     }
11158:                 } else {
11159:                     if (!$confhash{$item}{$type}) {
11160:                         $changes{$item}{$type} = 1;
11161:                     }
11162:                 }
11163:             }
11164:         }
11165:     }
11166:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
11167:         if (ref($domconfig{'quotas'}) eq 'HASH') {
11168:             if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
11169:                 foreach my $key (keys(%{$domconfig{'quotas'}{'defaultquota'}})) {
11170:                     if (exists($confhash{'defaultquota'}{$key})) {
11171:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{'defaultquota'}{$key}) {
11172:                             $changes{'defaultquota'}{$key} = 1;
11173:                         }
11174:                     } else {
11175:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{'defaultquota'}{$key};
11176:                     }
11177:                 }
11178:             } else {
11179:                 foreach my $key (keys(%{$domconfig{'quotas'}})) {
11180:                     if (exists($confhash{'defaultquota'}{$key})) {
11181:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{$key}) {
11182:                             $changes{'defaultquota'}{$key} = 1;
11183:                         }
11184:                     } else {
11185:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{$key};
11186:                     }
11187:                 }
11188:             }
11189:             if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
11190:                 foreach my $key (keys(%{$domconfig{'quotas'}{'authorquota'}})) {
11191:                     if (exists($confhash{'authorquota'}{$key})) {
11192:                         if ($confhash{'authorquota'}{$key} ne $domconfig{'quotas'}{'authorquota'}{$key}) {
11193:                             $changes{'authorquota'}{$key} = 1;
11194:                         }
11195:                     } else {
11196:                         $confhash{'authorquota'}{$key} = $domconfig{'quotas'}{'authorquota'}{$key};
11197:                     }
11198:                 }
11199:             }
11200:         }
11201:         if (ref($confhash{'defaultquota'}) eq 'HASH') {
11202:             foreach my $key (keys(%{$confhash{'defaultquota'}})) {
11203:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
11204:                     if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
11205:                         if (!exists($domconfig{'quotas'}{'defaultquota'}{$key})) {
11206:                             $changes{'defaultquota'}{$key} = 1;
11207:                         }
11208:                     } else {
11209:                         if (!exists($domconfig{'quotas'}{$key})) {
11210:                             $changes{'defaultquota'}{$key} = 1;
11211:                         }
11212:                     }
11213:                 } else {
11214:                     $changes{'defaultquota'}{$key} = 1;
11215:                 }
11216:             }
11217:         }
11218:         if (ref($confhash{'authorquota'}) eq 'HASH') {
11219:             foreach my $key (keys(%{$confhash{'authorquota'}})) {
11220:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
11221:                     if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
11222:                         if (!exists($domconfig{'quotas'}{'authorquota'}{$key})) {
11223:                             $changes{'authorquota'}{$key} = 1;
11224:                         }
11225:                     } else {
11226:                         $changes{'authorquota'}{$key} = 1;
11227:                     }
11228:                 } else {
11229:                     $changes{'authorquota'}{$key} = 1;
11230:                 }
11231:             }
11232:         }
11233:     }
11234: 
11235:     if ($context eq 'requestauthor') {
11236:         $domdefaults{'requestauthor'} = \%confhash;
11237:     } else {
11238:         foreach my $key (keys(%confhash)) {
11239:             unless (($context eq 'requestcourses') && (($key eq 'textbooks') || ($key eq 'templates'))) {
11240:                 $domdefaults{$key} = $confhash{$key};
11241:             }
11242:         }
11243:     }
11244: 
11245:     my %quotahash = (
11246:                       $action => { %confhash }
11247:                     );
11248:     my $putresult = &Apache::lonnet::put_dom('configuration',\%quotahash,
11249:                                              $dom);
11250:     if ($putresult eq 'ok') {
11251:         if (keys(%changes) > 0) {
11252:             my $cachetime = 24*60*60;
11253:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
11254:             if (ref($lastactref) eq 'HASH') {
11255:                 $lastactref->{'domdefaults'} = 1;
11256:             }
11257:             $resulttext = &mt('Changes made:').'<ul>';
11258:             unless (($context eq 'requestcourses') ||
11259:                     ($context eq 'requestauthor')) {
11260:                 if (ref($changes{'defaultquota'}) eq 'HASH') {
11261:                     $resulttext .= '<li>'.&mt('Portfolio default quotas').'<ul>';
11262:                     foreach my $type (@{$types},'default') {
11263:                         if (defined($changes{'defaultquota'}{$type})) {
11264:                             my $typetitle = $usertypes->{$type};
11265:                             if ($type eq 'default') {
11266:                                 $typetitle = $othertitle;
11267:                             }
11268:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'defaultquota'}{$type}).'</li>';
11269:                         }
11270:                     }
11271:                     $resulttext .= '</ul></li>';
11272:                 }
11273:                 if (ref($changes{'authorquota'}) eq 'HASH') {
11274:                     $resulttext .= '<li>'.&mt('Authoring Space default quotas').'<ul>';
11275:                     foreach my $type (@{$types},'default') {
11276:                         if (defined($changes{'authorquota'}{$type})) {
11277:                             my $typetitle = $usertypes->{$type};
11278:                             if ($type eq 'default') {
11279:                                 $typetitle = $othertitle;
11280:                             }
11281:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'authorquota'}{$type}).'</li>';
11282:                         }
11283:                     }
11284:                     $resulttext .= '</ul></li>';
11285:                 }
11286:             }
11287:             my %newenv;
11288:             foreach my $item (@usertools) {
11289:                 my (%haschgs,%inconf);
11290:                 if ($context eq 'requestauthor') {
11291:                     %haschgs = %changes;
11292:                     %inconf = %confhash;
11293:                 } else {
11294:                     if (ref($changes{$item}) eq 'HASH') {
11295:                         %haschgs = %{$changes{$item}};
11296:                     }
11297:                     if (ref($confhash{$item}) eq 'HASH') {
11298:                         %inconf = %{$confhash{$item}};
11299:                     }
11300:                 }
11301:                 if (keys(%haschgs) > 0) {
11302:                     my $newacc = 
11303:                         &Apache::lonnet::usertools_access($env{'user.name'},
11304:                                                           $env{'user.domain'},
11305:                                                           $item,'reload',$context);
11306:                     if (($context eq 'requestcourses') ||
11307:                         ($context eq 'requestauthor')) {
11308:                         if ($env{'environment.canrequest.'.$item} ne $newacc) {
11309:                             $newenv{'environment.canrequest.'.$item} = $newacc;
11310:                         }
11311:                     } else {
11312:                         if ($env{'environment.availabletools.'.$item} ne $newacc) { 
11313:                             $newenv{'environment.availabletools.'.$item} = $newacc;
11314:                         }
11315:                     }
11316:                     unless ($context eq 'requestauthor') {
11317:                         $resulttext .= '<li>'.$titles{$item}.'<ul>';
11318:                     }
11319:                     foreach my $type (@{$types},'default','_LC_adv') {
11320:                         if ($haschgs{$type}) {
11321:                             my $typetitle = $usertypes->{$type};
11322:                             if ($type eq 'default') {
11323:                                 $typetitle = $othertitle;
11324:                             } elsif ($type eq '_LC_adv') {
11325:                                 $typetitle = 'LON-CAPA Advanced Users'; 
11326:                             }
11327:                             if ($inconf{$type}) {
11328:                                 if ($context eq 'requestcourses') {
11329:                                     my $cond;
11330:                                     if ($inconf{$type} =~ /^autolimit=(\d*)$/) {
11331:                                         if ($1 eq '') {
11332:                                             $cond = &mt('(Automatic processing of any request).');
11333:                                         } else {
11334:                                             $cond = &mt('(Automatic processing of requests up to limit of [quant,_1,request] per user).',$1);
11335:                                         }
11336:                                     } else { 
11337:                                         $cond = $conditions{$inconf{$type}};
11338:                                     }
11339:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1].',$typetitle).' '.$cond.'</li>';
11340:                                 } elsif ($context eq 'requestauthor') {
11341:                                     $resulttext .= '<li>'.&mt('Set to "[_1]" for "[_2]".',
11342:                                                              $titles{$inconf{$type}},$typetitle);
11343: 
11344:                                 } else {
11345:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1]',$typetitle).'</li>';
11346:                                 }
11347:                             } else {
11348:                                 if ($type eq '_LC_adv') {
11349:                                     if ($inconf{$type} eq '0') {
11350:                                         $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
11351:                                     } else { 
11352:                                         $resulttext .= '<li>'.&mt('No override set for [_1]',$typetitle).'</li>';
11353:                                     }
11354:                                 } else {
11355:                                     $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
11356:                                 }
11357:                             }
11358:                         }
11359:                     }
11360:                     unless ($context eq 'requestauthor') {
11361:                         $resulttext .= '</ul></li>';
11362:                     }
11363:                 }
11364:             }
11365:             if (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
11366:                 if (ref($changes{'notify'}) eq 'HASH') {
11367:                     if ($changes{'notify'}{'approval'}) {
11368:                         if (ref($confhash{'notify'}) eq 'HASH') {
11369:                             if ($confhash{'notify'}{'approval'}) {
11370:                                 $resulttext .= '<li>'.&mt('Notification of requests requiring approval will be sent to: ').$confhash{'notify'}{'approval'}.'</li>';
11371:                             } else {
11372:                                 $resulttext .= '<li>'.&mt('No Domain Coordinators will receive notification of requests requiring approval.').'</li>';
11373:                             }
11374:                         }
11375:                     }
11376:                 }
11377:             }
11378:             if ($action eq 'requestcourses') {
11379:                 my @offon = ('off','on');
11380:                 if ($changes{'uniquecode'}) {
11381:                     if (ref($confhash{'uniquecode'}) eq 'HASH') {
11382:                         my $codestr = join(' ',map{ &mt($_); } sort(keys(%{$confhash{'uniquecode'}})));
11383:                         $resulttext .= '<li>'.
11384:                                        &mt('Generation of six character code as course identifier for distribution to students set to on for: [_1].','<b>'.$codestr.'</b>').
11385:                                        '</li>';
11386:                     } else {
11387:                         $resulttext .= '<li>'.&mt('Generation of six character code as course identifier for distribution to students set to off.').
11388:                                        '</li>';
11389:                     }
11390:                 }
11391:                 foreach my $type ('textbooks','templates') {
11392:                     if (ref($changes{$type}) eq 'HASH') {
11393:                         $resulttext .= '<li>'.&mt("Available $type updated").'<ul>';
11394:                         foreach my $key (sort(keys(%{$changes{$type}}))) {
11395:                             my %coursehash = &Apache::lonnet::coursedescription($key);
11396:                             my $coursetitle = $coursehash{'description'};
11397:                             my $position = $confhash{$type}{$key}{'order'} + 1;
11398:                             $resulttext .= '<li>';
11399:                             foreach my $item ('subject','title','publisher','author') {
11400:                                 next if ((($item eq 'author') || ($item eq 'publisher')) &&
11401:                                          ($type eq 'templates'));
11402:                                 my $name = $item.':';
11403:                                 $name =~ s/^(\w)/\U$1/;
11404:                                 $resulttext .= &mt($name).' '.$confhash{$type}{$key}{$item}.'<br />';
11405:                             }
11406:                             $resulttext .= ' '.&mt('Order: [_1]',$position).'<br />';
11407:                             if ($type eq 'textbooks') {
11408:                                 if ($confhash{$type}{$key}{'image'}) {
11409:                                     $resulttext .= ' '.&mt('Image: [_1]',
11410:                                                    '<img src="'.$confhash{$type}{$key}{'image'}.'"'.
11411:                                                    ' alt="Textbook cover" />').'<br />';
11412:                                 }
11413:                             }
11414:                             $resulttext .= ' '.&mt('LON-CAPA Course: [_1]',$coursetitle).'</li>';
11415:                         }
11416:                         $resulttext .= '</ul></li>';
11417:                     }
11418:                 }
11419:                 if (ref($changes{'validation'}) eq 'HASH') {
11420:                     if ((ref($validationitemsref) eq 'ARRAY') && (ref($validationnamesref) eq 'HASH')) {
11421:                         $resulttext .= '<li>'.&mt('Validation of courses/communities updated').'<ul>';
11422:                         foreach my $item (@{$validationitemsref}) {
11423:                             if (exists($changes{'validation'}{$item})) {
11424:                                 if ($item eq 'markup') {
11425:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
11426:                                                               '<br /><pre>'.$changes{'validation'}{$item}.'</pre>').'</li>';
11427:                                 } else {
11428:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
11429:                                                               '<b>'.$changes{'validation'}{$item}.'</b>').'</li>';
11430:                                 }
11431:                             }
11432:                         }
11433:                         if (exists($changes{'validation'}{'dc'})) {
11434:                             $resulttext .= '<li>'.&mt('Validated course requests identified as processed by: [_1]',
11435:                                                      '<b>'.$changes{'validation'}{'dc'}.'</b>').'</li>';
11436:                         }
11437:                     }
11438:                 }
11439:             }
11440:             $resulttext .= '</ul>';
11441:             if (keys(%newenv)) {
11442:                 &Apache::lonnet::appenv(\%newenv);
11443:             }
11444:         } else {
11445:             if ($context eq 'requestcourses') {
11446:                 $resulttext = &mt('No changes made to rights to request creation of courses.');
11447:             } elsif ($context eq 'requestauthor') {
11448:                 $resulttext = &mt('No changes made to rights to request author space.');
11449:             } else {
11450:                 $resulttext = &mt('No changes made to availability of personal information pages, blogs, portfolios or default quotas');
11451:             }
11452:         }
11453:     } else {
11454:         $resulttext = '<span class="LC_error">'.
11455: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
11456:     }
11457:     if ($errors) {
11458:         $resulttext .= '<p>'.&mt('The following errors occurred when modifying Textbook settings.').
11459:                        '<ul>'.$errors.'</ul></p>';
11460:     }
11461:     return $resulttext;
11462: }
11463: 
11464: sub process_textbook_image {
11465:     my ($r,$dom,$confname,$caller,$cdom,$cnum,$type,$configuserok,$switchserver,$author_ok) = @_;
11466:     my $filename = $env{'form.'.$caller.'.filename'};
11467:     my ($error,$url);
11468:     my ($width,$height) = (50,50);
11469:     if ($configuserok eq 'ok') {
11470:         if ($switchserver) {
11471:             $error = &mt('Upload of textbook image is not permitted to this server: [_1]',
11472:                          $switchserver);
11473:         } elsif ($author_ok eq 'ok') {
11474:             my ($result,$imageurl) =
11475:                 &publishlogo($r,'upload',$caller,$dom,$confname,
11476:                              "$type/$cdom/$cnum/cover",$width,$height);
11477:             if ($result eq 'ok') {
11478:                 $url = $imageurl;
11479:             } else {
11480:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
11481:             }
11482:         } else {
11483:             $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);
11484:         }
11485:     } else {
11486:         $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);
11487:     }
11488:     return ($url,$error);
11489: }
11490: 
11491: sub modify_autoenroll {
11492:     my ($dom,$lastactref,%domconfig) = @_;
11493:     my ($resulttext,%changes);
11494:     my %currautoenroll;
11495:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
11496:         foreach my $key (keys(%{$domconfig{'autoenroll'}})) {
11497:             $currautoenroll{$key} = $domconfig{'autoenroll'}{$key};
11498:         }
11499:     }
11500:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
11501:     my %title = ( run => 'Auto-enrollment active',
11502:                   sender => 'Sender for notification messages',
11503:                   coowners => 'Automatic assignment of co-ownership to instructors of record (institutional data)',
11504:                   autofailsafe => 'Failsafe for no drops if institutional data missing for a section');
11505:     my @offon = ('off','on');
11506:     my $sender_uname = $env{'form.sender_uname'};
11507:     my $sender_domain = $env{'form.sender_domain'};
11508:     if ($sender_domain eq '') {
11509:         $sender_uname = '';
11510:     } elsif ($sender_uname eq '') {
11511:         $sender_domain = '';
11512:     }
11513:     my $coowners = $env{'form.autoassign_coowners'};
11514:     my $autofailsafe = $env{'form.autoenroll_autofailsafe'};
11515:     $autofailsafe =~ s{^\s+|\s+$}{}g;
11516:     if ($autofailsafe =~ /\D/) {
11517:         undef($autofailsafe);
11518:     }
11519:     my $failsafe = $env{'form.autoenroll_failsafe'};
11520:     unless (($failsafe eq 'zero') || ($failsafe eq 'any')) {
11521:         $failsafe = 'off';
11522:         undef($autofailsafe);
11523:     }
11524:     my %autoenrollhash =  (
11525:                        autoenroll => { 'run' => $env{'form.autoenroll_run'},
11526:                                        'sender_uname' => $sender_uname,
11527:                                        'sender_domain' => $sender_domain,
11528:                                        'co-owners' => $coowners,
11529:                                        'autofailsafe' => $autofailsafe,
11530:                                        'failsafe' => $failsafe,
11531:                                 }
11532:                      );
11533:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autoenrollhash,
11534:                                              $dom);
11535:     if ($putresult eq 'ok') {
11536:         if (exists($currautoenroll{'run'})) {
11537:              if ($currautoenroll{'run'} ne $env{'form.autoenroll_run'}) {
11538:                  $changes{'run'} = 1;
11539:              }
11540:         } elsif ($autorun) {
11541:             if ($env{'form.autoenroll_run'} ne '1') {
11542:                  $changes{'run'} = 1;
11543:             }
11544:         }
11545:         if ($currautoenroll{'sender_uname'} ne $sender_uname) {
11546:             $changes{'sender'} = 1;
11547:         }
11548:         if ($currautoenroll{'sender_domain'} ne $sender_domain) {
11549:             $changes{'sender'} = 1;
11550:         }
11551:         if ($currautoenroll{'co-owners'} ne '') {
11552:             if ($currautoenroll{'co-owners'} ne $coowners) {
11553:                 $changes{'coowners'} = 1;
11554:             }
11555:         } elsif ($coowners) {
11556:             $changes{'coowners'} = 1;
11557:         }
11558:         if ($currautoenroll{'autofailsafe'} ne $autofailsafe) {
11559:             $changes{'autofailsafe'} = 1;
11560:         }
11561:         if ($currautoenroll{'failsafe'} ne $failsafe) {
11562:             $changes{'failsafe'} = 1;
11563:         }
11564:         if (keys(%changes) > 0) {
11565:             $resulttext = &mt('Changes made:').'<ul>';
11566:             if ($changes{'run'}) {
11567:                 $resulttext .= '<li>'.&mt("$title{'run'} set to $offon[$env{'form.autoenroll_run'}]").'</li>';
11568:             }
11569:             if ($changes{'sender'}) {
11570:                 if ($sender_uname eq '' || $sender_domain eq '') {
11571:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to default (course owner).").'</li>';
11572:                 } else {
11573:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to [_1]",$sender_uname.':'.$sender_domain).'</li>';
11574:                 }
11575:             }
11576:             if ($changes{'coowners'}) {
11577:                 $resulttext .= '<li>'.&mt("$title{'coowners'} set to $offon[$env{'form.autoassign_coowners'}]").'</li>';
11578:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
11579:                 if (ref($lastactref) eq 'HASH') {
11580:                     $lastactref->{'domainconfig'} = 1;
11581:                 }
11582:             }
11583:             if ($changes{'autofailsafe'}) {
11584:                 if ($autofailsafe ne '') {
11585:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section set to: [_1]',$autofailsafe).'</li>';
11586:                 } else {
11587:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section not in use').'</li>';
11588:                 }
11589:             }
11590:             if ($changes{'failsafe'}) {
11591:                 if ($failsafe eq 'off') {
11592:                     unless ($changes{'autofailsafe'}) {
11593:                         $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section not in use').'</li>';
11594:                     }
11595:                 } elsif ($failsafe eq 'zero') {
11596:                     $resulttext .= '<li>'.&mt('Failsafe applies if retrieved section enrollment is zero').'</li>';
11597:                 } else {
11598:                     $resulttext .= '<li>'.&mt('Failsafe applies if retrieved section enrollment is zero or greater').'</li>';
11599:                 }
11600:             }
11601:             if (($changes{'autofailsafe'}) || ($changes{'failsafe'})) {
11602:                 &Apache::lonnet::get_domain_defaults($dom,1);
11603:                 if (ref($lastactref) eq 'HASH') {
11604:                     $lastactref->{'domdefaults'} = 1;
11605:                 }
11606:             }
11607:             $resulttext .= '</ul>';
11608:         } else {
11609:             $resulttext = &mt('No changes made to auto-enrollment settings');
11610:         }
11611:     } else {
11612:         $resulttext = '<span class="LC_error">'.
11613: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
11614:     }
11615:     return $resulttext;
11616: }
11617: 
11618: sub modify_autoupdate {
11619:     my ($dom,%domconfig) = @_;
11620:     my ($resulttext,%currautoupdate,%fields,%changes);
11621:     if (ref($domconfig{'autoupdate'}) eq 'HASH') {
11622:         foreach my $key (keys(%{$domconfig{'autoupdate'}})) {
11623:             $currautoupdate{$key} = $domconfig{'autoupdate'}{$key};
11624:         }
11625:     }
11626:     my @offon = ('off','on');
11627:     my %title = &Apache::lonlocal::texthash (
11628:                     run        => 'Auto-update:',
11629:                     classlists => 'Updates to user information in classlists?',
11630:                     unexpired  => 'Skip updates for users without active or future roles?',
11631:                     lastactive => 'Skip updates for inactive users?',
11632:                 );
11633:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
11634:     my %fieldtitles = &Apache::lonlocal::texthash (
11635:                         id => 'Student/Employee ID',
11636:                         permanentemail => 'E-mail address',
11637:                         lastname => 'Last Name',
11638:                         firstname => 'First Name',
11639:                         middlename => 'Middle Name',
11640:                         generation => 'Generation',
11641:                       );
11642:     $othertitle = &mt('All users');
11643:     if (keys(%{$usertypes}) >  0) {
11644:         $othertitle = &mt('Other users');
11645:     }
11646:     foreach my $key (keys(%env)) {
11647:         if ($key =~ /^form\.updateable_(.+)_([^_]+)$/) {
11648:             my ($usertype,$item) = ($1,$2);
11649:             if (grep(/^\Q$item\E$/,keys(%fieldtitles))) {
11650:                 if ($usertype eq 'default') {   
11651:                     push(@{$fields{$1}},$2);
11652:                 } elsif (ref($types) eq 'ARRAY') {
11653:                     if (grep(/^\Q$usertype\E$/,@{$types})) {
11654:                         push(@{$fields{$1}},$2);
11655:                     }
11656:                 }
11657:             }
11658:         }
11659:     }
11660:     my @lockablenames = &Apache::loncommon::get_env_multiple('form.lockablenames');
11661:     @lockablenames = sort(@lockablenames);
11662:     if (ref($currautoupdate{'lockablenames'}) eq 'ARRAY') {
11663:         my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
11664:         if (@changed) {
11665:             $changes{'lockablenames'} = 1;
11666:         }
11667:     } else {
11668:         if (@lockablenames) {
11669:             $changes{'lockablenames'} = 1;
11670:         }
11671:     }
11672:     my %updatehash = (
11673:                       autoupdate => { run => $env{'form.autoupdate_run'},
11674:                                       classlists => $env{'form.classlists'},
11675:                                       unexpired  => $env{'form.unexpired'},
11676:                                       fields => {%fields},
11677:                                       lockablenames => \@lockablenames,
11678:                                     }
11679:                      );
11680:     my $lastactivedays;
11681:     if ($env{'form.lastactive'}) {
11682:         $lastactivedays = $env{'form.lastactivedays'};
11683:         $lastactivedays =~ s/^\s+|\s+$//g;
11684:         unless ($lastactivedays =~ /^\d+$/) {
11685:             undef($lastactivedays);
11686:             $env{'form.lastactive'} = 0;
11687:         }
11688:     }
11689:     $updatehash{'autoupdate'}{'lastactive'} = $lastactivedays;
11690:     foreach my $key (keys(%currautoupdate)) {
11691:         if (($key eq 'run') || ($key eq 'classlists') || ($key eq 'unexpired') || ($key eq 'lastactive')) {
11692:             if (exists($updatehash{autoupdate}{$key})) {
11693:                 if ($currautoupdate{$key} ne $updatehash{autoupdate}{$key}) {
11694:                     $changes{$key} = 1;
11695:                 }
11696:             }
11697:         } elsif ($key eq 'fields') {
11698:             if (ref($currautoupdate{$key}) eq 'HASH') {
11699:                 foreach my $item (@{$types},'default') {
11700:                     if (ref($currautoupdate{$key}{$item}) eq 'ARRAY') {
11701:                         my $change = 0;
11702:                         foreach my $type (@{$currautoupdate{$key}{$item}}) {
11703:                             if (!exists($fields{$item})) {
11704:                                 $change = 1;
11705:                                 last;
11706:                             } elsif (ref($fields{$item}) eq 'ARRAY') {
11707:                                 if (!grep(/^\Q$type\E$/,@{$fields{$item}})) {
11708:                                     $change = 1;
11709:                                     last;
11710:                                 }
11711:                             }
11712:                         }
11713:                         if ($change) {
11714:                             push(@{$changes{$key}},$item);
11715:                         }
11716:                     } 
11717:                 }
11718:             }
11719:         } elsif ($key eq 'lockablenames') {
11720:             if (ref($currautoupdate{$key}) eq 'ARRAY') {
11721:                 my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
11722:                 if (@changed) {
11723:                     $changes{'lockablenames'} = 1;
11724:                 }
11725:             } else {
11726:                 if (@lockablenames) {
11727:                     $changes{'lockablenames'} = 1;
11728:                 }
11729:             }
11730:         }
11731:     }
11732:     unless (grep(/^\Qlockablenames\E$/,keys(%currautoupdate))) {
11733:         if (@lockablenames) {
11734:             $changes{'lockablenames'} = 1;
11735:         }
11736:     }
11737:     unless (grep(/^unexpired$/,keys(%currautoupdate))) {
11738:         if ($updatehash{'autoupdate'}{'unexpired'}) {
11739:             $changes{'unexpired'} = 1;
11740:         }
11741:     }
11742:     unless (grep(/^lastactive$/,keys(%currautoupdate))) {
11743:         if ($updatehash{'autoupdate'}{'lastactive'} ne '') {
11744:             $changes{'lastactive'} = 1;
11745:         }
11746:     }
11747:     foreach my $item (@{$types},'default') {
11748:         if (defined($fields{$item})) {
11749:             if (ref($currautoupdate{'fields'}) eq 'HASH') {
11750:                 if (ref($currautoupdate{'fields'}{$item}) eq 'ARRAY') {
11751:                     my $change = 0;
11752:                     if (ref($fields{$item}) eq 'ARRAY') {
11753:                         foreach my $type (@{$fields{$item}}) {
11754:                             if (!grep(/^\Q$type\E$/,@{$currautoupdate{'fields'}{$item}})) {
11755:                                 $change = 1;
11756:                                 last;
11757:                             }
11758:                         }
11759:                     }
11760:                     if ($change) {
11761:                         push(@{$changes{'fields'}},$item);
11762:                     }
11763:                 } else {
11764:                     push(@{$changes{'fields'}},$item);
11765:                 }
11766:             } else {
11767:                 push(@{$changes{'fields'}},$item);
11768:             }
11769:         }
11770:     }
11771:     my $putresult = &Apache::lonnet::put_dom('configuration',\%updatehash,
11772:                                              $dom);
11773:     if ($putresult eq 'ok') {
11774:         if (keys(%changes) > 0) {
11775:             $resulttext = &mt('Changes made:').'<ul>';
11776:             foreach my $key (sort(keys(%changes))) {
11777:                 if ($key eq 'lockablenames') {
11778:                     $resulttext .= '<li>';
11779:                     if (@lockablenames) {
11780:                         $usertypes->{'default'} = $othertitle;
11781:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update), available for the following affiliations:").' '.
11782:                                    join(', ', map { $usertypes->{$_}; } @lockablenames).'</li>';
11783:                     } else {
11784:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update) is unavailable.");
11785:                     }
11786:                     $resulttext .= '</li>';
11787:                 } elsif (ref($changes{$key}) eq 'ARRAY') {
11788:                     foreach my $item (@{$changes{$key}}) {
11789:                         my @newvalues;
11790:                         foreach my $type (@{$fields{$item}}) {
11791:                             push(@newvalues,$fieldtitles{$type});
11792:                         }
11793:                         my $newvaluestr;
11794:                         if (@newvalues > 0) {
11795:                             $newvaluestr = join(', ',@newvalues);
11796:                         } else {
11797:                             $newvaluestr = &mt('none');
11798:                         }
11799:                         if ($item eq 'default') {
11800:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$othertitle,$newvaluestr).'</li>';
11801:                         } else {
11802:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$usertypes->{$item},$newvaluestr).'</li>';
11803:                         }
11804:                     }
11805:                 } else {
11806:                     my $newvalue;
11807:                     if ($key eq 'run') {
11808:                         $newvalue = $offon[$env{'form.autoupdate_run'}];
11809:                     } elsif ($key eq 'lastactive') {
11810:                         $newvalue = $offon[$env{'form.lastactive'}];
11811:                         unless ($lastactivedays eq '') {
11812:                             $newvalue .= '; '.&mt('inactive = no activity in last [quant,_1,day]',$lastactivedays);
11813:                         }
11814:                     } else {
11815:                         $newvalue = $offon[$env{'form.'.$key}];
11816:                     }
11817:                     $resulttext .= '<li>'.&mt("[_1] set to $newvalue",$title{$key}).'</li>';
11818:                 }
11819:             }
11820:             $resulttext .= '</ul>';
11821:         } else {
11822:             $resulttext = &mt('No changes made to autoupdates');
11823:         }
11824:     } else {
11825:         $resulttext = '<span class="LC_error">'.
11826: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
11827:     }
11828:     return $resulttext;
11829: }
11830: 
11831: sub modify_autocreate {
11832:     my ($dom,%domconfig) = @_;
11833:     my ($resulttext,%changes,%currautocreate,%newvals,%autocreatehash);
11834:     if (ref($domconfig{'autocreate'}) eq 'HASH') {
11835:         foreach my $key (keys(%{$domconfig{'autocreate'}})) {
11836:             $currautocreate{$key} = $domconfig{'autocreate'}{$key};
11837:         }
11838:     }
11839:     my %title= ( xml => 'Auto-creation of courses in XML course description files',
11840:                  req => 'Auto-creation of validated requests for official courses',
11841:                  xmldc => 'Identity of course creator of courses from XML files',
11842:                );
11843:     my @types = ('xml','req');
11844:     foreach my $item (@types) {
11845:         $newvals{$item} = $env{'form.autocreate_'.$item};
11846:         $newvals{$item} =~ s/\D//g;
11847:         $newvals{$item} = 0 if ($newvals{$item} eq '');
11848:     }
11849:     $newvals{'xmldc'} = $env{'form.autocreate_xmldc'};
11850:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
11851:     unless (exists($domcoords{$newvals{'xmldc'}})) {
11852:         $newvals{'xmldc'} = '';
11853:     } 
11854:     %autocreatehash =  (
11855:                         autocreate => { xml => $newvals{'xml'},
11856:                                         req => $newvals{'req'},
11857:                                       }
11858:                        );
11859:     if ($newvals{'xmldc'} ne '') {
11860:         $autocreatehash{'autocreate'}{'xmldc'} = $newvals{'xmldc'};
11861:     }
11862:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autocreatehash,
11863:                                              $dom);
11864:     if ($putresult eq 'ok') {
11865:         my @items = @types;
11866:         if ($newvals{'xml'}) {
11867:             push(@items,'xmldc');
11868:         }
11869:         foreach my $item (@items) {
11870:             if (exists($currautocreate{$item})) {
11871:                 if ($currautocreate{$item} ne $newvals{$item}) {
11872:                     $changes{$item} = 1;
11873:                 }
11874:             } elsif ($newvals{$item}) {
11875:                 $changes{$item} = 1;
11876:             }
11877:         }
11878:         if (keys(%changes) > 0) {
11879:             my @offon = ('off','on'); 
11880:             $resulttext = &mt('Changes made:').'<ul>';
11881:             foreach my $item (@types) {
11882:                 if ($changes{$item}) {
11883:                     my $newtxt = $offon[$newvals{$item}];
11884:                     $resulttext .= '<li>'.
11885:                                    &mt("$title{$item} set to [_1]$newtxt [_2]",
11886:                                        '<b>','</b>').
11887:                                    '</li>';
11888:                 }
11889:             }
11890:             if ($changes{'xmldc'}) {
11891:                 my ($dcname,$dcdom) = split(':',$newvals{'xmldc'});
11892:                 my $newtxt = &Apache::loncommon::plainname($dcname,$dcdom);
11893:                 $resulttext .= '<li>'.&mt("$title{'xmldc'} set to [_1]",'<b>'.$newtxt.'</b>').'</li>'; 
11894:             }
11895:             $resulttext .= '</ul>';
11896:         } else {
11897:             $resulttext = &mt('No changes made to auto-creation settings');
11898:         }
11899:     } else {
11900:         $resulttext = '<span class="LC_error">'.
11901:             &mt('An error occurred: [_1]',$putresult).'</span>';
11902:     }
11903:     return $resulttext;
11904: }
11905: 
11906: sub modify_directorysrch {
11907:     my ($dom,$lastactref,%domconfig) = @_;
11908:     my ($resulttext,%changes);
11909:     my %currdirsrch;
11910:     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
11911:         foreach my $key (keys(%{$domconfig{'directorysrch'}})) {
11912:             $currdirsrch{$key} = $domconfig{'directorysrch'}{$key};
11913:         }
11914:     }
11915:     my %title = ( available => 'Institutional directory search available',
11916:                   localonly => 'Other domains can search institution',
11917:                   lcavailable => 'LON-CAPA directory search available',
11918:                   lclocalonly => 'Other domains can search LON-CAPA domain',
11919:                   searchby => 'Search types',
11920:                   searchtypes => 'Search latitude');
11921:     my @offon = ('off','on');
11922:     my @otherdoms = ('Yes','No');
11923: 
11924:     my @searchtypes = &Apache::loncommon::get_env_multiple('form.searchtypes');  
11925:     my @cansearch = &Apache::loncommon::get_env_multiple('form.cansearch');
11926:     my @searchby = &Apache::loncommon::get_env_multiple('form.searchby');
11927: 
11928:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
11929:     if (keys(%{$usertypes}) == 0) {
11930:         @cansearch = ('default');
11931:     } else {
11932:         if (ref($currdirsrch{'cansearch'}) eq 'ARRAY') {
11933:             foreach my $type (@{$currdirsrch{'cansearch'}}) {
11934:                 if (!grep(/^\Q$type\E$/,@cansearch)) {
11935:                     push(@{$changes{'cansearch'}},$type);
11936:                 }
11937:             }
11938:             foreach my $type (@cansearch) {
11939:                 if (!grep(/^\Q$type\E$/,@{$currdirsrch{'cansearch'}})) {
11940:                     push(@{$changes{'cansearch'}},$type);
11941:                 }
11942:             }
11943:         } else {
11944:             push(@{$changes{'cansearch'}},@cansearch);
11945:         }
11946:     }
11947: 
11948:     if (ref($currdirsrch{'searchby'}) eq 'ARRAY') {
11949:         foreach my $by (@{$currdirsrch{'searchby'}}) {
11950:             if (!grep(/^\Q$by\E$/,@searchby)) {
11951:                 push(@{$changes{'searchby'}},$by);
11952:             }
11953:         }
11954:         foreach my $by (@searchby) {
11955:             if (!grep(/^\Q$by\E$/,@{$currdirsrch{'searchby'}})) {
11956:                 push(@{$changes{'searchby'}},$by);
11957:             }
11958:         }
11959:     } else {
11960:         push(@{$changes{'searchby'}},@searchby);
11961:     }
11962: 
11963:     if (ref($currdirsrch{'searchtypes'}) eq 'ARRAY') {
11964:         foreach my $type (@{$currdirsrch{'searchtypes'}}) {
11965:             if (!grep(/^\Q$type\E$/,@searchtypes)) {
11966:                 push(@{$changes{'searchtypes'}},$type);
11967:             }
11968:         }
11969:         foreach my $type (@searchtypes) {
11970:             if (!grep(/^\Q$type\E$/,@{$currdirsrch{'searchtypes'}})) {
11971:                 push(@{$changes{'searchtypes'}},$type);
11972:             }
11973:         }
11974:     } else {
11975:         if (exists($currdirsrch{'searchtypes'})) {
11976:             foreach my $type (@searchtypes) {  
11977:                 if ($type ne $currdirsrch{'searchtypes'}) { 
11978:                     push(@{$changes{'searchtypes'}},$type);
11979:                 }
11980:             }
11981:             if (!grep(/^\Q$currdirsrch{'searchtypes'}\E/,@searchtypes)) {
11982:                 push(@{$changes{'searchtypes'}},$currdirsrch{'searchtypes'});
11983:             }   
11984:         } else {
11985:             push(@{$changes{'searchtypes'}},@searchtypes); 
11986:         }
11987:     }
11988: 
11989:     my %dirsrch_hash =  (
11990:             directorysrch => { available => $env{'form.dirsrch_available'},
11991:                                cansearch => \@cansearch,
11992:                                localonly => $env{'form.dirsrch_instlocalonly'},
11993:                                lclocalonly => $env{'form.dirsrch_domlocalonly'},
11994:                                lcavailable => $env{'form.dirsrch_domavailable'},
11995:                                searchby => \@searchby,
11996:                                searchtypes => \@searchtypes,
11997:                              }
11998:             );
11999:     my $putresult = &Apache::lonnet::put_dom('configuration',\%dirsrch_hash,
12000:                                              $dom);
12001:     if ($putresult eq 'ok') {
12002:         if (exists($currdirsrch{'available'})) {
12003:              if ($currdirsrch{'available'} ne $env{'form.dirsrch_available'}) {
12004:                  $changes{'available'} = 1;
12005:              }
12006:         } else {
12007:             if ($env{'form.dirsrch_available'} eq '1') {
12008:                 $changes{'available'} = 1;
12009:             }
12010:         }
12011:         if (exists($currdirsrch{'lcavailable'})) {
12012:             if ($currdirsrch{'lcavailable'} ne $env{'form.dirsrch_domavailable'}) {
12013:                 $changes{'lcavailable'} = 1;
12014:             }
12015:         } else {
12016:             if ($env{'form.dirsrch_lcavailable'} eq '1') {
12017:                 $changes{'lcavailable'} = 1;
12018:             }
12019:         }
12020:         if (exists($currdirsrch{'localonly'})) {
12021:             if ($currdirsrch{'localonly'} ne $env{'form.dirsrch_instlocalonly'}) {
12022:                 $changes{'localonly'} = 1;
12023:             }
12024:         } else {
12025:             if ($env{'form.dirsrch_instlocalonly'} eq '1') {
12026:                 $changes{'localonly'} = 1;
12027:             }
12028:         }
12029:         if (exists($currdirsrch{'lclocalonly'})) {
12030:             if ($currdirsrch{'lclocalonly'} ne $env{'form.dirsrch_domlocalonly'}) {
12031:                 $changes{'lclocalonly'} = 1;
12032:             }
12033:         } else {
12034:             if ($env{'form.dirsrch_domlocalonly'} eq '1') {
12035:                 $changes{'lclocalonly'} = 1;
12036:             }
12037:         }
12038:         if (keys(%changes) > 0) {
12039:             $resulttext = &mt('Changes made:').'<ul>';
12040:             if ($changes{'available'}) {
12041:                 $resulttext .= '<li>'.&mt("$title{'available'} set to: $offon[$env{'form.dirsrch_available'}]").'</li>';
12042:             }
12043:             if ($changes{'lcavailable'}) {
12044:                 $resulttext .= '<li>'.&mt("$title{'lcavailable'} set to: $offon[$env{'form.dirsrch_domavailable'}]").'</li>';
12045:             }
12046:             if ($changes{'localonly'}) {
12047:                 $resulttext .= '<li>'.&mt("$title{'localonly'} set to: $otherdoms[$env{'form.dirsrch_instlocalonly'}]").'</li>';
12048:             }
12049:             if ($changes{'lclocalonly'}) {
12050:                 $resulttext .= '<li>'.&mt("$title{'lclocalonly'} set to: $otherdoms[$env{'form.dirsrch_domlocalonly'}]").'</li>';
12051:             }
12052:             if (ref($changes{'cansearch'}) eq 'ARRAY') {
12053:                 my $chgtext;
12054:                 if (ref($usertypes) eq 'HASH') {
12055:                     if (keys(%{$usertypes}) > 0) {
12056:                         foreach my $type (@{$types}) {
12057:                             if (grep(/^\Q$type\E$/,@cansearch)) {
12058:                                 $chgtext .= $usertypes->{$type}.'; ';
12059:                             }
12060:                         }
12061:                         if (grep(/^default$/,@cansearch)) {
12062:                             $chgtext .= $othertitle;
12063:                         } else {
12064:                             $chgtext =~ s/\; $//;
12065:                         }
12066:                         $resulttext .=
12067:                             '<li>'.
12068:                             &mt("Users from domain '[_1]' permitted to search the institutional directory set to: [_2]",
12069:                                 '<span class="LC_cusr_emph">'.$dom.'</span>',$chgtext).
12070:                             '</li>';
12071:                     }
12072:                 }
12073:             }
12074:             if (ref($changes{'searchby'}) eq 'ARRAY') {
12075:                 my ($searchtitles,$titleorder) = &sorted_searchtitles();
12076:                 my $chgtext;
12077:                 foreach my $type (@{$titleorder}) {
12078:                     if (grep(/^\Q$type\E$/,@searchby)) {
12079:                         if (defined($searchtitles->{$type})) {
12080:                             $chgtext .= $searchtitles->{$type}.'; ';
12081:                         }
12082:                     }
12083:                 }
12084:                 $chgtext =~ s/\; $//;
12085:                 $resulttext .= '<li>'.&mt("$title{'searchby'} set to: [_1]",$chgtext).'</li>';
12086:             }
12087:             if (ref($changes{'searchtypes'}) eq 'ARRAY') {
12088:                 my ($srchtypes_desc,$srchtypeorder) = &sorted_searchtypes(); 
12089:                 my $chgtext;
12090:                 foreach my $type (@{$srchtypeorder}) {
12091:                     if (grep(/^\Q$type\E$/,@searchtypes)) {
12092:                         if (defined($srchtypes_desc->{$type})) {
12093:                             $chgtext .= $srchtypes_desc->{$type}.'; ';
12094:                         }
12095:                     }
12096:                 }
12097:                 $chgtext =~ s/\; $//;
12098:                 $resulttext .= '<li>'.&mt($title{'searchtypes'}.' set to: "[_1]"',$chgtext).'</li>';
12099:             }
12100:             $resulttext .= '</ul>';
12101:             &Apache::lonnet::do_cache_new('directorysrch',$dom,$dirsrch_hash{'directorysrch'},3600);
12102:             if (ref($lastactref) eq 'HASH') {
12103:                 $lastactref->{'directorysrch'} = 1;
12104:             }
12105:         } else {
12106:             $resulttext = &mt('No changes made to directory search settings');
12107:         }
12108:     } else {
12109:         $resulttext = '<span class="LC_error">'.
12110:                       &mt('An error occurred: [_1]',$putresult).'</span>';
12111:     }
12112:     return $resulttext;
12113: }
12114: 
12115: sub modify_contacts {
12116:     my ($dom,$lastactref,%domconfig) = @_;
12117:     my ($resulttext,%currsetting,%newsetting,%changes,%contacts_hash);
12118:     if (ref($domconfig{'contacts'}) eq 'HASH') {
12119:         foreach my $key (keys(%{$domconfig{'contacts'}})) {
12120:             $currsetting{$key} = $domconfig{'contacts'}{$key};
12121:         }
12122:     }
12123:     my (%others,%to,%bcc,%includestr,%includeloc);
12124:     my @contacts = ('supportemail','adminemail');
12125:     my @mailings = ('errormail','packagesmail','helpdeskmail','otherdomsmail',
12126:                     'lonstatusmail','requestsmail','updatesmail','idconflictsmail','hostipmail');
12127:     my @toggles = ('reporterrors','reportupdates','reportstatus');
12128:     my @lonstatus = ('threshold','sysmail','weights','excluded');
12129:     my ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
12130:     foreach my $type (@mailings) {
12131:         @{$newsetting{$type}} = 
12132:             &Apache::loncommon::get_env_multiple('form.'.$type);
12133:         foreach my $item (@contacts) {
12134:             if (grep(/^\Q$item\E$/,@{$newsetting{$type}})) {
12135:                 $contacts_hash{contacts}{$type}{$item} = 1;
12136:             } else {
12137:                 $contacts_hash{contacts}{$type}{$item} = 0;
12138:             }
12139:         }
12140:         $others{$type} = $env{'form.'.$type.'_others'};
12141:         $contacts_hash{contacts}{$type}{'others'} = $others{$type};
12142:         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
12143:             $bcc{$type} = $env{'form.'.$type.'_bcc'};
12144:             $contacts_hash{contacts}{$type}{'bcc'} = $bcc{$type};
12145:             if (($env{'form.'.$type.'_includestr'} ne '') && ($env{'form.'.$type.'_includeloc'} =~ /^s|b$/)) {
12146:                 $includestr{$type} = $env{'form.'.$type.'_includestr'};
12147:                 $includeloc{$type} = $env{'form.'.$type.'_includeloc'};
12148:                 $contacts_hash{contacts}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
12149:             }
12150:         }
12151:     }
12152:     foreach my $item (@contacts) {
12153:         $to{$item} = $env{'form.'.$item};
12154:         $contacts_hash{'contacts'}{$item} = $to{$item};
12155:     }
12156:     foreach my $item (@toggles) {
12157:         if ($env{'form.'.$item} =~ /^(0|1)$/) {
12158:             $contacts_hash{'contacts'}{$item} = $env{'form.'.$item};
12159:         }
12160:     }
12161:     my ($lonstatus_defs,$lonstatus_names) = &Apache::loncommon::lon_status_items();
12162:     foreach my $item (@lonstatus) {
12163:         if ($item eq 'excluded') {
12164:             my (%serverhomes,@excluded);
12165:             map { $serverhomes{$_} = 1; } values(%Apache::lonnet::serverhomeIDs);
12166:             my @possexcluded = &Apache::loncommon::get_env_multiple('form.errorexcluded');
12167:             if (@possexcluded) {
12168:                 foreach my $id (sort(@possexcluded)) {
12169:                     if ($serverhomes{$id}) {
12170:                         push(@excluded,$id);
12171:                     }
12172:                 }
12173:             }
12174:             if (@excluded) {
12175:                 $contacts_hash{'contacts'}{'lonstatus'}{$item} = \@excluded;
12176:             }
12177:         } elsif ($item eq 'weights') {
12178:             foreach my $type ('E','W','N','U') {
12179:                 $env{'form.error'.$item.'_'.$type} =~ s/^\s+|\s+$//g;
12180:                 if ($env{'form.error'.$item.'_'.$type} =~ /^\d+$/) {
12181:                     unless ($env{'form.error'.$item.'_'.$type} == $lonstatus_defs->{$type}) {
12182:                         $contacts_hash{'contacts'}{'lonstatus'}{$item}{$type} =
12183:                             $env{'form.error'.$item.'_'.$type};
12184:                     }
12185:                 }
12186:             }
12187:         } elsif (($item eq 'threshold') || ($item eq 'sysmail')) {
12188:             $env{'form.error'.$item} =~ s/^\s+|\s+$//g;
12189:             if ($env{'form.error'.$item} =~ /^\d+$/) {
12190:                 unless ($env{'form.error'.$item} == $lonstatus_defs->{$item}) {
12191:                     $contacts_hash{'contacts'}{'lonstatus'}{$item} = $env{'form.error'.$item};
12192:                 }
12193:             }
12194:         }
12195:     }
12196:     if ((ref($fields) eq 'ARRAY') && (ref($possoptions) eq 'HASH')) {
12197:         foreach my $field (@{$fields}) {
12198:             if (ref($possoptions->{$field}) eq 'ARRAY') {
12199:                 my $value = $env{'form.helpform_'.$field};
12200:                 $value =~ s/^\s+|\s+$//g;
12201:                 if (grep(/^\Q$value\E$/,@{$possoptions->{$field}})) {
12202:                     $contacts_hash{'contacts'}{'helpform'}{$field} = $value;
12203:                     if ($field eq 'screenshot') {
12204:                         $env{'form.helpform_maxsize'} =~ s/^\s+|\s+$//g;
12205:                         if ($env{'form.helpform_maxsize'} =~ /^\d+\.?\d*$/) {
12206:                             $contacts_hash{'contacts'}{'helpform'}{'maxsize'} = $env{'form.helpform_maxsize'};
12207:                         }
12208:                     }
12209:                 }
12210:             }
12211:         }
12212:     }
12213:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
12214:     my (@statuses,%usertypeshash,@overrides);
12215:     if ((ref($types) eq 'ARRAY') && (@{$types} > 0)) {
12216:         @statuses = @{$types};
12217:         if (ref($usertypes) eq 'HASH') {
12218:             %usertypeshash = %{$usertypes};
12219:         }
12220:     }
12221:     if (@statuses) {
12222:         my @possoverrides = &Apache::loncommon::get_env_multiple('form.overrides');
12223:         foreach my $type (@possoverrides) {
12224:             if (($type ne '') && (grep(/^\Q$type\E$/,@statuses))) {
12225:                 push(@overrides,$type);
12226:             }
12227:         }
12228:         if (@overrides) {
12229:             foreach my $type (@overrides) {
12230:                 my @standard = &Apache::loncommon::get_env_multiple('form.override_'.$type);
12231:                 foreach my $item (@contacts) {
12232:                     if (grep(/^\Q$item\E$/,@standard)) {
12233:                         $contacts_hash{'contacts'}{'overrides'}{$type}{$item} = 1;
12234:                         $newsetting{'override_'.$type}{$item} = 1;
12235:                     } else {
12236:                         $contacts_hash{'contacts'}{'overrides'}{$type}{$item} = 0;
12237:                         $newsetting{'override_'.$type}{$item} = 0;
12238:                     }
12239:                 }
12240:                 $contacts_hash{'contacts'}{'overrides'}{$type}{'others'} = $env{'form.override_'.$type.'_others'};
12241:                 $contacts_hash{'contacts'}{'overrides'}{$type}{'bcc'} = $env{'form.override_'.$type.'_bcc'};
12242:                 $newsetting{'override_'.$type}{'others'} = $env{'form.override_'.$type.'_others'};
12243:                 $newsetting{'override_'.$type}{'bcc'} = $env{'form.override_'.$type.'_bcc'};
12244:                 if (($env{'form.override_'.$type.'_includestr'} ne '') && ($env{'form.override_'.$type.'_includeloc'} =~ /^s|b$/)) {
12245:                     $includestr{$type} = $env{'form.override_'.$type.'_includestr'};
12246:                     $includeloc{$type} = $env{'form.override_'.$type.'_includeloc'};
12247:                     $contacts_hash{'contacts'}{'overrides'}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
12248:                     $newsetting{'override_'.$type}{'include'} = $contacts_hash{'contacts'}{'overrides'}{$type}{'include'};
12249:                 }
12250:             }    
12251:         }
12252:     }
12253:     if (keys(%currsetting) > 0) {
12254:         foreach my $item (@contacts) {
12255:             if ($to{$item} ne $currsetting{$item}) {
12256:                 $changes{$item} = 1;
12257:             }
12258:         }
12259:         foreach my $type (@mailings) {
12260:             foreach my $item (@contacts) {
12261:                 if (ref($currsetting{$type}) eq 'HASH') {
12262:                     if ($currsetting{$type}{$item} ne $contacts_hash{contacts}{$type}{$item}) {
12263:                         push(@{$changes{$type}},$item);
12264:                     }
12265:                 } else {
12266:                     push(@{$changes{$type}},@{$newsetting{$type}});
12267:                 }
12268:             }
12269:             if ($others{$type} ne $currsetting{$type}{'others'}) {
12270:                 push(@{$changes{$type}},'others');
12271:             }
12272:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
12273:                 if ($bcc{$type} ne $currsetting{$type}{'bcc'}) {
12274:                     push(@{$changes{$type}},'bcc'); 
12275:                 }
12276:                 my ($currloc,$currstr) = split(/:/,$currsetting{$type}{'include'},2);
12277:                 if (($includeloc{$type} ne $currloc) || (&escape($includestr{$type}) ne $currstr)) {
12278:                     push(@{$changes{$type}},'include');
12279:                 }
12280:             }
12281:         }
12282:         if (ref($fields) eq 'ARRAY') {
12283:             if (ref($currsetting{'helpform'}) eq 'HASH') {
12284:                 foreach my $field (@{$fields}) {
12285:                     if ($currsetting{'helpform'}{$field} ne $contacts_hash{'contacts'}{'helpform'}{$field}) {
12286:                         push(@{$changes{'helpform'}},$field);
12287:                     }
12288:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
12289:                         if ($currsetting{'helpform'}{'maxsize'} ne $contacts_hash{'contacts'}{'helpform'}{'maxsize'}) {
12290:                             push(@{$changes{'helpform'}},'maxsize');
12291:                         }
12292:                     }
12293:                 }
12294:             } else {
12295:                 foreach my $field (@{$fields}) {
12296:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
12297:                         push(@{$changes{'helpform'}},$field);
12298:                     }
12299:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
12300:                         if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
12301:                             push(@{$changes{'helpform'}},'maxsize');
12302:                         }
12303:                     }
12304:                 }
12305:             }
12306:         }
12307:         if (@statuses) {
12308:             if (ref($currsetting{'overrides'}) eq 'HASH') {
12309:                 foreach my $key (keys(%{$currsetting{'overrides'}})) {
12310:                     if (ref($currsetting{'overrides'}{$key}) eq 'HASH') {
12311:                         if (ref($newsetting{'override_'.$key}) eq 'HASH') {
12312:                             foreach my $item (@contacts,'bcc','others','include') {
12313:                                 if ($currsetting{'overrides'}{$key}{$item} ne $newsetting{'override_'.$key}{$item}) {
12314:                                     push(@{$changes{'overrides'}},$key);
12315:                                     last;
12316:                                 }
12317:                             }
12318:                         } else {
12319:                             push(@{$changes{'overrides'}},$key);
12320:                         }
12321:                     }
12322:                 }
12323:                 foreach my $key (@overrides) {
12324:                     unless (exists($currsetting{'overrides'}{$key})) {
12325:                         push(@{$changes{'overrides'}},$key);
12326:                     }
12327:                 }
12328:             } else {
12329:                 foreach my $key (@overrides) {
12330:                     push(@{$changes{'overrides'}},$key);
12331:                 }
12332:             }
12333:         }
12334:         if (ref($currsetting{'lonstatus'}) eq 'HASH') {
12335:             foreach my $key ('excluded','weights','threshold','sysmail') {
12336:                 if ($key eq 'excluded') {
12337:                     if ((ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') &&
12338:                         (ref($contacts_hash{contacts}{lonstatus}{excluded}) eq 'ARRAY')) {
12339:                         if ((ref($currsetting{'lonstatus'}{$key}) eq 'ARRAY') &&
12340:                             (@{$currsetting{'lonstatus'}{$key}})) {
12341:                             my @diffs =
12342:                                 &Apache::loncommon::compare_arrays($contacts_hash{contacts}{lonstatus}{excluded},
12343:                                                                    $currsetting{'lonstatus'}{$key});
12344:                             if (@diffs) {
12345:                                 push(@{$changes{'lonstatus'}},$key);
12346:                             }
12347:                         } elsif (@{$contacts_hash{contacts}{lonstatus}{excluded}}) {
12348:                             push(@{$changes{'lonstatus'}},$key);
12349:                         }
12350:                     } elsif ((ref($currsetting{'lonstatus'}{$key}) eq 'ARRAY') &&
12351:                              (@{$currsetting{'lonstatus'}{$key}})) {
12352:                         push(@{$changes{'lonstatus'}},$key);
12353:                     }
12354:                 } elsif ($key eq 'weights') {
12355:                     if ((ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') &&
12356:                         (ref($contacts_hash{contacts}{lonstatus}{$key}) eq 'HASH')) {
12357:                         if (ref($currsetting{'lonstatus'}{$key}) eq 'HASH') {
12358:                             foreach my $type ('E','W','N','U') {
12359:                                 unless ($contacts_hash{contacts}{lonstatus}{$key}{$type} eq
12360:                                         $currsetting{'lonstatus'}{$key}{$type}) {
12361:                                     push(@{$changes{'lonstatus'}},$key);
12362:                                     last;
12363:                                 }
12364:                             }
12365:                         } else {
12366:                             foreach my $type ('E','W','N','U') {
12367:                                 if ($contacts_hash{contacts}{lonstatus}{$key}{$type} ne '') {
12368:                                     push(@{$changes{'lonstatus'}},$key);
12369:                                     last;
12370:                                 }
12371:                             }
12372:                         }
12373:                     } elsif (ref($currsetting{'lonstatus'}{$key}) eq 'HASH') {
12374:                         foreach my $type ('E','W','N','U') {
12375:                             if ($currsetting{'lonstatus'}{$key}{$type} ne '') {
12376:                                 push(@{$changes{'lonstatus'}},$key);
12377:                                 last;
12378:                             }
12379:                         }
12380:                     }
12381:                 } elsif (($key eq 'threshold') || ($key eq 'sysmail')) {
12382:                     if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
12383:                         if ($currsetting{'lonstatus'}{$key} =~ /^\d+$/) {
12384:                             if ($currsetting{'lonstatus'}{$key} != $contacts_hash{contacts}{lonstatus}{$key}) {
12385:                                 push(@{$changes{'lonstatus'}},$key);
12386:                             }
12387:                         } elsif ($contacts_hash{contacts}{lonstatus}{$key} =~ /^\d+$/) {
12388:                             push(@{$changes{'lonstatus'}},$key);
12389:                         }
12390:                     } elsif ($currsetting{'lonstatus'}{$key} =~ /^\d+$/) {
12391:                         push(@{$changes{'lonstatus'}},$key);
12392:                     }
12393:                 }
12394:             }
12395:         } else {
12396:             if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
12397:                 foreach my $key ('excluded','weights','threshold','sysmail') {
12398:                     if (exists($contacts_hash{contacts}{lonstatus}{$key})) {
12399:                         push(@{$changes{'lonstatus'}},$key);
12400:                     }
12401:                 }
12402:             }
12403:         }
12404:     } else {
12405:         my %default;
12406:         $default{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
12407:         $default{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
12408:         $default{'errormail'} = 'adminemail';
12409:         $default{'packagesmail'} = 'adminemail';
12410:         $default{'helpdeskmail'} = 'supportemail';
12411:         $default{'otherdomsmail'} = 'supportemail';
12412:         $default{'lonstatusmail'} = 'adminemail';
12413:         $default{'requestsmail'} = 'adminemail';
12414:         $default{'updatesmail'} = 'adminemail';
12415:         $default{'hostipmail'} = 'adminemail';
12416:         foreach my $item (@contacts) {
12417:            if ($to{$item} ne $default{$item}) {
12418:                $changes{$item} = 1;
12419:            }
12420:         }
12421:         foreach my $type (@mailings) {
12422:             if ((@{$newsetting{$type}} != 1) || ($newsetting{$type}[0] ne $default{$type})) {
12423:                 push(@{$changes{$type}},@{$newsetting{$type}});
12424:             }
12425:             if ($others{$type} ne '') {
12426:                 push(@{$changes{$type}},'others');
12427:             }
12428:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
12429:                 if ($bcc{$type} ne '') {
12430:                     push(@{$changes{$type}},'bcc');
12431:                 }
12432:                 if (($includeloc{$type} =~ /^b|s$/) && ($includestr{$type} ne '')) {
12433:                     push(@{$changes{$type}},'include');
12434:                 }
12435:             }
12436:         }
12437:         if (ref($fields) eq 'ARRAY') {
12438:             foreach my $field (@{$fields}) {
12439:                 if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
12440:                     push(@{$changes{'helpform'}},$field);
12441:                 }
12442:                 if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
12443:                     if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
12444:                         push(@{$changes{'helpform'}},'maxsize');
12445:                     }
12446:                 }
12447:             }
12448:         }
12449:         if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
12450:             foreach my $key ('excluded','weights','threshold','sysmail') {
12451:                 if (exists($contacts_hash{contacts}{lonstatus}{$key})) {
12452:                     push(@{$changes{'lonstatus'}},$key);
12453:                 }
12454:             }
12455:         }
12456:     }
12457:     foreach my $item (@toggles) {
12458:         if (($env{'form.'.$item} == 1) && ($currsetting{$item} == 0)) {
12459:             $changes{$item} = 1;
12460:         } elsif ((!$env{'form.'.$item}) &&
12461:                  (($currsetting{$item} eq '') || ($currsetting{$item} == 1))) {
12462:             $changes{$item} = 1;
12463:         }
12464:     }
12465:     my $putresult = &Apache::lonnet::put_dom('configuration',\%contacts_hash,
12466:                                              $dom);
12467:     if ($putresult eq 'ok') {
12468:         if (keys(%changes) > 0) {
12469:             &Apache::loncommon::devalidate_domconfig_cache($dom);
12470:             if (ref($lastactref) eq 'HASH') {
12471:                 $lastactref->{'domainconfig'} = 1;
12472:             }
12473:             my ($titles,$short_titles)  = &contact_titles();
12474:             $resulttext = &mt('Changes made:').'<ul>';
12475:             foreach my $item (@contacts) {
12476:                 if ($changes{$item}) {
12477:                     $resulttext .= '<li>'.$titles->{$item}.
12478:                                     &mt(' set to: ').
12479:                                     '<span class="LC_cusr_emph">'.
12480:                                     $to{$item}.'</span></li>';
12481:                 }
12482:             }
12483:             foreach my $type (@mailings) {
12484:                 if (ref($changes{$type}) eq 'ARRAY') {
12485:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
12486:                         $resulttext .= '<li>'.$titles->{$type}.' -- '.&mt('sent to').': ';
12487:                     } else {
12488:                         $resulttext .= '<li>'.$titles->{$type}.': ';
12489:                     }
12490:                     my @text;
12491:                     foreach my $item (@{$newsetting{$type}}) {
12492:                         push(@text,$short_titles->{$item});
12493:                     }
12494:                     if ($others{$type} ne '') {
12495:                         push(@text,$others{$type});
12496:                     }
12497:                     if (@text) {
12498:                         $resulttext .= '<span class="LC_cusr_emph">'.
12499:                                        join(', ',@text).'</span>';
12500:                     }
12501:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
12502:                         if ($bcc{$type} ne '') {
12503:                             my $bcctext;
12504:                             if (@text) {
12505:                                 $bcctext = '&nbsp;'.&mt('with Bcc to');
12506:                             } else {
12507:                                 $bcctext = '(Bcc)';
12508:                             }
12509:                             $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$bcc{$type}.'</span>';
12510:                         } elsif (!@text) {
12511:                             $resulttext .= &mt('No one');
12512:                         }
12513:                         if ($includestr{$type} ne '') {
12514:                             if ($includeloc{$type} eq 'b') {
12515:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail body:').' '.$includestr{$type};
12516:                             } elsif ($includeloc{$type} eq 's') {
12517:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail subject:').' '.$includestr{$type};
12518:                             }
12519:                         }
12520:                     } elsif (!@text) {
12521:                         $resulttext .= &mt('No recipients');
12522:                     }
12523:                     $resulttext .= '</li>';
12524:                 }
12525:             }
12526:             if (ref($changes{'overrides'}) eq 'ARRAY') {
12527:                 my @deletions;
12528:                 foreach my $type (@{$changes{'overrides'}}) {
12529:                     if ($usertypeshash{$type}) {
12530:                         if (grep(/^\Q$type\E/,@overrides)) {
12531:                             $resulttext .= '<li>'.&mt("Overrides based on requester's affiliation set for [_1]",
12532:                                                       $usertypeshash{$type}).'<ul><li>';
12533:                             if (ref($newsetting{'override_'.$type}) eq 'HASH') {
12534:                                 my @text;
12535:                                 foreach my $item (@contacts) {
12536:                                     if ($newsetting{'override_'.$type}{$item}) {
12537:                                         push(@text,$short_titles->{$item});
12538:                                     }
12539:                                 }
12540:                                 if ($newsetting{'override_'.$type}{'others'} ne '') {
12541:                                     push(@text,$newsetting{'override_'.$type}{'others'});
12542:                                 }
12543: 
12544:                                 if (@text) {
12545:                                     $resulttext .= &mt('Helpdesk e-mail sent to: [_1]',
12546:                                                        '<span class="LC_cusr_emph">'.join(', ',@text).'</span>');
12547:                                 }
12548:                                 if ($newsetting{'override_'.$type}{'bcc'} ne '') {
12549:                                     my $bcctext;
12550:                                     if (@text) {
12551:                                         $bcctext = '&nbsp;'.&mt('with Bcc to');
12552:                                     } else {
12553:                                         $bcctext = '(Bcc)';
12554:                                     }
12555:                                     $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$newsetting{'override_'.$type}{'bcc'}.'</span>';
12556:                                 } elsif (!@text) {
12557:                                      $resulttext .= &mt('Helpdesk e-mail sent to no one');
12558:                                 }
12559:                                 $resulttext .= '</li>';
12560:                                 if ($newsetting{'override_'.$type}{'include'} ne '') {
12561:                                     my ($loc,$str) = split(/:/,$newsetting{'override_'.$type}{'include'});
12562:                                     if ($loc eq 'b') {
12563:                                         $resulttext .= '<li>'.&mt('Text automatically added to e-mail body:').' '.&unescape($str).'</li>';
12564:                                     } elsif ($loc eq 's') {
12565:                                         $resulttext .= '<li>'.&mt('Text automatically added to e-mail subject:').' '.&unescape($str).'</li>';
12566:                                     }
12567:                                 }
12568:                             }
12569:                             $resulttext .= '</li></ul></li>';
12570:                         } else {
12571:                             push(@deletions,$usertypeshash{$type});
12572:                         }
12573:                     }
12574:                 }
12575:                 if (@deletions) {
12576:                     $resulttext .= '<li>'.&mt("Overrides based on requester's affiliation discontinued for: [_1]",
12577:                                               join(', ',@deletions)).'</li>';
12578:                 }
12579:             }
12580:             my @offon = ('off','on');
12581:             my $corelink = &core_link_msu();
12582:             if ($changes{'reporterrors'}) {
12583:                 $resulttext .= '<li>'.
12584:                                &mt('E-mail error reports to [_1] set to "'.
12585:                                    $offon[$env{'form.reporterrors'}].'".',
12586:                                    $corelink).
12587:                                '</li>';
12588:             }
12589:             if ($changes{'reportupdates'}) {
12590:                 $resulttext .= '<li>'.
12591:                                 &mt('E-mail record of completed LON-CAPA updates to [_1] set to "'.
12592:                                     $offon[$env{'form.reportupdates'}].'".',
12593:                                     $corelink).
12594:                                 '</li>';
12595:             }
12596:             if ($changes{'reportstatus'}) {
12597:                 $resulttext .= '<li>'.
12598:                                 &mt('E-mail status if errors above threshold to [_1] set to "'.
12599:                                     $offon[$env{'form.reportstatus'}].'".',
12600:                                     $corelink).
12601:                                 '</li>';
12602:             }
12603:             if (ref($changes{'lonstatus'}) eq 'ARRAY') {
12604:                 $resulttext .= '<li>'.
12605:                                &mt('Nightly status check e-mail settings').':<ul>';
12606:                 my (%defval,%use_def,%shown);
12607:                 $defval{'threshold'} = $lonstatus_defs->{'threshold'};
12608:                 $defval{'sysmail'} = $lonstatus_defs->{'sysmail'};
12609:                 $defval{'weights'} =
12610:                     join(', ',map { $lonstatus_names->{$_}.'='.$lonstatus_defs->{$_}; } ('E','W','N','U'));
12611:                 $defval{'excluded'} = &mt('None');
12612:                 if (ref($contacts_hash{'contacts'}{'lonstatus'}) eq 'HASH') {
12613:                     foreach my $item ('threshold','sysmail','weights','excluded') {
12614:                         if (exists($contacts_hash{'contacts'}{'lonstatus'}{$item})) {
12615:                             if (($item eq 'threshold') || ($item eq 'sysmail')) {
12616:                                 $shown{$item} = $contacts_hash{'contacts'}{'lonstatus'}{$item};
12617:                             } elsif ($item eq 'weights') {
12618:                                 if (ref($contacts_hash{'contacts'}{'lonstatus'}{$item}) eq 'HASH') {
12619:                                     foreach my $type ('E','W','N','U') {
12620:                                         $shown{$item} .= $lonstatus_names->{$type}.'=';
12621:                                         if (exists($contacts_hash{'contacts'}{'lonstatus'}{$item}{$type})) {
12622:                                             $shown{$item} .= $contacts_hash{'contacts'}{'lonstatus'}{$item}{$type};
12623:                                         } else {
12624:                                             $shown{$item} .= $lonstatus_defs->{$type};
12625:                                         }
12626:                                         $shown{$item} .= ', ';
12627:                                     }
12628:                                     $shown{$item} =~ s/, $//;
12629:                                 } else {
12630:                                     $shown{$item} = $defval{$item};
12631:                                 }
12632:                             } elsif ($item eq 'excluded') {
12633:                                 if (ref($contacts_hash{'contacts'}{'lonstatus'}{$item}) eq 'ARRAY') {
12634:                                     $shown{$item} = join(', ',@{$contacts_hash{'contacts'}{'lonstatus'}{$item}});
12635:                                 } else {
12636:                                     $shown{$item} = $defval{$item};
12637:                                 }
12638:                             }
12639:                         } else {
12640:                             $shown{$item} = $defval{$item};
12641:                         }
12642:                     }
12643:                 } else {
12644:                     foreach my $item ('threshold','weights','excluded','sysmail') {
12645:                         $shown{$item} = $defval{$item};
12646:                     }
12647:                 }
12648:                 foreach my $item ('threshold','weights','excluded','sysmail') {
12649:                     $resulttext .= '<li>'.&mt($titles->{'error'.$item}.' -- [_1]',
12650:                                           $shown{$item}).'</li>';
12651:                 }
12652:                 $resulttext .= '</ul></li>';
12653:             }
12654:             if ((ref($changes{'helpform'}) eq 'ARRAY') && (ref($fields) eq 'ARRAY')) {
12655:                 my (@optional,@required,@unused,$maxsizechg);
12656:                 foreach my $field (@{$changes{'helpform'}}) {
12657:                     if ($field eq 'maxsize') {
12658:                         $maxsizechg = 1;
12659:                         next;
12660:                     }
12661:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'yes') {
12662:                         push(@optional,$field);
12663:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'no') {
12664:                         push(@unused,$field);
12665:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'req') {
12666:                         push(@required,$field);
12667:                     }
12668:                 }
12669:                 if (@optional) {
12670:                     $resulttext .= '<li>'.
12671:                                    &mt('Help form fields changed to "Optional": [_1].',
12672:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @optional)).'</span>'.
12673:                                    '</li>';
12674:                 }
12675:                 if (@required) {
12676:                     $resulttext .= '<li>'.
12677:                                    &mt('Help form fields changed to "Required": [_1].',
12678:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @required)).'</span>'.
12679:                                    '</li>';
12680:                 }
12681:                 if (@unused) {
12682:                     $resulttext .= '<li>'.
12683:                                    &mt('Help form fields changed to "Not shown": [_1].',
12684:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @unused)).'</span>'.
12685:                                    '</li>';
12686:                 }
12687:                 if ($maxsizechg) {
12688:                     $resulttext .= '<li>'.
12689:                                    &mt('Max size for file uploaded to help form by logged-in user set to [_1] MB.',
12690:                                        $contacts_hash{'contacts'}{'helpform'}{'maxsize'}).
12691:                                    '</li>';
12692:                 }
12693:             }
12694:             $resulttext .= '</ul>';
12695:         } else {
12696:             $resulttext = &mt('No changes made to contacts and form settings');
12697:         }
12698:     } else {
12699:         $resulttext = '<span class="LC_error">'.
12700:             &mt('An error occurred: [_1].',$putresult).'</span>';
12701:     }
12702:     return $resulttext;
12703: }
12704: 
12705: sub modify_passwords {
12706:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
12707:     my ($resulttext,%current,%changes,%newvalues,@oktypes,$errors,
12708:         $updatedefaults,$updateconf);
12709:     my $customfn = 'resetpw.html';
12710:     if (ref($domconfig{'passwords'}) eq 'HASH') {
12711:         %current = %{$domconfig{'passwords'}};
12712:     }
12713:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
12714:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
12715:     if (ref($types) eq 'ARRAY') {
12716:         @oktypes = @{$types};
12717:     }
12718:     push(@oktypes,'default');
12719: 
12720:     my %titles = &Apache::lonlocal::texthash (
12721:         intauth_cost   => 'Encryption cost for bcrypt (positive integer)',
12722:         intauth_check  => 'Check bcrypt cost if authenticated',
12723:         intauth_switch => 'Existing crypt-based switched to bcrypt on authentication',
12724:         permanent      => 'Permanent e-mail address',
12725:         critical       => 'Critical notification address',
12726:         notify         => 'Notification address',
12727:         min            => 'Minimum password length',
12728:         max            => 'Maximum password length',
12729:         chars          => 'Required characters',
12730:         numsaved       => 'Number of previous passwords to save',
12731:         reset          => 'Resetting Forgotten Password',
12732:         intauth        => 'Encryption of Stored Passwords (Internal Auth)',
12733:         rules          => 'Rules for LON-CAPA Passwords',
12734:         crsownerchg    => 'Course Owner Changing Student Passwords',
12735:         username       => 'Username',
12736:         email          => 'E-mail address',
12737:     );
12738: 
12739: #
12740: # Retrieve current domain configuration for internal authentication from $domconfig{'defaults'}.
12741: #
12742:     my (%curr_defaults,%save_defaults);
12743:     if (ref($domconfig{'defaults'}) eq 'HASH') {
12744:         foreach my $key (keys(%{$domconfig{'defaults'}})) {
12745:             if ($key =~ /^intauth_(cost|check|switch)$/) {
12746:                 $curr_defaults{$key} = $domconfig{'defaults'}{$key};
12747:             } else {
12748:                 $save_defaults{$key} = $domconfig{'defaults'}{$key};
12749:             }
12750:         }
12751:     }
12752:     my %staticdefaults = (
12753:         'resetlink'      => 2,
12754:         'resetcase'      => \@oktypes,
12755:         'resetprelink'   => 'both',
12756:         'resetemail'     => ['critical','notify','permanent'],
12757:         'intauth_cost'   => 10,
12758:         'intauth_check'  => 0,
12759:         'intauth_switch' => 0,
12760:     );
12761:     $staticdefaults{'min'} = $Apache::lonnet::passwdmin;
12762:     foreach my $type (@oktypes) {
12763:         $staticdefaults{'resetpostlink'}{$type} = ['email','username'];
12764:     }
12765:     my $linklife = $env{'form.passwords_link'};
12766:     $linklife =~ s/^\s+|\s+$//g;
12767:     if (($linklife =~ /^\d+(|\.\d*)$/) && ($linklife > 0)) {
12768:         $newvalues{'resetlink'} = $linklife;
12769:         if ($current{'resetlink'}) {
12770:             if ($current{'resetlink'} ne $linklife) {
12771:                 $changes{'reset'} = 1;
12772:             }
12773:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
12774:             if ($staticdefaults{'resetlink'} ne $linklife) {
12775:                 $changes{'reset'} = 1;
12776:             }
12777:         }
12778:     } elsif ($current{'resetlink'}) {
12779:         $changes{'reset'} = 1;
12780:     }
12781:     my @casesens;
12782:     my @posscase = &Apache::loncommon::get_env_multiple('form.passwords_case_sensitive');
12783:     foreach my $case (sort(@posscase)) {
12784:         if (grep(/^\Q$case\E$/,@oktypes)) {
12785:             push(@casesens,$case);
12786:         }
12787:     }
12788:     $newvalues{'resetcase'} = \@casesens;
12789:     if (ref($current{'resetcase'}) eq 'ARRAY') {
12790:         my @diffs = &Apache::loncommon::compare_arrays($current{'resetcase'},\@casesens);
12791:         if (@diffs > 0) {
12792:             $changes{'reset'} = 1;
12793:         }
12794:     } elsif (!ref($domconfig{passwords}) eq 'HASH') {
12795:         my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetcase'},\@casesens);
12796:         if (@diffs > 0) {
12797:             $changes{'reset'} = 1;
12798:         }
12799:     }
12800:     if ($env{'form.passwords_prelink'} =~ /^(both|either)$/) {
12801:         $newvalues{'resetprelink'} = $env{'form.passwords_prelink'};
12802:         if (exists($current{'resetprelink'})) {
12803:             if ($current{'resetprelink'} ne $newvalues{'resetprelink'}) {
12804:                 $changes{'reset'} = 1;
12805:             }
12806:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
12807:             if ($staticdefaults{'resetprelink'} ne $newvalues{'resetprelink'}) {
12808:                 $changes{'reset'} = 1;
12809:             }
12810:         }
12811:     } elsif ($current{'resetprelink'}) {
12812:         $changes{'reset'} = 1;
12813:     }
12814:     foreach my $type (@oktypes) {
12815:         my @possplink = &Apache::loncommon::get_env_multiple('form.passwords_postlink_'.$type);
12816:         my @postlink;
12817:         foreach my $item (sort(@possplink)) {
12818:             if ($item =~ /^(email|username)$/) {
12819:                 push(@postlink,$item);
12820:             }
12821:         }
12822:         $newvalues{'resetpostlink'}{$type} = \@postlink;
12823:         unless ($changes{'reset'}) {
12824:             if (ref($current{'resetpostlink'}) eq 'HASH') {
12825:                 if (ref($current{'resetpostlink'}{$type}) eq 'ARRAY') {
12826:                     my @diffs = &Apache::loncommon::compare_arrays($current{'resetpostlink'}{$type},\@postlink);
12827:                     if (@diffs > 0) {
12828:                         $changes{'reset'} = 1;
12829:                     }
12830:                 } else {
12831:                     $changes{'reset'} = 1;
12832:                 }
12833:             } elsif (!ref($domconfig{passwords}) eq 'HASH') {
12834:                 my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetpostlink'}{$type},\@postlink);
12835:                 if (@diffs > 0) {
12836:                     $changes{'reset'} = 1;
12837:                 }
12838:             }
12839:         }
12840:     }
12841:     my @possemailsrc = &Apache::loncommon::get_env_multiple('form.passwords_emailsrc');
12842:     my @resetemail;
12843:     foreach my $item (sort(@possemailsrc)) {
12844:         if ($item =~ /^(permanent|critical|notify)$/) {
12845:             push(@resetemail,$item);
12846:         }
12847:     }
12848:     $newvalues{'resetemail'} = \@resetemail;
12849:     unless ($changes{'reset'}) {
12850:         if (ref($current{'resetemail'}) eq 'ARRAY') {
12851:             my @diffs = &Apache::loncommon::compare_arrays($current{'resetemail'},\@resetemail);
12852:             if (@diffs > 0) {
12853:                 $changes{'reset'} = 1;
12854:             }
12855:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
12856:             my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetemail'},\@resetemail);
12857:             if (@diffs > 0) {
12858:                 $changes{'reset'} = 1;
12859:             }
12860:         }
12861:     }
12862:     if ($env{'form.passwords_stdtext'} == 0) {
12863:         $newvalues{'resetremove'} = 1;
12864:         unless ($current{'resetremove'}) {
12865:             $changes{'reset'} = 1;
12866:         }
12867:     } elsif ($current{'resetremove'}) {
12868:         $changes{'reset'} = 1;
12869:     }
12870:     if ($env{'form.passwords_customfile.filename'} ne '') {
12871:         my $servadm = $r->dir_config('lonAdmEMail');
12872:         my $servadm = $r->dir_config('lonAdmEMail');
12873:         my ($configuserok,$author_ok,$switchserver) =
12874:             &config_check($dom,$confname,$servadm);
12875:         my $error;
12876:         if ($configuserok eq 'ok') {
12877:             if ($switchserver) {
12878:                 $error = &mt("Upload of file containing domain-specific text is not permitted to this server: [_1]",$switchserver);
12879:             } else {
12880:                 if ($author_ok eq 'ok') {
12881:                     my ($result,$customurl) =
12882:                         &publishlogo($r,'upload','passwords_customfile',$dom,
12883:                                      $confname,'customtext/resetpw','','',$customfn);
12884:                     if ($result eq 'ok') {
12885:                         $newvalues{'resetcustom'} = $customurl;
12886:                         $changes{'reset'} = 1;
12887:                     } else {
12888:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$customfn,$result);
12889:                     }
12890:                 } else {
12891:                     $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);
12892:                 }
12893:             }
12894:         } else {
12895:             $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);
12896:         }
12897:         if ($error) {
12898:             &Apache::lonnet::logthis($error);
12899:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12900:         }
12901:     } elsif ($current{'resetcustom'}) {
12902:         if ($env{'form.passwords_custom_del'}) {
12903:             $changes{'reset'} = 1;
12904:         } else {
12905:             $newvalues{'resetcustom'} = $current{'resetcustom'};
12906:         }
12907:     }
12908:     $env{'form.intauth_cost'} =~ s/^\s+|\s+$//g;
12909:     if (($env{'form.intauth_cost'} ne '') && ($env{'form.intauth_cost'} =~ /^\d+$/)) {
12910:         $save_defaults{'intauth_cost'} = $env{'form.intauth_cost'};
12911:         if ($save_defaults{'intauth_cost'} ne $curr_defaults{'intauth_cost'}) {
12912:             $changes{'intauth'} = 1;
12913:         }
12914:     } else {
12915:         $save_defaults{'intauth_cost'} = $curr_defaults{'intauth_cost'};
12916:     }
12917:     if ($env{'form.intauth_check'} =~ /^(0|1|2)$/) {
12918:         $save_defaults{'intauth_check'} = $env{'form.intauth_check'};
12919:         if ($save_defaults{'intauth_check'} ne $curr_defaults{'intauth_check'}) {
12920:             $changes{'intauth'} = 1;
12921:         }
12922:     } else {
12923:         $save_defaults{'intauth_check'} = $curr_defaults{'intauth_check'};
12924:     }
12925:     if ($env{'form.intauth_switch'} =~ /^(0|1|2)$/) {
12926:         $save_defaults{'intauth_switch'} = $env{'form.intauth_switch'};
12927:         if ($save_defaults{'intauth_switch'} ne $curr_defaults{'intauth_switch'}) {
12928:             $changes{'intauth'} = 1;
12929:         }
12930:     } else {
12931:         $save_defaults{'intauth_check'} = $curr_defaults{'intauth_check'};
12932:     }
12933:     foreach my $item ('cost','check','switch') {
12934:         if ($save_defaults{'intauth_'.$item} ne $domdefaults{'intauth_'.$item}) {
12935:             $domdefaults{'intauth_'.$item} = $save_defaults{'intauth_'.$item};
12936:             $updatedefaults = 1;
12937:         }
12938:     }
12939:     foreach my $rule ('min','max','numsaved') {
12940:         $env{'form.passwords_'.$rule} =~ s/^\s+|\s+$//g;
12941:         my $ruleok;
12942:         if ($rule eq 'min') {
12943:             if ($env{'form.passwords_'.$rule} =~ /^\d+$/) {
12944:                 if ($env{'form.passwords_'.$rule} >= $Apache::lonnet::passwdmin) {
12945:                     $ruleok = 1;
12946:                 }
12947:             }
12948:         } elsif (($env{'form.passwords_'.$rule} =~ /^\d+$/) &&
12949:                  ($env{'form.passwords_'.$rule} ne '0')) {
12950:             $ruleok = 1;
12951:         }
12952:         if ($ruleok) {
12953:             $newvalues{$rule} = $env{'form.passwords_'.$rule};
12954:             if (exists($current{$rule})) {
12955:                 if ($newvalues{$rule} ne $current{$rule}) {
12956:                     $changes{'rules'} = 1;
12957:                 }
12958:             } elsif ($rule eq 'min') {
12959:                 if ($staticdefaults{$rule} ne $newvalues{$rule}) {
12960:                     $changes{'rules'} = 1;
12961:                 }
12962:             } else {
12963:                 $changes{'rules'} = 1;
12964:             }
12965:         } elsif (exists($current{$rule})) {
12966:             $changes{'rules'} = 1;
12967:         }
12968:     }
12969:     my @posschars = &Apache::loncommon::get_env_multiple('form.passwords_chars');
12970:     my @chars;
12971:     foreach my $item (sort(@posschars)) {
12972:         if ($item =~ /^(uc|lc|num|spec)$/) {
12973:             push(@chars,$item);
12974:         }
12975:     }
12976:     $newvalues{'chars'} = \@chars;
12977:     unless ($changes{'rules'}) {
12978:         if (ref($current{'chars'}) eq 'ARRAY') {
12979:             my @diffs = &Apache::loncommon::compare_arrays($current{'chars'},\@chars);
12980:             if (@diffs > 0) {
12981:                 $changes{'rules'} = 1;
12982:             }
12983:         } else {
12984:             if (@chars > 0) {
12985:                 $changes{'rules'} = 1;
12986:             }
12987:         }
12988:     }
12989:     my %crsownerchg = (
12990:                         by => [],
12991:                         for => [],
12992:                       );
12993:     foreach my $item ('by','for') {
12994:         my @posstypes = &Apache::loncommon::get_env_multiple('form.passwords_crsowner_'.$item);
12995:         foreach my $type (sort(@posstypes)) {
12996:             if (grep(/^\Q$type\E$/,@oktypes)) {
12997:                 push(@{$crsownerchg{$item}},$type);
12998:             }
12999:         }
13000:     }
13001:     $newvalues{'crsownerchg'} = \%crsownerchg;
13002:     if (ref($current{'crsownerchg'}) eq 'HASH') {
13003:         foreach my $item ('by','for') {
13004:             if (ref($current{'crsownerchg'}{$item}) eq 'ARRAY') {
13005:                 my @diffs = &Apache::loncommon::compare_arrays($current{'crsownerchg'}{$item},$crsownerchg{$item});
13006:                 if (@diffs > 0) {
13007:                     $changes{'crsownerchg'} = 1;
13008:                     last;
13009:                 }
13010:             }
13011:         }
13012:     } elsif (!(ref($domconfig{passwords}) eq 'HASH')) {
13013:         foreach my $item ('by','for') {
13014:             if (@{$crsownerchg{$item}} > 0) {
13015:                 $changes{'crsownerchg'} = 1;
13016:                 last;
13017:             }
13018:         }
13019:     }
13020: 
13021:     my %confighash = (
13022:                         defaults  => \%save_defaults,
13023:                         passwords => \%newvalues,
13024:                      );
13025:     &process_captcha('passwords',\%changes,$confighash{'passwords'},$domconfig{'passwords'});
13026: 
13027:     my $putresult = &Apache::lonnet::put_dom('configuration',\%confighash,$dom);
13028:     if ($putresult eq 'ok') {
13029:         if (keys(%changes) > 0) {
13030:             $resulttext = &mt('Changes made: ').'<ul>';
13031:             foreach my $key ('reset','intauth','rules','crsownerchg') {
13032:                 if ($changes{$key}) {
13033:                     unless ($key eq 'intauth') {
13034:                         $updateconf = 1;
13035:                     }
13036:                     $resulttext .= '<li>'.$titles{$key}.':<ul>';
13037:                     if ($key eq 'reset') {
13038:                         if ($confighash{'passwords'}{'captcha'} eq 'original') {
13039:                             $resulttext .= '<li>'.&mt('CAPTCHA validation set to use: original CAPTCHA').'</li>';
13040:                         } elsif ($confighash{'passwords'}{'captcha'} eq 'recaptcha') {
13041:                             $resulttext .= '<li>'.&mt('CAPTCHA validation set to use: reCAPTCHA').' '.
13042:                                            &mt('version: [_1]',$confighash{'passwords'}{'recaptchaversion'}).'<br />';
13043:                             if (ref($confighash{'passwords'}{'recaptchakeys'}) eq 'HASH') {
13044:                                 $resulttext .= &mt('Public key: [_1]',$confighash{'passwords'}{'recaptchakeys'}{'public'}).'</br>'.
13045:                                                &mt('Private key: [_1]',$confighash{'passwords'}{'recaptchakeys'}{'private'}).'</li>';
13046:                             }
13047:                         } else {
13048:                             $resulttext .= '<li>'.&mt('No CAPTCHA validation').'</li>';
13049:                         }
13050:                         if ($confighash{'passwords'}{'resetlink'}) {
13051:                             $resulttext .= '<li>'.&mt('Reset link expiration set to [quant,_1,hour]',$confighash{'passwords'}{'resetlink'}).'</li>';
13052:                         } else {
13053:                             $resulttext .= '<li>'.&mt('No reset link expiration set.').' '.
13054:                                                   &mt('Will default to 2 hours').'</li>';
13055:                         }
13056:                         if (ref($confighash{'passwords'}{'resetcase'}) eq 'ARRAY') {
13057:                             if (@{$confighash{'passwords'}{'resetcase'}} == 0) {
13058:                                 $resulttext .= '<li>'.&mt('User input for username and/or e-mail address not case sensitive for "Forgot Password" web form').'</li>';
13059:                             } else {
13060:                                 my $casesens;
13061:                                 foreach my $type (@{$confighash{'passwords'}{'resetcase'}}) {
13062:                                     if ($type eq 'default') {
13063:                                         $casesens .= $othertitle.', ';
13064:                                     } elsif ($usertypes->{$type} ne '') {
13065:                                         $casesens .= $usertypes->{$type}.', ';
13066:                                     }
13067:                                 }
13068:                                 $casesens =~ s/\Q, \E$//;
13069:                                 $resulttext .= '<li>'.&mt('"Forgot Password" web form input for username and/or e-mail address is case-sensitive for: [_1]',$casesens).'</li>';
13070:                             }
13071:                         } else {
13072:                             $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>';
13073:                         }
13074:                         if ($confighash{'passwords'}{'resetprelink'} eq 'either') {
13075:                             $resulttext .= '<li>'.&mt('Users can enter either a username or an e-mail address in "Forgot Password" web form').'</li>';
13076:                         } else {
13077:                             $resulttext .= '<li>'.&mt('Users can enter both a username and an e-mail address in "Forgot Password" web form').'</li>';
13078:                         }
13079:                         if (ref($confighash{'passwords'}{'resetpostlink'}) eq 'HASH') {
13080:                             my $output;
13081:                             if (ref($types) eq 'ARRAY') {
13082:                                 foreach my $type (@{$types}) {
13083:                                     if (ref($confighash{'passwords'}{'resetpostlink'}{$type}) eq 'ARRAY') {
13084:                                         if (@{$confighash{'passwords'}{'resetpostlink'}{$type}} == 0) {
13085:                                             $output .= $usertypes->{$type}.' -- '.&mt('none');
13086:                                         } else {
13087:                                             $output .= $usertypes->{$type}.' -- '.
13088:                                                        join(', ',map { $titles{$_}; } (@{$confighash{'passwords'}{'resetpostlink'}{$type}})).'; ';
13089:                                         }
13090:                                     }
13091:                                 }
13092:                             }
13093:                             if (ref($confighash{'passwords'}{'resetpostlink'}{'default'}) eq 'ARRAY') {
13094:                                 if (@{$confighash{'passwords'}{'resetpostlink'}{'default'}} == 0) {
13095:                                     $output .= $othertitle.' -- '.&mt('none');
13096:                                 } else {
13097:                                     $output .= $othertitle.' -- '.
13098:                                                join(', ',map { $titles{$_}; } (@{$confighash{'passwords'}{'resetpostlink'}{'default'}}));
13099:                                 }
13100:                             }
13101:                             if ($output) {
13102:                                 $resulttext .= '<li>'.&mt('Information required for new password form (by user type) set to: [_1]',$output).'</li>';
13103:                             } else {
13104:                                 $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>';
13105:                             }
13106:                         } else {
13107:                             $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>';
13108:                         }
13109:                         if (ref($confighash{'passwords'}{'resetemail'}) eq 'ARRAY') {
13110:                             if (@{$confighash{'passwords'}{'resetemail'}} > 0) {
13111:                                 $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$confighash{'passwords'}{'resetemail'}})).'</li>';
13112:                             } else {
13113:                                 $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$staticdefaults{'resetemail'}})).'</li>';
13114:                             }
13115:                         } else {
13116:                             $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$staticdefaults{'resetemail'}})).'</li>';
13117:                         }
13118:                         if ($confighash{'passwords'}{'resetremove'}) {
13119:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" web form not shown').'</li>';
13120:                         } else {
13121:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" web form is shown').'</li>';
13122:                         }
13123:                         if ($confighash{'passwords'}{'resetcustom'}) {
13124:                             my $customlink = &Apache::loncommon::modal_link($confighash{'passwords'}{'resetcustom'},
13125:                                                                             &mt('custom text'),600,500,undef,undef,
13126:                                                                             undef,undef,'background-color:#ffffff');
13127:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" form includes: [_1]',$customlink).'</li>';
13128:                         } else {
13129:                             $resulttext .= '<li>'.&mt('No custom text included in preamble to "Forgot Password" form').'</li>';
13130:                         }
13131:                     } elsif ($key eq 'intauth') {
13132:                         foreach my $item ('cost','switch','check') {
13133:                             my $value = $save_defaults{$key.'_'.$item};
13134:                             if ($item eq 'switch') {
13135:                                 my %optiondesc = &Apache::lonlocal::texthash (
13136:                                                      0 => 'No',
13137:                                                      1 => 'Yes',
13138:                                                      2 => 'Yes, and copy existing passwd file to passwd.bak file',
13139:                                                  );
13140:                                 if ($value =~ /^(0|1|2)$/) {
13141:                                     $value = $optiondesc{$value};
13142:                                 } else {
13143:                                     $value = &mt('none -- defaults to No');
13144:                                 }
13145:                             } elsif ($item eq 'check') {
13146:                                 my %optiondesc = &Apache::lonlocal::texthash (
13147:                                                      0 => 'No',
13148:                                                      1 => 'Yes, allow login then update passwd file using default cost (if higher)',
13149:                                                      2 => 'Yes, disallow login if stored cost is less than domain default',
13150:                                                  );
13151:                                 if ($value =~ /^(0|1|2)$/) {
13152:                                     $value = $optiondesc{$value};
13153:                                 } else {
13154:                                     $value = &mt('none -- defaults to No');
13155:                                 }
13156:                             }
13157:                             $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$titles{$key.'_'.$item},$value).'</li>';
13158:                         }
13159:                     } elsif ($key eq 'rules') {
13160:                         foreach my $rule ('min','max','numsaved') {
13161:                             if ($confighash{'passwords'}{$rule} eq '') {
13162:                                 if ($rule eq 'min') {
13163:                                     $resulttext .= '<li>'.&mt('[_1] not set.',$titles{$rule});
13164:                                                    ' '.&mt('Default of [_1] will be used',
13165:                                                            $Apache::lonnet::passwdmin).'</li>';
13166:                                 } else {
13167:                                     $resulttext .= '<li>'.&mt('[_1] set to none',$titles{$rule}).'</li>';
13168:                                 }
13169:                             } else {
13170:                                 $resulttext .= '<li>'.&mt('[_1] set to [_2]',$titles{$rule},$confighash{'passwords'}{$rule}).'</li>';
13171:                             }
13172:                         }
13173:                         if (ref($confighash{'passwords'}{'chars'}) eq 'ARRAY') {
13174:                             if (@{$confighash{'passwords'}{'chars'}} > 0) {
13175:                                 my %rulenames = &Apache::lonlocal::texthash(
13176:                                                      uc => 'At least one upper case letter',
13177:                                                      lc => 'At least one lower case letter',
13178:                                                      num => 'At least one number',
13179:                                                      spec => 'At least one non-alphanumeric',
13180:                                                    );
13181:                                 my $needed = '<ul><li>'.
13182:                                              join('</li><li>',map {$rulenames{$_} } @{$confighash{'passwords'}{'chars'}}).
13183:                                              '</li></ul>';
13184:                                 $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$titles{'chars'},$needed).'</li>';
13185:                             } else {
13186:                                 $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
13187:                             }
13188:                         } else {
13189:                             $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
13190:                         }
13191:                     } elsif ($key eq 'crsownerchg') {
13192:                         if (ref($confighash{'passwords'}{'crsownerchg'}) eq 'HASH') {
13193:                             if ((@{$confighash{'passwords'}{'crsownerchg'}{'by'}} == 0) ||
13194:                                 (@{$confighash{'passwords'}{'crsownerchg'}{'for'}} == 0)) {
13195:                                 $resulttext .= '<li>'.&mt('Course owner may not change student passwords.').'</li>';
13196:                             } else {
13197:                                 my %crsownerstr;
13198:                                 foreach my $item ('by','for') {
13199:                                     if (ref($confighash{'passwords'}{'crsownerchg'}{$item}) eq 'ARRAY') {
13200:                                         foreach my $type (@{$confighash{'passwords'}{'crsownerchg'}{$item}}) {
13201:                                             if ($type eq 'default') {
13202:                                                 $crsownerstr{$item} .= $othertitle.', ';
13203:                                             } elsif ($usertypes->{$type} ne '') {
13204:                                                 $crsownerstr{$item} .= $usertypes->{$type}.', ';
13205:                                             }
13206:                                         }
13207:                                         $crsownerstr{$item} =~ s/\Q, \E$//;
13208:                                     }
13209:                                 }
13210:                                 $resulttext .= '<li>'.&mt('Course owner (with status: [_1]) may change passwords for students (with status: [_2]).',
13211:                                            $crsownerstr{'by'},$crsownerstr{'for'}).'</li>';
13212:                             }
13213:                         } else {
13214:                             $resulttext .= '<li>'.&mt('Course owner may not change student passwords.').'</li>';
13215:                         }
13216:                     }
13217:                     $resulttext .= '</ul></li>';
13218:                 }
13219:             }
13220:             $resulttext .= '</ul>';
13221:         } else {
13222:             $resulttext = &mt('No changes made to password settings');
13223:         }
13224:         my $cachetime = 24*60*60;
13225:         if ($updatedefaults) {
13226:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
13227:             if (ref($lastactref) eq 'HASH') {
13228:                 $lastactref->{'domdefaults'} = 1;
13229:             }
13230:         }
13231:         if ($updateconf) {
13232:             &Apache::lonnet::do_cache_new('passwdconf',$dom,$confighash{'passwords'},$cachetime);
13233:             if (ref($lastactref) eq 'HASH') {
13234:                 $lastactref->{'passwdconf'} = 1;
13235:             }
13236:         }
13237:     } else {
13238:         $resulttext = '<span class="LC_error">'.
13239:             &mt('An error occurred: [_1]',$putresult).'</span>';
13240:     }
13241:     if ($errors) {
13242:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
13243:                        $errors.'</ul></p>';
13244:     }
13245:     return $resulttext;
13246: }
13247: 
13248: sub modify_usercreation {
13249:     my ($dom,%domconfig) = @_;
13250:     my ($resulttext,%curr_usercreation,%changes,%authallowed,%cancreate,%save_usercreate);
13251:     my $warningmsg;
13252:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
13253:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
13254:             if ($key eq 'cancreate') {
13255:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
13256:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
13257:                         if (($item eq 'requestcrs') || ($item eq 'course') || ($item eq 'author')) {
13258:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
13259:                         } else {
13260:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
13261:                         }
13262:                     }
13263:                 }
13264:             } elsif ($key eq 'email_rule') {
13265:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
13266:             } else {
13267:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
13268:             }
13269:         }
13270:     }
13271:     my @username_rule = &Apache::loncommon::get_env_multiple('form.username_rule');
13272:     my @id_rule = &Apache::loncommon::get_env_multiple('form.id_rule');
13273:     my @contexts = ('author','course','requestcrs');
13274:     foreach my $item(@contexts) {
13275:         $cancreate{$item} = $env{'form.can_createuser_'.$item};
13276:     }
13277:     if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
13278:         foreach my $item (@contexts) {
13279:             if ($curr_usercreation{'cancreate'}{$item} ne $cancreate{$item}) {
13280:                 push(@{$changes{'cancreate'}},$item);
13281:             }
13282:         }
13283:     } elsif (ref($curr_usercreation{'cancreate'}) eq 'ARRAY') {
13284:         foreach my $item (@contexts) {
13285:             if (!grep(/^\Q$item\E$/,@{$curr_usercreation{'cancreate'}})) {
13286:                 if ($cancreate{$item} ne 'any') {
13287:                     push(@{$changes{'cancreate'}},$item);
13288:                 }
13289:             } else {
13290:                 if ($cancreate{$item} ne 'none') {
13291:                     push(@{$changes{'cancreate'}},$item);
13292:                 }
13293:             }
13294:         }
13295:     } else {
13296:         foreach my $item (@contexts)  {
13297:             push(@{$changes{'cancreate'}},$item);
13298:         }
13299:     }
13300: 
13301:     if (ref($curr_usercreation{'username_rule'}) eq 'ARRAY') {
13302:         foreach my $type (@{$curr_usercreation{'username_rule'}}) {
13303:             if (!grep(/^\Q$type\E$/,@username_rule)) {
13304:                 push(@{$changes{'username_rule'}},$type);
13305:             }
13306:         }
13307:         foreach my $type (@username_rule) {
13308:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'username_rule'}})) {
13309:                 push(@{$changes{'username_rule'}},$type);
13310:             }
13311:         }
13312:     } else {
13313:         push(@{$changes{'username_rule'}},@username_rule);
13314:     }
13315: 
13316:     if (ref($curr_usercreation{'id_rule'}) eq 'ARRAY') {
13317:         foreach my $type (@{$curr_usercreation{'id_rule'}}) {
13318:             if (!grep(/^\Q$type\E$/,@id_rule)) {
13319:                 push(@{$changes{'id_rule'}},$type);
13320:             }
13321:         }
13322:         foreach my $type (@id_rule) {
13323:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'id_rule'}})) {
13324:                 push(@{$changes{'id_rule'}},$type);
13325:             }
13326:         }
13327:     } else {
13328:         push(@{$changes{'id_rule'}},@id_rule);
13329:     }
13330: 
13331:     my @authen_contexts = ('author','course','domain');
13332:     my @authtypes = ('int','krb4','krb5','loc');
13333:     my %authhash;
13334:     foreach my $item (@authen_contexts) {
13335:         my @authallowed =  &Apache::loncommon::get_env_multiple('form.'.$item.'_auth');
13336:         foreach my $auth (@authtypes) {
13337:             if (grep(/^\Q$auth\E$/,@authallowed)) {
13338:                 $authhash{$item}{$auth} = 1;
13339:             } else {
13340:                 $authhash{$item}{$auth} = 0;
13341:             }
13342:         }
13343:     }
13344:     if (ref($curr_usercreation{'authtypes'}) eq 'HASH') {
13345:         foreach my $item (@authen_contexts) {
13346:             if (ref($curr_usercreation{'authtypes'}{$item}) eq 'HASH') {
13347:                 foreach my $auth (@authtypes) {
13348:                     if ($authhash{$item}{$auth} ne $curr_usercreation{'authtypes'}{$item}{$auth}) {
13349:                         push(@{$changes{'authtypes'}},$item);
13350:                         last;
13351:                     }
13352:                 }
13353:             }
13354:         }
13355:     } else {
13356:         foreach my $item (@authen_contexts) {
13357:             push(@{$changes{'authtypes'}},$item);
13358:         }
13359:     }
13360: 
13361:     $save_usercreate{'cancreate'}{'course'} = $cancreate{'course'}; 
13362:     $save_usercreate{'cancreate'}{'author'} = $cancreate{'author'};
13363:     $save_usercreate{'cancreate'}{'requestcrs'} = $cancreate{'requestcrs'};
13364:     $save_usercreate{'id_rule'} = \@id_rule;
13365:     $save_usercreate{'username_rule'} = \@username_rule,
13366:     $save_usercreate{'authtypes'} = \%authhash;
13367: 
13368:     my %usercreation_hash =  (
13369:         usercreation     => \%save_usercreate,
13370:     );
13371: 
13372:     my $putresult = &Apache::lonnet::put_dom('configuration',\%usercreation_hash,
13373:                                              $dom);
13374: 
13375:     if ($putresult eq 'ok') {
13376:         if (keys(%changes) > 0) {
13377:             $resulttext = &mt('Changes made:').'<ul>';
13378:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
13379:                 my %lt = &usercreation_types();
13380:                 foreach my $type (@{$changes{'cancreate'}}) {
13381:                     my $chgtext = $lt{$type}.', ';
13382:                     if ($cancreate{$type} eq 'none') {
13383:                         $chgtext .= &mt('creation of new users is not permitted, except by a Domain Coordinator.');
13384:                     } elsif ($cancreate{$type} eq 'any') {
13385:                         $chgtext .= &mt('creation of new users is permitted for both institutional and non-institutional usernames.');
13386:                     } elsif ($cancreate{$type} eq 'official') {
13387:                         $chgtext .= &mt('creation of new users is only permitted for institutional usernames.');
13388:                     } elsif ($cancreate{$type} eq 'unofficial') {
13389:                         $chgtext .= &mt('creation of new users is only permitted for non-institutional usernames.');
13390:                     }
13391:                     $resulttext .= '<li>'.$chgtext.'</li>';
13392:                 }
13393:             }
13394:             if (ref($changes{'username_rule'}) eq 'ARRAY') {
13395:                 my ($rules,$ruleorder) = 
13396:                     &Apache::lonnet::inst_userrules($dom,'username');
13397:                 my $chgtext = '<ul>';
13398:                 foreach my $type (@username_rule) {
13399:                     if (ref($rules->{$type}) eq 'HASH') {
13400:                         $chgtext .= '<li>'.$rules->{$type}{'name'}.'</li>';
13401:                     }
13402:                 }
13403:                 $chgtext .= '</ul>';
13404:                 if (@username_rule > 0) {
13405:                     $resulttext .= '<li>'.&mt('Usernames with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';     
13406:                 } else {
13407:                     $resulttext .= '<li>'.&mt('There are now no username formats restricted to verified users in the institutional directory.').'</li>'; 
13408:                 }
13409:             }
13410:             if (ref($changes{'id_rule'}) eq 'ARRAY') {
13411:                 my ($idrules,$idruleorder) = 
13412:                     &Apache::lonnet::inst_userrules($dom,'id');
13413:                 my $chgtext = '<ul>';
13414:                 foreach my $type (@id_rule) {
13415:                     if (ref($idrules->{$type}) eq 'HASH') {
13416:                         $chgtext .= '<li>'.$idrules->{$type}{'name'}.'</li>';
13417:                     }
13418:                 }
13419:                 $chgtext .= '</ul>';
13420:                 if (@id_rule > 0) {
13421:                     $resulttext .= '<li>'.&mt('IDs with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';
13422:                 } else {
13423:                     $resulttext .= '<li>'.&mt('There are now no ID formats restricted to verified users in the institutional directory.').'</li>';
13424:                 }
13425:             }
13426:             my %authname = &authtype_names();
13427:             my %context_title = &context_names();
13428:             if (ref($changes{'authtypes'}) eq 'ARRAY') {
13429:                 my $chgtext = '<ul>';
13430:                 foreach my $type (@{$changes{'authtypes'}}) {
13431:                     my @allowed;
13432:                     $chgtext .= '<li><span class="LC_cusr_emph">'.$context_title{$type}.'</span> - '.&mt('assignable authentication types: ');
13433:                     foreach my $auth (@authtypes) {
13434:                         if ($authhash{$type}{$auth}) {
13435:                             push(@allowed,$authname{$auth});
13436:                         }
13437:                     }
13438:                     if (@allowed > 0) {
13439:                         $chgtext .= join(', ',@allowed).'</li>';
13440:                     } else {
13441:                         $chgtext .= &mt('none').'</li>';
13442:                     }
13443:                 }
13444:                 $chgtext .= '</ul>';
13445:                 $resulttext .= '<li>'.&mt('Authentication types available for assignment to new users').'<br />'.$chgtext;
13446:                 $resulttext .= '</li>';
13447:             }
13448:             $resulttext .= '</ul>';
13449:         } else {
13450:             $resulttext = &mt('No changes made to user creation settings');
13451:         }
13452:     } else {
13453:         $resulttext = '<span class="LC_error">'.
13454:             &mt('An error occurred: [_1]',$putresult).'</span>';
13455:     }
13456:     if ($warningmsg ne '') {
13457:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
13458:     }
13459:     return $resulttext;
13460: }
13461: 
13462: sub modify_selfcreation {
13463:     my ($dom,$lastactref,%domconfig) = @_;
13464:     my ($resulttext,$warningmsg,%curr_usercreation,%curr_usermodify,%curr_inststatus,%changes,%cancreate);
13465:     my (%save_usercreate,%save_usermodify,%save_inststatus,@types,%usertypes);
13466:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
13467:     my ($othertitle,$usertypesref,$typesref) = &Apache::loncommon::sorted_inst_types($dom);
13468:     if (ref($typesref) eq 'ARRAY') {
13469:         @types = @{$typesref};
13470:     }
13471:     if (ref($usertypesref) eq 'HASH') {
13472:         %usertypes = %{$usertypesref};
13473:     }
13474:     $usertypes{'default'} = $othertitle;
13475: #
13476: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usercreation'}.
13477: #
13478:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
13479:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
13480:             if ($key eq 'cancreate') {
13481:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
13482:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
13483:                         if (($item eq 'selfcreate') || ($item eq 'statustocreate') ||
13484:                             ($item eq 'captcha') || ($item eq 'recaptchakeys') ||
13485:                             ($item eq 'recaptchaversion') || ($item eq 'notify') ||
13486:                             ($item eq 'emailusername') || ($item eq 'shibenv') ||
13487:                             ($item eq 'selfcreateprocessing') || ($item eq 'emailverified') ||
13488:                             ($item eq 'emailoptions') || ($item eq 'emaildomain')) {
13489:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
13490:                         } else {
13491:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
13492:                         }
13493:                     }
13494:                 }
13495:             } elsif ($key eq 'email_rule') {
13496:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
13497:             } else {
13498:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
13499:             }
13500:         }
13501:     }
13502: #
13503: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usermodification'}.
13504: #
13505:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
13506:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
13507:             if ($key eq 'selfcreate') {
13508:                 $curr_usermodify{$key} = $domconfig{'usermodification'}{$key};
13509:             } else {
13510:                 $save_usermodify{$key} = $domconfig{'usermodification'}{$key};
13511:             }
13512:         }
13513:     }
13514: #
13515: # Retrieve current domain configuration for institutional status types from $domconfig{'inststatus'}.
13516: #
13517:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
13518:         foreach my $key (keys(%{$domconfig{'inststatus'}})) {
13519:             if ($key eq 'inststatusguest') {
13520:                 $curr_inststatus{$key} = $domconfig{'inststatus'}{$key};
13521:             } else {
13522:                 $save_inststatus{$key} = $domconfig{'inststatus'}{$key};
13523:             }
13524:         }
13525:     }
13526: 
13527:     my @contexts = ('selfcreate');
13528:     @{$cancreate{'selfcreate'}} = ();
13529:     %{$cancreate{'emailusername'}} = ();
13530:     if (@types) {
13531:         @{$cancreate{'statustocreate'}} = ();
13532:     }
13533:     %{$cancreate{'selfcreateprocessing'}} = ();
13534:     %{$cancreate{'shibenv'}} = ();
13535:     %{$cancreate{'emailverified'}} = ();
13536:     %{$cancreate{'emailoptions'}} = ();
13537:     %{$cancreate{'emaildomain'}} = ();
13538:     my %selfcreatetypes = (
13539:                              sso   => 'users authenticated by institutional single sign on',
13540:                              login => 'users authenticated by institutional log-in',
13541:                              email => 'users verified by e-mail',
13542:                           );
13543: #
13544: # Populate $cancreate{'selfcreate'} array reference with types of user, for which self-creation of user accounts
13545: # is permitted.
13546: #
13547: 
13548:     my ($emailrules,$emailruleorder) = &Apache::lonnet::inst_userrules($dom,'email');
13549: 
13550:     my (@statuses,%email_rule);
13551:     foreach my $item ('login','sso','email') {
13552:         if ($item eq 'email') {
13553:             if ($env{'form.cancreate_email'}) {
13554:                 if (@types) {
13555:                     my @poss_statuses = &Apache::loncommon::get_env_multiple('form.selfassign');
13556:                     foreach my $status (@poss_statuses) {
13557:                         if (grep(/^\Q$status\E$/,(@types,'default'))) {
13558:                             push(@statuses,$status);
13559:                         }
13560:                     }
13561:                     $save_inststatus{'inststatusguest'} = \@statuses;
13562:                 } else {
13563:                     push(@statuses,'default');
13564:                 }
13565:                 if (@statuses) {
13566:                     my %curr_rule;
13567:                     if (ref($curr_usercreation{'email_rule'}) eq 'ARRAY') {
13568:                         foreach my $type (@statuses) {
13569:                             $curr_rule{$type} = $curr_usercreation{'email_rule'};
13570:                         }
13571:                     } elsif (ref($curr_usercreation{'email_rule'}) eq 'HASH') {
13572:                         foreach my $type (@statuses) {
13573:                             $curr_rule{$type} = $curr_usercreation{'email_rule'}{$type};
13574:                         }
13575:                     }
13576:                     push(@{$cancreate{'selfcreate'}},'email');
13577:                     push(@contexts,('selfcreateprocessing','emailverified','emailoptions'));
13578:                     my %curremaildom;
13579:                     if (ref($curr_usercreation{'cancreate'}{'emaildomain'}) eq 'HASH') {
13580:                         %curremaildom = %{$curr_usercreation{'cancreate'}{'emaildomain'}};
13581:                     }
13582:                     foreach my $type (@statuses) {
13583:                         if ($env{'form.cancreate_emailprocess_'.$type} =~ /^(?:approval|automatic)$/) {
13584:                             $cancreate{'selfcreateprocessing'}{$type} = $env{'form.cancreate_emailprocess_'.$type};
13585:                         }
13586:                         if ($env{'form.cancreate_usernameoptions_'.$type} =~ /^(?:all|first|free)$/) {
13587:                             $cancreate{'emailverified'}{$type} = $env{'form.cancreate_usernameoptions_'.$type};
13588:                         }
13589:                         if ($env{'form.cancreate_emailoptions_'.$type} =~ /^(any|inst|noninst|custom)$/) {
13590: #
13591: # Retrieve rules (if any) governing types of e-mail address which may be used to verify a username.
13592: #
13593:                             my $chosen = $1;
13594:                             if (($chosen eq 'inst') || ($chosen eq 'noninst')) {
13595:                                 my $emaildom;
13596:                                 if ($env{'form.cancreate_emaildomain_'.$chosen.'_'.$type} =~ /^\@[^\@]+$/) {
13597:                                     $emaildom = $env{'form.cancreate_emaildomain_'.$chosen.'_'.$type};
13598:                                     $cancreate{'emaildomain'}{$type}{$chosen} = $emaildom;
13599:                                     if (ref($curremaildom{$type}) eq 'HASH') {
13600:                                         if (exists($curremaildom{$type}{$chosen})) {
13601:                                             if ($curremaildom{$type}{$chosen} ne $emaildom) {
13602:                                                 push(@{$changes{'cancreate'}},'emaildomain');
13603:                                             }
13604:                                         } elsif ($emaildom ne '') {
13605:                                             push(@{$changes{'cancreate'}},'emaildomain');
13606:                                         }
13607:                                     } elsif ($emaildom ne '') {
13608:                                         push(@{$changes{'cancreate'}},'emaildomain');
13609:                                     }
13610:                                 }
13611:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
13612:                             } elsif ($chosen eq 'custom') {
13613:                                 my @possemail_rules = &Apache::loncommon::get_env_multiple('form.email_rule_'.$type);
13614:                                 $email_rule{$type} = [];
13615:                                 if (ref($emailrules) eq 'HASH') {
13616:                                     foreach my $rule (@possemail_rules) {
13617:                                         if (exists($emailrules->{$rule})) {
13618:                                             push(@{$email_rule{$type}},$rule);
13619:                                         }
13620:                                     }
13621:                                 }
13622:                                 if (@{$email_rule{$type}}) {
13623:                                     $cancreate{'emailoptions'}{$type} = 'custom';
13624:                                     if (ref($curr_rule{$type}) eq 'ARRAY') {
13625:                                         if (@{$curr_rule{$type}} > 0) {
13626:                                             foreach my $rule (@{$curr_rule{$type}}) {
13627:                                                 if (!grep(/^\Q$rule\E$/,@{$email_rule{$type}})) {
13628:                                                     push(@{$changes{'email_rule'}},$type);
13629:                                                 }
13630:                                             }
13631:                                         }
13632:                                         foreach my $type (@{$email_rule{$type}}) {
13633:                                             if (!grep(/^\Q$type\E$/,@{$curr_rule{$type}})) {
13634:                                                 push(@{$changes{'email_rule'}},$type);
13635:                                             }
13636:                                         }
13637:                                     } else {
13638:                                         push(@{$changes{'email_rule'}},$type);
13639:                                     }
13640:                                 }
13641:                             } else {
13642:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
13643:                             }
13644:                         }
13645:                     }
13646:                     if (@types) {
13647:                         if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
13648:                             my @changed = &Apache::loncommon::compare_arrays(\@statuses,$curr_inststatus{'inststatusguest'});
13649:                             if (@changed) {
13650:                                 push(@{$changes{'inststatus'}},'inststatusguest');
13651:                             }
13652:                         } else {
13653:                             push(@{$changes{'inststatus'}},'inststatusguest');
13654:                         }
13655:                     }
13656:                 } else {
13657:                     delete($env{'form.cancreate_email'});
13658:                     if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
13659:                         if (@{$curr_inststatus{'inststatusguest'}} > 0) {
13660:                             push(@{$changes{'inststatus'}},'inststatusguest');
13661:                         }
13662:                     }
13663:                 }
13664:             } else {
13665:                 $save_inststatus{'inststatusguest'} = [];
13666:                 if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
13667:                     if (@{$curr_inststatus{'inststatusguest'}} > 0) {
13668:                         push(@{$changes{'inststatus'}},'inststatusguest');
13669:                     }
13670:                 }
13671:             }
13672:         } else {
13673:             if ($env{'form.cancreate_'.$item}) {
13674:                 push(@{$cancreate{'selfcreate'}},$item);
13675:             }
13676:         }
13677:     }
13678:     my (%userinfo,%savecaptcha);
13679:     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
13680: #
13681: # Populate $cancreate{'emailusername'}{$type} hash ref with information fields (if new user will provide data
13682: # value set to one), if self-creation with e-mail address permitted, where $type is user type: faculty, staff, student etc.
13683: #
13684: 
13685:     if ($env{'form.cancreate_email'}) {
13686:         push(@contexts,'emailusername');
13687:         if (@statuses) {
13688:             foreach my $type (@statuses) {
13689:                 if (ref($infofields) eq 'ARRAY') {
13690:                     foreach my $field (@{$infofields}) {
13691:                         if ($env{'form.canmodify_emailusername_'.$type.'_'.$field} =~ /^(required|optional)$/) {
13692:                             $cancreate{'emailusername'}{$type}{$field} = $1;
13693:                         }
13694:                     }
13695:                 }
13696:             }
13697:         }
13698: #
13699: # Populate $cancreate{'notify'} hash ref with names of Domain Coordinators who are to be notified of
13700: # queued requests for self-creation of account verified by e-mail.
13701: #
13702: 
13703:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.selfcreationnotifyapproval');
13704:         @approvalnotify = sort(@approvalnotify);
13705:         $cancreate{'notify'}{'approval'} = join(',',@approvalnotify);
13706:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
13707:             if (ref($curr_usercreation{'cancreate'}{'notify'}) eq 'HASH') {
13708:                 if ($curr_usercreation{'cancreate'}{'notify'}{'approval'} ne $cancreate{'notify'}{'approval'}) {
13709:                     push(@{$changes{'cancreate'}},'notify');
13710:                 }
13711:             } else {
13712:                 if ($cancreate{'notify'}{'approval'}) {
13713:                     push(@{$changes{'cancreate'}},'notify');
13714:                 }
13715:             }
13716:         } elsif ($cancreate{'notify'}{'approval'}) {
13717:             push(@{$changes{'cancreate'}},'notify');
13718:         }
13719: 
13720:         &process_captcha('cancreate',\%changes,\%savecaptcha,$curr_usercreation{'cancreate'});
13721:     }
13722: #  
13723: # Check if domain default is set appropriately, if self-creation of accounts is to be available for
13724: # institutional log-in.
13725: #
13726:     if (grep(/^login$/,@{$cancreate{'selfcreate'}})) {
13727:         if (!((($domdefaults{'auth_def'} =~/^krb/) && ($domdefaults{'auth_arg_def'} ne '')) || 
13728:                ($domdefaults{'auth_def'} eq 'localauth'))) {
13729:             $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.').' '.
13730:                           &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.');
13731:         }
13732:     }
13733:     my @fields = ('lastname','firstname','middlename','generation',
13734:                   'permanentemail','id');
13735:     my @shibfields = (@fields,'inststatus');
13736:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
13737: #
13738: # Where usernames may created for institutional log-in and/or institutional single sign on:
13739: # (a) populate $cancreate{'statustocreate'} array reference with institutional status types who
13740: # may self-create accounts 
13741: # (b) populate $save_usermodify{'selfcreate'} hash reference with status types, and information fields
13742: # which the user may supply, if institutional data is unavailable.
13743: #
13744:     if (($env{'form.cancreate_login'}) || ($env{'form.cancreate_sso'})) {
13745:         if (@types) {
13746:             @{$cancreate{'statustocreate'}} = &Apache::loncommon::get_env_multiple('form.statustocreate');
13747:             push(@contexts,'statustocreate');
13748:             foreach my $type (@types) {
13749:                 my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$type);
13750:                 foreach my $field (@fields) {
13751:                     if (grep(/^\Q$field\E$/,@modifiable)) {
13752:                         $save_usermodify{'selfcreate'}{$type}{$field} = 1;
13753:                     } else {
13754:                         $save_usermodify{'selfcreate'}{$type}{$field} = 0;
13755:                     }
13756:                 }
13757:             }
13758:             if (ref($curr_usermodify{'selfcreate'}) eq 'HASH') {
13759:                 foreach my $type (@types) {
13760:                     if (ref($curr_usermodify{'selfcreate'}{$type}) eq 'HASH') {
13761:                         foreach my $field (@fields) {
13762:                             if ($save_usermodify{'selfcreate'}{$type}{$field} ne
13763:                                 $curr_usermodify{'selfcreate'}{$type}{$field}) {
13764:                                 push(@{$changes{'selfcreate'}},$type);
13765:                                 last;
13766:                             }
13767:                         }
13768:                     }
13769:                 }
13770:             } else {
13771:                 foreach my $type (@types) {
13772:                     push(@{$changes{'selfcreate'}},$type);
13773:                 }
13774:             }
13775:         }
13776:         foreach my $field (@shibfields) {
13777:             if ($env{'form.shibenv_'.$field} ne '') {
13778:                 $cancreate{'shibenv'}{$field} = $env{'form.shibenv_'.$field};
13779:             }
13780:         }
13781:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
13782:             if (ref($curr_usercreation{'cancreate'}{'shibenv'}) eq 'HASH') {
13783:                 foreach my $field (@shibfields) {
13784:                     if ($env{'form.shibenv_'.$field} ne $curr_usercreation{'cancreate'}{'shibenv'}{$field}) {
13785:                         push(@{$changes{'cancreate'}},'shibenv');
13786:                     }
13787:                 }
13788:             } else {
13789:                 foreach my $field (@shibfields) {
13790:                     if ($env{'form.shibenv_'.$field}) {
13791:                         push(@{$changes{'cancreate'}},'shibenv');
13792:                         last;
13793:                     }
13794:                 }
13795:             }
13796:         }
13797:     }
13798:     foreach my $item (@contexts) {
13799:         if (ref($curr_usercreation{'cancreate'}{$item}) eq 'ARRAY') {
13800:             foreach my $curr (@{$curr_usercreation{'cancreate'}{$item}}) {
13801:                 if (ref($cancreate{$item}) eq 'ARRAY') {
13802:                     if (!grep(/^$curr$/,@{$cancreate{$item}})) {
13803:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
13804:                             push(@{$changes{'cancreate'}},$item);
13805:                         }
13806:                     }
13807:                 }
13808:             }
13809:             if (ref($cancreate{$item}) eq 'ARRAY') {
13810:                 foreach my $type (@{$cancreate{$item}}) {
13811:                     if (!grep(/^$type$/,@{$curr_usercreation{'cancreate'}{$item}})) {
13812:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
13813:                             push(@{$changes{'cancreate'}},$item);
13814:                         }
13815:                     }
13816:                 }
13817:             }
13818:         } elsif (ref($curr_usercreation{'cancreate'}{$item}) eq 'HASH') {
13819:             if (ref($cancreate{$item}) eq 'HASH') {
13820:                 foreach my $type (keys(%{$curr_usercreation{'cancreate'}{$item}})) {
13821:                     if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
13822:                         foreach my $field (keys(%{$curr_usercreation{'cancreate'}{$item}{$type}})) {
13823:                             unless ($curr_usercreation{'cancreate'}{$item}{$type}{$field} eq $cancreate{$item}{$type}{$field}) {
13824:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
13825:                                     push(@{$changes{'cancreate'}},$item);
13826:                                 }
13827:                             }
13828:                         }
13829:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
13830:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
13831:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
13832:                                 push(@{$changes{'cancreate'}},$item);
13833:                             }
13834:                         }
13835:                     }
13836:                 }
13837:                 foreach my $type (keys(%{$cancreate{$item}})) {
13838:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
13839:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
13840:                             if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
13841:                                 unless ($curr_usercreation{'cancreate'}{$item}{$type}{$field} eq $cancreate{$item}{$type}{$field}) {
13842:                                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
13843:                                         push(@{$changes{'cancreate'}},$item);
13844:                                     }
13845:                                 }
13846:                             } else {
13847:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
13848:                                     push(@{$changes{'cancreate'}},$item);
13849:                                 }
13850:                             }
13851:                         }
13852:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
13853:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
13854:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
13855:                                 push(@{$changes{'cancreate'}},$item);
13856:                             }
13857:                         }
13858:                     }
13859:                 }
13860:             }
13861:         } elsif ($curr_usercreation{'cancreate'}{$item}) {
13862:             if (ref($cancreate{$item}) eq 'ARRAY') {
13863:                 if (!grep(/^\Q$curr_usercreation{'cancreate'}{$item}\E$/,@{$cancreate{$item}})) {
13864:                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
13865:                         push(@{$changes{'cancreate'}},$item);
13866:                     }
13867:                 }
13868:             }
13869:         } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
13870:             if (ref($cancreate{$item}) eq 'HASH') {
13871:                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
13872:                     push(@{$changes{'cancreate'}},$item);
13873:                 }
13874:             }
13875:         } elsif ($item eq 'emailusername') {
13876:             if (ref($cancreate{$item}) eq 'HASH') {
13877:                 foreach my $type (keys(%{$cancreate{$item}})) {
13878:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
13879:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
13880:                             if ($cancreate{$item}{$type}{$field}) {
13881:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
13882:                                     push(@{$changes{'cancreate'}},$item);
13883:                                 }
13884:                                 last;
13885:                             }
13886:                         }
13887:                     }
13888:                 }
13889:             }
13890:         }
13891:     }
13892: #
13893: # Populate %save_usercreate hash with updates to self-creation configuration.
13894: #
13895:     $save_usercreate{'cancreate'}{'captcha'} = $savecaptcha{'captcha'};
13896:     $save_usercreate{'cancreate'}{'recaptchakeys'} = $savecaptcha{'recaptchakeys'};
13897:     $save_usercreate{'cancreate'}{'recaptchaversion'} = $savecaptcha{'recaptchaversion'};
13898:     $save_usercreate{'cancreate'}{'selfcreate'} = $cancreate{'selfcreate'};
13899:     if (ref($cancreate{'notify'}) eq 'HASH') {
13900:         $save_usercreate{'cancreate'}{'notify'} = $cancreate{'notify'};
13901:     }
13902:     if (ref($cancreate{'selfcreateprocessing'}) eq 'HASH') {
13903:         $save_usercreate{'cancreate'}{'selfcreateprocessing'} = $cancreate{'selfcreateprocessing'};
13904:     }
13905:     if (ref($cancreate{'emailverified'}) eq 'HASH') {
13906:         $save_usercreate{'cancreate'}{'emailverified'} = $cancreate{'emailverified'};
13907:     }
13908:     if (ref($cancreate{'emailoptions'}) eq 'HASH') {
13909:         $save_usercreate{'cancreate'}{'emailoptions'} = $cancreate{'emailoptions'};
13910:     }
13911:     if (ref($cancreate{'emaildomain'}) eq 'HASH') {
13912:         $save_usercreate{'cancreate'}{'emaildomain'} = $cancreate{'emaildomain'};
13913:     }
13914:     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
13915:         $save_usercreate{'cancreate'}{'statustocreate'} = $cancreate{'statustocreate'};
13916:     }
13917:     if (ref($cancreate{'shibenv'}) eq 'HASH') {
13918:         $save_usercreate{'cancreate'}{'shibenv'} = $cancreate{'shibenv'};
13919:     }
13920:     $save_usercreate{'cancreate'}{'emailusername'} = $cancreate{'emailusername'};
13921:     $save_usercreate{'email_rule'} = \%email_rule;
13922: 
13923:     my %userconfig_hash = (
13924:             usercreation     => \%save_usercreate,
13925:             usermodification => \%save_usermodify,
13926:             inststatus       => \%save_inststatus,
13927:     );
13928: 
13929:     my $putresult = &Apache::lonnet::put_dom('configuration',\%userconfig_hash,
13930:                                              $dom);
13931: #
13932: # Accumulate details of changes to domain configuration for self-creation of usernames in $resulttext
13933: #
13934:     if ($putresult eq 'ok') {
13935:         if (keys(%changes) > 0) {
13936:             $resulttext = &mt('Changes made:').'<ul>';
13937:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
13938:                 my %lt = &selfcreation_types();
13939:                 foreach my $type (@{$changes{'cancreate'}}) {
13940:                     my $chgtext = '';
13941:                     if ($type eq 'selfcreate') {
13942:                         if (@{$cancreate{$type}} == 0) {
13943:                             $chgtext .= &mt('Self creation of a new user account is not permitted.');
13944:                         } else {
13945:                             $chgtext .= &mt('Self-creation of a new account is permitted for:').
13946:                                         '<ul>';
13947:                             foreach my $case (@{$cancreate{$type}}) {
13948:                                 $chgtext .= '<li>'.$selfcreatetypes{$case}.'</li>';
13949:                             }
13950:                             $chgtext .= '</ul>';
13951:                             if (ref($cancreate{$type}) eq 'ARRAY') {
13952:                                 if (grep(/^(login|sso)$/,@{$cancreate{$type}})) {
13953:                                     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
13954:                                         if (@{$cancreate{'statustocreate'}} == 0) {
13955:                                             $chgtext .= '<span class="LC_warning">'.
13956:                                                         &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts via log-in or single sign-on.").
13957:                                                         '</span><br />';
13958:                                         }
13959:                                     }
13960:                                 }
13961:                                 if (grep(/^email$/,@{$cancreate{$type}})) {
13962:                                     if (!@statuses) {
13963:                                         $chgtext .= '<span class="LC_warning">'.
13964:                                                     &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.").
13965:                                                     '</span><br />';
13966: 
13967:                                     }
13968:                                 }
13969:                             }
13970:                         }
13971:                     } elsif ($type eq 'shibenv') {
13972:                         if (keys(%{$cancreate{$type}}) == 0) {
13973:                             $chgtext .= &mt('Shibboleth-autheticated user does not use environment variables to set user information').'<br />'; 
13974:                         } else {
13975:                             $chgtext .= &mt('Shibboleth-autheticated user information set from environment variables, as follows:').
13976:                                         '<ul>';
13977:                             foreach my $field (@shibfields) {
13978:                                 next if ($cancreate{$type}{$field} eq '');
13979:                                 if ($field eq 'inststatus') {
13980:                                     $chgtext .= '<li>'.&mt('Institutional status').' -- '.$cancreate{$type}{$field}.'</li>';
13981:                                 } else {
13982:                                     $chgtext .= '<li>'.$fieldtitles{$field}.' -- '.$cancreate{$type}{$field}.'</li>';
13983:                                 }
13984:                             }
13985:                             $chgtext .= '</ul>';
13986:                         }
13987:                     } elsif ($type eq 'statustocreate') {
13988:                         if ((ref($cancreate{'selfcreate'}) eq 'ARRAY') &&
13989:                             (ref($cancreate{'statustocreate'}) eq 'ARRAY')) {
13990:                             if (@{$cancreate{'selfcreate'}} > 0) {
13991:                                 if (@{$cancreate{'statustocreate'}} == 0) {
13992:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts set to 'None'.");
13993:                                     if (!grep(/^email$/,@{$cancreate{'selfcreate'}})) {
13994:                                         $chgtext .= '<br />'.
13995:                                                     '<span class="LC_warning">'.
13996:                                                     &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts.").
13997:                                                     '</span>';
13998:                                     }
13999:                                 } elsif (keys(%usertypes) > 0) {
14000:                                     if (grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
14001:                                         $chgtext .= &mt('Creation of a new account for an institutional user is restricted to the following institutional affiliation(s):');
14002:                                     } else {
14003:                                         $chgtext .= &mt('Institutional affiliations permitted to create accounts with institutional authentication were set as follows:');
14004:                                     }
14005:                                     $chgtext .= '<ul>';
14006:                                     foreach my $case (@{$cancreate{$type}}) {
14007:                                         if ($case eq 'default') {
14008:                                             $chgtext .= '<li>'.$othertitle.'</li>';
14009:                                         } else {
14010:                                             $chgtext .= '<li>'.$usertypes{$case}.'</li>';
14011:                                         }
14012:                                     }
14013:                                     $chgtext .= '</ul>';
14014:                                     if (!grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
14015:                                         $chgtext .= '<span class="LC_warning">'.
14016:                                                     &mt('However, users authenticated by institutional login/single sign on are not currently permitted to create accounts.').
14017:                                                     '</span>';
14018:                                     }
14019:                                 }
14020:                             } else {
14021:                                 if (@{$cancreate{$type}} == 0) {
14022:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts were set to 'none'.");
14023:                                 } else {
14024:                                     $chgtext .= &mt('Although institutional affiliations permitted to create accounts were changed, self creation of accounts is not currently permitted for any authentication types.');
14025:                                 }
14026:                             }
14027:                             $chgtext .= '<br />';
14028:                         }
14029:                     } elsif ($type eq 'selfcreateprocessing') {
14030:                         my %choices = &Apache::lonlocal::texthash (
14031:                                                                     automatic => 'Automatic approval',
14032:                                                                     approval  => 'Queued for approval',
14033:                                                                   );
14034:                         if (@types) {
14035:                             if (@statuses) {
14036:                                 $chgtext .= &mt('Processing of requests to create account with e-mail verification set as follows:').
14037:                                             '<ul>';
14038:                                 foreach my $status (@statuses) {
14039:                                     if ($status eq 'default') {
14040:                                         $chgtext .= '<li>'.$othertitle.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
14041:                                     } else {
14042:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
14043:                                     }
14044:                                 }
14045:                                 $chgtext .= '</ul>';
14046:                             }
14047:                         } else {
14048:                             $chgtext .= &mt('Processing of requests to create account with e-mail verification set to: "[_1]"',
14049:                                             $choices{$cancreate{'selfcreateprocessing'}{'default'}});
14050:                         }
14051:                     } elsif ($type eq 'emailverified') {
14052:                         my %options = &Apache::lonlocal::texthash (
14053:                                                                     all   => 'Same as e-mail',
14054:                                                                     first => 'Omit @domain',
14055:                                                                     free  => 'Free to choose',
14056:                                                                   );
14057:                         if (@types) {
14058:                             if (@statuses) {
14059:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, username is set as follows:').
14060:                                             '<ul>';
14061:                                 foreach my $status (@statuses) {
14062:                                     if ($status eq 'default') {
14063:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
14064:                                     } else {
14065:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
14066:                                     }
14067:                                 }
14068:                                 $chgtext .= '</ul>';
14069:                             }
14070:                         } else {
14071:                             $chgtext .= &mt("For self-created accounts verified by e-mail address, user's username is: '[_1]'",
14072:                                             $options{$cancreate{'emailverified'}{'default'}});
14073:                         }
14074:                     } elsif ($type eq 'emailoptions') {
14075:                         my %options = &Apache::lonlocal::texthash (
14076:                                                                     any     => 'Any e-mail',
14077:                                                                     inst    => 'Institutional only',
14078:                                                                     noninst => 'Non-institutional only',
14079:                                                                     custom  => 'Custom restrictions',
14080:                                                                   );
14081:                         if (@types) {
14082:                             if (@statuses) {
14083:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, requirements for e-mail address are as follows:').
14084:                                             '<ul>';
14085:                                 foreach my $status (@statuses) {
14086:                                     if ($type eq 'default') {
14087:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
14088:                                     } else {
14089:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
14090:                                     }
14091:                                 }
14092:                                 $chgtext .= '</ul>';
14093:                             }
14094:                         } else {
14095:                             if ($cancreate{'emailoptions'}{'default'} eq 'any') {
14096:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, any e-mail may be used');
14097:                             } else {
14098:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, e-mail restricted to: "[_1]"',
14099:                                                 $options{$cancreate{'emailoptions'}{'default'}});
14100:                             }
14101:                         }
14102:                     } elsif ($type eq 'emaildomain') {
14103:                         my $output;
14104:                         if (@statuses) {
14105:                             foreach my $type (@statuses) {
14106:                                 if (ref($cancreate{'emaildomain'}{$type}) eq 'HASH') {
14107:                                     if ($cancreate{'emailoptions'}{$type} eq 'inst') {
14108:                                         if ($type eq 'default') {
14109:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
14110:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} eq '')) {
14111:                                                 $output = '<li>'.$othertitle.' -- '.&mt('No restriction on e-mail domain').'</li>';
14112:                                             } else {
14113:                                                 $output = '<li>'.$othertitle.' -- '.&mt("User's e-mail address needs to end: [_1]",
14114:                                                                                         $cancreate{'emaildomain'}{$type}{'inst'}).'</li>';
14115:                                             }
14116:                                         } else {
14117:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
14118:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} eq '')) {
14119:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
14120:                                             } else {
14121:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address needs to end: [_1]",
14122:                                                                                               $cancreate{'emaildomain'}{$type}{'inst'}).'</li>';
14123:                                             }
14124:                                         }
14125:                                     } elsif ($cancreate{'emailoptions'}{$type} eq 'noninst') {
14126:                                         if ($type eq 'default') {
14127:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
14128:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
14129:                                                 $output = '<li>'.$othertitle.' -- '.&mt('No restriction on e-mail domain').'</li>';
14130:                                             } else {
14131:                                                 $output = '<li>'.$othertitle.' -- '.&mt("User's e-mail address must not end: [_1]",
14132:                                                                                         $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';
14133:                                             }
14134:                                         } else {
14135:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
14136:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
14137:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
14138:                                             } else {
14139:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address must not end: [_1]",
14140:                                                                                                 $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';
14141:                                             }
14142:                                         }
14143:                                     }
14144:                                 }
14145:                             }
14146:                         }
14147:                         if ($output ne '') {
14148:                             $chgtext .= &mt('For self-created accounts verified by e-mail address:').
14149:                                         '<ul>'.$output.'</ul>';
14150:                         }
14151:                     } elsif ($type eq 'captcha') {
14152:                         if ($savecaptcha{$type} eq 'notused') {
14153:                             $chgtext .= &mt('No CAPTCHA validation in use for self-creation screen.');
14154:                         } else {
14155:                             my %captchas = &captcha_phrases();
14156:                             if ($captchas{$savecaptcha{$type}}) {
14157:                                 $chgtext .= &mt("Validation for self-creation screen set to $captchas{$savecaptcha{$type}}.");
14158:                             } else {
14159:                                 $chgtext .= &mt('Validation for self-creation screen set to unknown type.');
14160:                             }
14161:                         }
14162:                     } elsif ($type eq 'recaptchakeys') {
14163:                         my ($privkey,$pubkey);
14164:                         if (ref($savecaptcha{$type}) eq 'HASH') {
14165:                             $pubkey = $savecaptcha{$type}{'public'};
14166:                             $privkey = $savecaptcha{$type}{'private'};
14167:                         }
14168:                         $chgtext .= &mt('ReCAPTCHA keys changes').'<ul>';
14169:                         if (!$pubkey) {
14170:                             $chgtext .= '<li>'.&mt('Public key deleted').'</li>';
14171:                         } else {
14172:                             $chgtext .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
14173:                         }
14174:                         if (!$privkey) {
14175:                             $chgtext .= '<li>'.&mt('Private key deleted').'</li>';
14176:                         } else {
14177:                             $chgtext .= '<li>'.&mt('Private key set to [_1]',$pubkey).'</li>';
14178:                         }
14179:                         $chgtext .= '</ul>';
14180:                     } elsif ($type eq 'recaptchaversion') {
14181:                         if ($savecaptcha{'captcha'} eq 'recaptcha') {
14182:                             $chgtext .= &mt('ReCAPTCHA set to version [_1]',$savecaptcha{$type});
14183:                         }
14184:                     } elsif ($type eq 'emailusername') {
14185:                         if (ref($cancreate{'emailusername'}) eq 'HASH') {
14186:                             if (@statuses) {
14187:                                 foreach my $type (@statuses) {
14188:                                     if (ref($cancreate{'emailusername'}{$type}) eq 'HASH') {
14189:                                         if (keys(%{$cancreate{'emailusername'}{$type}}) > 0) {
14190:                                             $chgtext .= &mt('When self-creating account with e-mail verification, the following information will be provided by [_1]:',"'$usertypes{$type}'").
14191:                                                     '<ul>';
14192:                                             foreach my $field (@{$infofields}) {
14193:                                                 if ($cancreate{'emailusername'}{$type}{$field}) {
14194:                                                     $chgtext .= '<li>'.$infotitles->{$field}.'</li>';
14195:                                                 }
14196:                                             }
14197:                                             $chgtext .= '</ul>';
14198:                                         } else {
14199:                                             $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
14200:                                         }
14201:                                     } else {
14202:                                         $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
14203:                                     }
14204:                                 }
14205:                             }
14206:                         }
14207:                     } elsif ($type eq 'notify') {
14208:                         my $numapprove = 0;
14209:                         if (ref($changes{'cancreate'}) eq 'ARRAY') {
14210:                             if ((grep(/^notify$/,@{$changes{'cancreate'}})) && (ref($cancreate{'notify'}) eq 'HASH')) {
14211:                                 if ($cancreate{'notify'}{'approval'}) {
14212:                                     $chgtext .= &mt('Notification of username requests requiring approval will be sent to: ').$cancreate{'notify'}{'approval'};
14213:                                     $numapprove ++;
14214:                                 }
14215:                             }
14216:                         }
14217:                         unless ($numapprove) {
14218:                             $chgtext .= &mt('No Domain Coordinators will receive notification of username requests requiring approval.');
14219:                         }
14220:                     }
14221:                     if ($chgtext) {
14222:                         $resulttext .= '<li>'.$chgtext.'</li>';
14223:                     }
14224:                 }
14225:             }
14226:             if ((ref($changes{'email_rule'}) eq 'ARRAY') && (@{$changes{'email_rule'}} > 0)) {
14227:                 my ($emailrules,$emailruleorder) =
14228:                     &Apache::lonnet::inst_userrules($dom,'email');
14229:                 foreach my $type (@{$changes{'email_rule'}}) {
14230:                     if (ref($email_rule{$type}) eq 'ARRAY') {
14231:                         my $chgtext = '<ul>';
14232:                         foreach my $rule (@{$email_rule{$type}}) {
14233:                             if (ref($emailrules->{$rule}) eq 'HASH') {
14234:                                 $chgtext .= '<li>'.$emailrules->{$rule}{'name'}.'</li>';
14235:                             }
14236:                         }
14237:                         $chgtext .= '</ul>';
14238:                         my $typename;
14239:                         if (@types) {
14240:                             if ($type eq 'default') {
14241:                                 $typename = $othertitle;
14242:                             } else {
14243:                                 $typename = $usertypes{$type};
14244:                             }
14245:                             $chgtext .= &mt('(Affiliation: [_1])',$typename);
14246:                         }
14247:                         if (@{$email_rule{$type}} > 0) {
14248:                             $resulttext .= '<li>'.
14249:                                            &mt('Accounts may not be created by users verified by e-mail, for e-mail addresses of the following types: ',
14250:                                                $usertypes{$type}).
14251:                                            $chgtext.
14252:                                            '</li>';
14253:                         } else {
14254:                             $resulttext .= '<li>'.
14255:                                            &mt('There are now no restrictions on e-mail addresses which may be used for verification when a user requests an account.').
14256:                                            '</li>'.
14257:                                            &mt('(Affiliation: [_1])',$typename);
14258:                         }
14259:                     }
14260:                 }
14261:             }
14262:             if (ref($changes{'inststatus'}) eq 'ARRAY') {
14263:                 if (ref($save_inststatus{'inststatusguest'}) eq 'ARRAY') {
14264:                     if (@{$save_inststatus{'inststatusguest'}} > 0) {
14265:                         my $chgtext = '<ul>';
14266:                         foreach my $type (@{$save_inststatus{'inststatusguest'}}) {
14267:                             $chgtext .= '<li>'.$usertypes{$type}.'</li>';
14268:                         }
14269:                         $chgtext .= '</ul>';
14270:                         $resulttext .= '<li>'.
14271:                                        &mt('A user will self-report one of the following affiliations when requesting an account verified by e-mail: ').
14272:                                           $chgtext.
14273:                                        '</li>';
14274:                     } else {
14275:                         $resulttext .= '<li>'.
14276:                                        &mt('No affiliations available for self-reporting when requesting an account verified by e-mail.').
14277:                                        '</li>';
14278:                     }
14279:                 }
14280:             }
14281:             if (ref($changes{'selfcreate'}) eq 'ARRAY') {
14282:                 $resulttext .= '<li>'.&mt('When self-creating institutional account:').'<ul>';
14283:                 my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
14284:                 foreach my $type (@{$changes{'selfcreate'}}) {
14285:                     my $typename = $type;
14286:                     if (keys(%usertypes) > 0) {
14287:                         if ($usertypes{$type} ne '') {
14288:                             $typename = $usertypes{$type};
14289:                         }
14290:                     }
14291:                     my @modifiable;
14292:                     $resulttext .= '<li>'.
14293:                                     &mt('Self-creation of account by users with status: [_1]',
14294:                                         '<span class="LC_cusr_emph">'.$typename.'</span>').
14295:                                     ' - '.&mt('modifiable fields (if institutional data blank): ');
14296:                     foreach my $field (@fields) {
14297:                         if ($save_usermodify{'selfcreate'}{$type}{$field}) {
14298:                             push(@modifiable,'<b>'.$fieldtitles{$field}.'</b>');
14299:                         }
14300:                     }
14301:                     if (@modifiable > 0) {
14302:                         $resulttext .= join(', ',@modifiable);
14303:                     } else {
14304:                         $resulttext .= &mt('none');
14305:                     }
14306:                     $resulttext .= '</li>';
14307:                 }
14308:                 $resulttext .= '</ul></li>';
14309:             }
14310:             $resulttext .= '</ul>';
14311:             my $cachetime = 24*60*60;
14312:             $domdefaults{'inststatusguest'} = $save_inststatus{'inststatusguest'};
14313:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
14314:             if (ref($lastactref) eq 'HASH') {
14315:                 $lastactref->{'domdefaults'} = 1;
14316:             }
14317:         } else {
14318:             $resulttext = &mt('No changes made to self-creation settings');
14319:         }
14320:     } else {
14321:         $resulttext = '<span class="LC_error">'.
14322:             &mt('An error occurred: [_1]',$putresult).'</span>';
14323:     }
14324:     if ($warningmsg ne '') {
14325:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
14326:     }
14327:     return $resulttext;
14328: }
14329: 
14330: sub process_captcha {
14331:     my ($container,$changes,$newsettings,$currsettings) = @_;
14332:     return unless ((ref($changes) eq 'HASH') && (ref($newsettings) eq 'HASH'));
14333:     $newsettings->{'captcha'} = $env{'form.'.$container.'_captcha'};
14334:     unless ($newsettings->{'captcha'} eq 'recaptcha' || $newsettings->{'captcha'} eq 'notused') {
14335:         $newsettings->{'captcha'} = 'original';
14336:     }
14337:     my %current;
14338:     if (ref($currsettings) eq 'HASH') {
14339:         %current = %{$currsettings};
14340:     }
14341:     if ($current{'captcha'} ne $newsettings->{'captcha'}) {
14342:         if ($container eq 'cancreate') {
14343:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
14344:                 push(@{$changes->{'cancreate'}},'captcha');
14345:             } elsif (!defined($changes->{'cancreate'})) {
14346:                 $changes->{'cancreate'} = ['captcha'];
14347:             }
14348:         } elsif ($container eq 'passwords') {
14349:             $changes->{'reset'} = 1;
14350:         } else {
14351:             $changes->{'captcha'} = 1;
14352:         }
14353:     }
14354:     my ($newpub,$newpriv,$currpub,$currpriv,$newversion,$currversion);
14355:     if ($newsettings->{'captcha'} eq 'recaptcha') {
14356:         $newpub = $env{'form.'.$container.'_recaptchapub'};
14357:         $newpriv = $env{'form.'.$container.'_recaptchapriv'};
14358:         $newpub =~ s/[^\w\-]//g;
14359:         $newpriv =~ s/[^\w\-]//g;
14360:         $newsettings->{'recaptchakeys'} = {
14361:                                              public  => $newpub,
14362:                                              private => $newpriv,
14363:                                           };
14364:         $newversion = $env{'form.'.$container.'_recaptchaversion'};
14365:         $newversion =~ s/\D//g;
14366:         if ($newversion ne '2') {
14367:             $newversion = 1;
14368:         }
14369:         $newsettings->{'recaptchaversion'} = $newversion;
14370:     }
14371:     if (ref($current{'recaptchakeys'}) eq 'HASH') {
14372:         $currpub = $current{'recaptchakeys'}{'public'};
14373:         $currpriv = $current{'recaptchakeys'}{'private'};
14374:         unless ($newsettings->{'captcha'} eq 'recaptcha') {
14375:             $newsettings->{'recaptchakeys'} = {
14376:                                                  public  => '',
14377:                                                  private => '',
14378:                                               }
14379:         }
14380:     }
14381:     if ($current{'captcha'} eq 'recaptcha') {
14382:         $currversion = $current{'recaptchaversion'};
14383:         if ($currversion ne '2') {
14384:             $currversion = 1;
14385:         }
14386:     }
14387:     if ($currversion ne $newversion) {
14388:         if ($container eq 'cancreate') {
14389:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
14390:                 push(@{$changes->{'cancreate'}},'recaptchaversion');
14391:             } elsif (!defined($changes->{'cancreate'})) {
14392:                 $changes->{'cancreate'} = ['recaptchaversion'];
14393:             }
14394:         } elsif ($container eq 'passwords') {
14395:             $changes->{'reset'} = 1;
14396:         } else {
14397:             $changes->{'recaptchaversion'} = 1;
14398:         }
14399:     }
14400:     if (($newpub ne $currpub) || ($newpriv ne $currpriv)) {
14401:         if ($container eq 'cancreate') {
14402:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
14403:                 push(@{$changes->{'cancreate'}},'recaptchakeys');
14404:             } elsif (!defined($changes->{'cancreate'})) {
14405:                 $changes->{'cancreate'} = ['recaptchakeys'];
14406:             }
14407:         } elsif ($container eq 'passwords') {
14408:             $changes->{'reset'} = 1;
14409:         } else {
14410:             $changes->{'recaptchakeys'} = 1;
14411:         }
14412:     }
14413:     return;
14414: }
14415: 
14416: sub modify_usermodification {
14417:     my ($dom,%domconfig) = @_;
14418:     my ($resulttext,%curr_usermodification,%changes,%modifyhash);
14419:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
14420:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
14421:             if ($key eq 'selfcreate') {
14422:                 $modifyhash{$key} = $domconfig{'usermodification'}{$key};
14423:             } else {  
14424:                 $curr_usermodification{$key} = $domconfig{'usermodification'}{$key};
14425:             }
14426:         }
14427:     }
14428:     my @contexts = ('author','course');
14429:     my %context_title = (
14430:                            author => 'In author context',
14431:                            course => 'In course context',
14432:                         );
14433:     my @fields = ('lastname','firstname','middlename','generation',
14434:                   'permanentemail','id');
14435:     my %roles = (
14436:                   author => ['ca','aa'],
14437:                   course => ['st','ep','ta','in','cr'],
14438:                 );
14439:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
14440:     foreach my $context (@contexts) {
14441:         foreach my $role (@{$roles{$context}}) {
14442:             my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$role);
14443:             foreach my $item (@fields) {
14444:                 if (grep(/^\Q$item\E$/,@modifiable)) {
14445:                     $modifyhash{$context}{$role}{$item} = 1;
14446:                 } else {
14447:                     $modifyhash{$context}{$role}{$item} = 0;
14448:                 }
14449:             }
14450:         }
14451:         if (ref($curr_usermodification{$context}) eq 'HASH') {
14452:             foreach my $role (@{$roles{$context}}) {
14453:                 if (ref($curr_usermodification{$context}{$role}) eq 'HASH') {
14454:                     foreach my $field (@fields) {
14455:                         if ($modifyhash{$context}{$role}{$field} ne 
14456:                                 $curr_usermodification{$context}{$role}{$field}) {
14457:                             push(@{$changes{$context}},$role);
14458:                             last;
14459:                         }
14460:                     }
14461:                 }
14462:             }
14463:         } else {
14464:             foreach my $context (@contexts) {
14465:                 foreach my $role (@{$roles{$context}}) {
14466:                     push(@{$changes{$context}},$role);
14467:                 }
14468:             }
14469:         }
14470:     }
14471:     my %usermodification_hash =  (
14472:                                    usermodification => \%modifyhash,
14473:                                  );
14474:     my $putresult = &Apache::lonnet::put_dom('configuration',
14475:                                              \%usermodification_hash,$dom);
14476:     if ($putresult eq 'ok') {
14477:         if (keys(%changes) > 0) {
14478:             $resulttext = &mt('Changes made: ').'<ul>';
14479:             foreach my $context (@contexts) {
14480:                 if (ref($changes{$context}) eq 'ARRAY') {
14481:                     $resulttext .= '<li>'.$context_title{$context}.':<ul>';
14482:                     if (ref($changes{$context}) eq 'ARRAY') {
14483:                         foreach my $role (@{$changes{$context}}) {
14484:                             my $rolename;
14485:                             if ($role eq 'cr') {
14486:                                 $rolename = &mt('Custom');
14487:                             } else {
14488:                                 $rolename = &Apache::lonnet::plaintext($role);
14489:                             }
14490:                             my @modifiable;
14491:                             $resulttext .= '<li><span class="LC_cusr_emph">'.&mt('Target user with [_1] role',$rolename).'</span> - '.&mt('modifiable fields: ');
14492:                             foreach my $field (@fields) {
14493:                                 if ($modifyhash{$context}{$role}{$field}) {
14494:                                     push(@modifiable,$fieldtitles{$field});
14495:                                 }
14496:                             }
14497:                             if (@modifiable > 0) {
14498:                                 $resulttext .= join(', ',@modifiable);
14499:                             } else {
14500:                                 $resulttext .= &mt('none'); 
14501:                             }
14502:                             $resulttext .= '</li>';
14503:                         }
14504:                         $resulttext .= '</ul></li>';
14505:                     }
14506:                 }
14507:             }
14508:             $resulttext .= '</ul>';
14509:         } else {
14510:             $resulttext = &mt('No changes made to user modification settings');
14511:         }
14512:     } else {
14513:         $resulttext = '<span class="LC_error">'.
14514:             &mt('An error occurred: [_1]',$putresult).'</span>';
14515:     }
14516:     return $resulttext;
14517: }
14518: 
14519: sub modify_defaults {
14520:     my ($dom,$lastactref,%domconfig) = @_;
14521:     my ($resulttext,$mailmsgtxt,%newvalues,%changes,@errors);
14522:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
14523:     my @items = ('auth_def','auth_arg_def','lang_def','timezone_def','datelocale_def',
14524:                  'portal_def');
14525:     my @authtypes = ('internal','krb4','krb5','localauth');
14526:     foreach my $item (@items) {
14527:         $newvalues{$item} = $env{'form.'.$item};
14528:         if ($item eq 'auth_def') {
14529:             if ($newvalues{$item} ne '') {
14530:                 if (!grep(/^\Q$newvalues{$item}\E$/,@authtypes)) {
14531:                     push(@errors,$item);
14532:                 }
14533:             }
14534:         } elsif ($item eq 'lang_def') {
14535:             if ($newvalues{$item} ne '') {
14536:                 if ($newvalues{$item} =~ /^(\w+)/) {
14537:                     my $langcode = $1;
14538:                     if ($langcode ne 'x_chef') {
14539:                         if (code2language($langcode) eq '') {
14540:                             push(@errors,$item);
14541:                         }
14542:                     }
14543:                 } else {
14544:                     push(@errors,$item);
14545:                 }
14546:             }
14547:         } elsif ($item eq 'timezone_def') {
14548:             if ($newvalues{$item} ne '') {
14549:                 if (!DateTime::TimeZone->is_valid_name($newvalues{$item})) {
14550:                     push(@errors,$item);   
14551:                 }
14552:             }
14553:         } elsif ($item eq 'datelocale_def') {
14554:             if ($newvalues{$item} ne '') {
14555:                 my @datelocale_ids = DateTime::Locale->ids();
14556:                 if (!grep(/^\Q$newvalues{$item}\E$/,@datelocale_ids)) {
14557:                     push(@errors,$item);
14558:                 }
14559:             }
14560:         } elsif ($item eq 'portal_def') {
14561:             if ($newvalues{$item} ne '') {
14562:                 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])\/?$/) {
14563:                     push(@errors,$item);
14564:                 }
14565:             }
14566:         }
14567:         if (grep(/^\Q$item\E$/,@errors)) {
14568:             $newvalues{$item} = $domdefaults{$item};
14569:         } elsif ($domdefaults{$item} ne $newvalues{$item}) {
14570:             $changes{$item} = 1;
14571:         }
14572:         $domdefaults{$item} = $newvalues{$item};
14573:     }
14574:     my %staticdefaults = (
14575:                            'intauth_cost'   => 10,
14576:                            'intauth_check'  => 0,
14577:                            'intauth_switch' => 0,
14578:                          );
14579:     foreach my $item ('intauth_cost','intauth_check','intauth_switch') {
14580:         if (exists($domdefaults{$item})) {
14581:             $newvalues{$item} = $domdefaults{$item};
14582:         } else {
14583:             $newvalues{$item} = $staticdefaults{$item};
14584:         }
14585:     }
14586:     my %defaults_hash = (
14587:                          defaults => \%newvalues,
14588:                         );
14589:     my $title = &defaults_titles();
14590: 
14591:     my $currinststatus;
14592:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
14593:         $currinststatus = $domconfig{'inststatus'};
14594:     } else {
14595:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
14596:         $currinststatus = {
14597:                              inststatustypes => $usertypes,
14598:                              inststatusorder => $types,
14599:                              inststatusguest => [],
14600:                           };
14601:     }
14602:     my @todelete = &Apache::loncommon::get_env_multiple('form.inststatus_delete');
14603:     my @allpos;
14604:     my %alltypes;
14605:     my @inststatusguest;
14606:     if (ref($currinststatus) eq 'HASH') {
14607:         if (ref($currinststatus->{'inststatusguest'}) eq 'ARRAY') {
14608:             foreach my $type (@{$currinststatus->{'inststatusguest'}}) {
14609:                 unless (grep(/^\Q$type\E$/,@todelete)) {
14610:                     push(@inststatusguest,$type);
14611:                 }
14612:             }
14613:         }
14614:     }
14615:     my ($currtitles,$currorder);
14616:     if (ref($currinststatus) eq 'HASH') {
14617:         if (ref($currinststatus->{'inststatusorder'}) eq 'ARRAY') {
14618:             foreach my $type (@{$currinststatus->{'inststatusorder'}}) {
14619:                 if (ref($currinststatus->{inststatustypes}) eq 'HASH') {
14620:                     if ($currinststatus->{inststatustypes}->{$type} ne '') {
14621:                         $currtitles .= $currinststatus->{inststatustypes}->{$type}.',';
14622:                     }
14623:                 }
14624:                 unless (grep(/^\Q$type\E$/,@todelete)) { 
14625:                     my $position = $env{'form.inststatus_pos_'.$type};
14626:                     $position =~ s/\D+//g;
14627:                     $allpos[$position] = $type;
14628:                     $alltypes{$type} = $env{'form.inststatus_title_'.$type};
14629:                     $alltypes{$type} =~ s/`//g;
14630:                 }
14631:             }
14632:             $currorder = join(',',@{$currinststatus->{'inststatusorder'}});
14633:             $currtitles =~ s/,$//;
14634:         }
14635:     }
14636:     if ($env{'form.addinststatus'}) {
14637:         my $newtype = $env{'form.addinststatus'};
14638:         $newtype =~ s/\W//g;
14639:         unless (exists($alltypes{$newtype})) {
14640:             $alltypes{$newtype} = $env{'form.addinststatus_title'};
14641:             $alltypes{$newtype} =~ s/`//g; 
14642:             my $position = $env{'form.addinststatus_pos'};
14643:             $position =~ s/\D+//g;
14644:             if ($position ne '') {
14645:                 $allpos[$position] = $newtype;
14646:             }
14647:         }
14648:     }
14649:     my @orderedstatus;
14650:     foreach my $type (@allpos) {
14651:         unless (($type eq '') || (grep(/^\Q$type\E$/,@orderedstatus))) {
14652:             push(@orderedstatus,$type);
14653:         }
14654:     }
14655:     foreach my $type (keys(%alltypes)) {
14656:         unless (grep(/^\Q$type\E$/,@orderedstatus)) {
14657:             delete($alltypes{$type});
14658:         }
14659:     }
14660:     $defaults_hash{'inststatus'} = {
14661:                                      inststatustypes => \%alltypes,
14662:                                      inststatusorder => \@orderedstatus,
14663:                                      inststatusguest => \@inststatusguest,
14664:                                    };
14665:     if (ref($defaults_hash{'inststatus'}) eq 'HASH') {
14666:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
14667:             $domdefaults{$item} = $defaults_hash{'inststatus'}{$item};
14668:         }
14669:     }
14670:     if ($currorder ne join(',',@orderedstatus)) {
14671:         $changes{'inststatus'}{'inststatusorder'} = 1;
14672:     }
14673:     my $newtitles;
14674:     foreach my $item (@orderedstatus) {
14675:         $newtitles .= $alltypes{$item}.',';
14676:     }
14677:     $newtitles =~ s/,$//;
14678:     if ($currtitles ne $newtitles) {
14679:         $changes{'inststatus'}{'inststatustypes'} = 1;
14680:     }
14681:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaults_hash,
14682:                                              $dom);
14683:     if ($putresult eq 'ok') {
14684:         if (keys(%changes) > 0) {
14685:             $resulttext = &mt('Changes made:').'<ul>';
14686:             my $version = &Apache::lonnet::get_server_loncaparev($dom);
14687:             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";
14688:             foreach my $item (sort(keys(%changes))) {
14689:                 if ($item eq 'inststatus') {
14690:                     if (ref($changes{'inststatus'}) eq 'HASH') {
14691:                         if (@orderedstatus) {
14692:                             $resulttext .= '<li>'.&mt('Institutional user status types set to:').' ';
14693:                             foreach my $type (@orderedstatus) { 
14694:                                 $resulttext .= $alltypes{$type}.', ';
14695:                             }
14696:                             $resulttext =~ s/, $//;
14697:                             $resulttext .= '</li>';
14698:                         } else {
14699:                             $resulttext .= '<li>'.&mt('Institutional user status types deleted').'</li>';
14700:                         }
14701:                     }
14702:                 } else {
14703:                     my $value = $env{'form.'.$item};
14704:                     if ($value eq '') {
14705:                         $value = &mt('none');
14706:                     } elsif ($item eq 'auth_def') {
14707:                         my %authnames = &authtype_names();
14708:                         my %shortauth = (
14709:                                           internal   => 'int',
14710:                                           krb4       => 'krb4',
14711:                                           krb5       => 'krb5',
14712:                                           localauth  => 'loc',
14713:                         );
14714:                         $value = $authnames{$shortauth{$value}};
14715:                     }
14716:                     $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$title->{$item},$value).'</li>';
14717:                     $mailmsgtext .= "$title->{$item} set to $value\n";  
14718:                 }
14719:             }
14720:             $resulttext .= '</ul>';
14721:             $mailmsgtext .= "\n";
14722:             my $cachetime = 24*60*60;
14723:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
14724:             if (ref($lastactref) eq 'HASH') {
14725:                 $lastactref->{'domdefaults'} = 1;
14726:             }
14727:             if ($changes{'auth_def'} || $changes{'auth_arg_def'} || $changes{'lang_def'} || $changes{'datelocale_def'}) {
14728:                 my $notify = 1;
14729:                 if (ref($domconfig{'contacts'}) eq 'HASH') {
14730:                     if ($domconfig{'contacts'}{'reportupdates'} == 0) {
14731:                         $notify = 0;
14732:                     }
14733:                 }
14734:                 if ($notify) {
14735:                     &Apache::lonmsg::sendemail('installrecord@loncapa.org',
14736:                                                "LON-CAPA Domain Settings Change - $dom",
14737:                                                $mailmsgtext);
14738:                 }
14739:             }
14740:         } else {
14741:             $resulttext = &mt('No changes made to default authentication/language/timezone settings');
14742:         }
14743:     } else {
14744:         $resulttext = '<span class="LC_error">'.
14745:             &mt('An error occurred: [_1]',$putresult).'</span>';
14746:     }
14747:     if (@errors > 0) {
14748:         $resulttext .= '<br />'.&mt('The following were left unchanged because the values entered were invalid:');
14749:         foreach my $item (@errors) {
14750:             $resulttext .= ' "'.$title->{$item}.'",';
14751:         }
14752:         $resulttext =~ s/,$//;
14753:     }
14754:     return $resulttext;
14755: }
14756: 
14757: sub modify_scantron {
14758:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
14759:     my ($resulttext,%confhash,%changes,$errors);
14760:     my $custom = 'custom.tab';
14761:     my $default = 'default.tab';
14762:     my $servadm = $r->dir_config('lonAdmEMail');
14763:     my ($configuserok,$author_ok,$switchserver) =
14764:         &config_check($dom,$confname,$servadm);
14765:     if ($env{'form.scantronformat.filename'} ne '') {
14766:         my $error;
14767:         if ($configuserok eq 'ok') {
14768:             if ($switchserver) {
14769:                 $error = &mt("Upload of bubblesheet format file is not permitted to this server: [_1]",$switchserver);
14770:             } else {
14771:                 if ($author_ok eq 'ok') {
14772:                     my ($result,$scantronurl) =
14773:                         &publishlogo($r,'upload','scantronformat',$dom,
14774:                                      $confname,'scantron','','',$custom);
14775:                     if ($result eq 'ok') {
14776:                         $confhash{'scantron'}{'scantronformat'} = $scantronurl;
14777:                         $changes{'scantronformat'} = 1;
14778:                     } else {
14779:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$custom,$result);
14780:                     }
14781:                 } else {
14782:                     $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);
14783:                 }
14784:             }
14785:         } else {
14786:             $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);
14787:         }
14788:         if ($error) {
14789:             &Apache::lonnet::logthis($error);
14790:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
14791:         }
14792:     }
14793:     if (ref($domconfig{'scantron'}) eq 'HASH') {
14794:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
14795:             if ($env{'form.scantronformat_del'}) {
14796:                 $confhash{'scantron'}{'scantronformat'} = '';
14797:                 $changes{'scantronformat'} = 1;
14798:             } else {
14799:                 $confhash{'scantron'}{'scantronformat'} = $domconfig{'scantron'}{'scantronformat'};
14800:             }
14801:         }
14802:     }
14803:     my @options = ('hdr','pad','rem');
14804:     my @fields = &scantroncsv_fields();
14805:     my %titles = &scantronconfig_titles();
14806:     my @formats = &Apache::loncommon::get_env_multiple('form.scantronconfig');
14807:     my ($newdat,$currdat,%newcol,%currcol);
14808:     if (grep(/^dat$/,@formats)) {
14809:         $confhash{'scantron'}{config}{dat} = 1;
14810:         $newdat = 1;
14811:     } else {
14812:         $newdat = 0;
14813:     }
14814:     if (grep(/^csv$/,@formats)) {
14815:         my %bynum;
14816:         foreach my $field (@fields) {
14817:             if ($env{'form.scantronconfig_csv_'.$field} =~ /^(\d+)$/) {
14818:                 my $posscol = $1;
14819:                 if (($posscol < 20) && (!$bynum{$posscol})) {
14820:                     $confhash{'scantron'}{config}{csv}{fields}{$field} = $posscol;
14821:                     $bynum{$posscol} = $field;
14822:                     $newcol{$field} = $posscol;
14823:                 }
14824:             }
14825:         }
14826:         if (keys(%newcol)) {
14827:             foreach my $option (@options) {
14828:                 if ($env{'form.scantroncsv_'.$option}) {
14829:                     $confhash{'scantron'}{config}{csv}{options}{$option} = 1;
14830:                 }
14831:             }
14832:         }
14833:     }
14834:     $currdat = 1;
14835:     if (ref($domconfig{'scantron'}) eq 'HASH') {
14836:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
14837:             unless (exists($domconfig{'scantron'}{'config'}{'dat'})) {
14838:                 $currdat = 0;
14839:             }
14840:             if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
14841:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
14842:                     %currcol = %{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}};
14843:                 }
14844:             }
14845:         }
14846:     }
14847:     if ($currdat != $newdat) {
14848:         $changes{'config'} = 1;
14849:     } else {
14850:         foreach my $field (@fields) {
14851:             if ($currcol{$field} ne '') {
14852:                 if ($currcol{$field} ne $newcol{$field}) {
14853:                     $changes{'config'} = 1;
14854:                     last;
14855:                 }
14856:             } elsif ($newcol{$field} ne '') {
14857:                 $changes{'config'} = 1;
14858:                 last;
14859:             }
14860:         }
14861:     }
14862:     if (keys(%confhash) > 0) {
14863:         my $putresult = &Apache::lonnet::put_dom('configuration',\%confhash,
14864:                                                  $dom);
14865:         if ($putresult eq 'ok') {
14866:             if (keys(%changes) > 0) {
14867:                 if (ref($confhash{'scantron'}) eq 'HASH') {
14868:                     $resulttext = &mt('Changes made:').'<ul>';
14869:                     if ($changes{'scantronformat'}) {
14870:                         if ($confhash{'scantron'}{'scantronformat'} eq '') {
14871:                             $resulttext .= '<li>'.&mt('[_1] bubblesheet format file removed; [_2] file will be used for courses in this domain.',$custom,$default).'</li>';
14872:                         } else {
14873:                             $resulttext .= '<li>'.&mt('Custom bubblesheet format file ([_1]) uploaded for use with courses in this domain.',$custom).'</li>';
14874:                         }
14875:                     }
14876:                     if ($changes{'config'}) {
14877:                         if (ref($confhash{'scantron'}{'config'}) eq 'HASH') {
14878:                             if ($confhash{'scantron'}{'config'}{'dat'}) {
14879:                                 $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .dat format').'</li>';
14880:                             }
14881:                             if (ref($confhash{'scantron'}{'config'}{'csv'}) eq 'HASH') {
14882:                                 if (ref($confhash{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
14883:                                     if (keys(%{$confhash{'scantron'}{'config'}{'csv'}{'fields'}})) {
14884:                                         $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .csv format, with following fields/column numbers supported:').'<ul>';
14885:                                         foreach my $field (@fields) {
14886:                                             if ($confhash{'scantron'}{'config'}{'csv'}{'fields'}{$field} ne '') {
14887:                                                 my $showcol = $confhash{'scantron'}{'config'}{'csv'}{'fields'}{$field} + 1;
14888:                                                 $resulttext .= '<li>'.$titles{$field}.': '.$showcol.'</li>';
14889:                                             }
14890:                                         }
14891:                                         $resulttext .= '</ul></li>';
14892:                                         if (ref($confhash{'scantron'}{'config'}{'csv'}{'options'}) eq 'HASH') {
14893:                                             if (keys(%{$confhash{'scantron'}{'config'}{'csv'}{'options'}})) {
14894:                                                 $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .csv format, with following options:').'<ul>';
14895:                                                 foreach my $option (@options) {
14896:                                                     if ($confhash{'scantron'}{'config'}{'csv'}{'options'}{$option} ne '') {
14897:                                                         $resulttext .= '<li>'.$titles{$option}.'</li>';
14898:                                                     }
14899:                                                 }
14900:                                                 $resulttext .= '</ul></li>';
14901:                                             }
14902:                                         }
14903:                                     }
14904:                                 }
14905:                             }
14906:                         } else {
14907:                             $resulttext .= '<li>'.&mt('No bubblesheet data upload formats set -- will default to assuming .dat format').'</li>';
14908:                         }
14909:                     }
14910:                     $resulttext .= '</ul>';
14911:                 } else {
14912:                     $resulttext = &mt('Changes made to bubblesheet format file.');
14913:                 }
14914:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
14915:                 if (ref($lastactref) eq 'HASH') {
14916:                     $lastactref->{'domainconfig'} = 1;
14917:                 }
14918:             } else {
14919:                 $resulttext = &mt('No changes made to bubblesheet format settings');
14920:             }
14921:         } else {
14922:             $resulttext = '<span class="LC_error">'.
14923:                 &mt('An error occurred: [_1]',$putresult).'</span>';
14924:         }
14925:     } else {
14926:         $resulttext = &mt('No changes made to bubblesheet format settings');
14927:     }
14928:     if ($errors) {
14929:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
14930:                        $errors.'</ul>';
14931:     }
14932:     return $resulttext;
14933: }
14934: 
14935: sub modify_coursecategories {
14936:     my ($dom,$lastactref,%domconfig) = @_;
14937:     my ($resulttext,%deletions,%reorderings,%needreordering,%adds,%changes,$errors,
14938:         $cathash);
14939:     my @deletecategory = &Apache::loncommon::get_env_multiple('form.deletecategory');
14940:     my @catitems = ('unauth','auth');
14941:     my @cattypes = ('std','domonly','codesrch','none');
14942:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
14943:         $cathash = $domconfig{'coursecategories'}{'cats'};
14944:         if ($domconfig{'coursecategories'}{'togglecats'} ne $env{'form.togglecats'}) {
14945:             $changes{'togglecats'} = 1;
14946:             $domconfig{'coursecategories'}{'togglecats'} = $env{'form.togglecats'};
14947:         }
14948:         if ($domconfig{'coursecategories'}{'categorize'} ne $env{'form.categorize'}) {
14949:             $changes{'categorize'} = 1;
14950:             $domconfig{'coursecategories'}{'categorize'} = $env{'form.categorize'};
14951:         }
14952:         if ($domconfig{'coursecategories'}{'togglecatscomm'} ne $env{'form.togglecatscomm'}) {
14953:             $changes{'togglecatscomm'} = 1;
14954:             $domconfig{'coursecategories'}{'togglecatscomm'} = $env{'form.togglecatscomm'};
14955:         }
14956:         if ($domconfig{'coursecategories'}{'categorizecomm'} ne $env{'form.categorizecomm'}) {
14957:             $changes{'categorizecomm'} = 1;
14958:             $domconfig{'coursecategories'}{'categorizecomm'} = $env{'form.categorizecomm'};
14959:         }
14960:         foreach my $item (@catitems) {
14961:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
14962:                 if ($domconfig{'coursecategories'}{$item} ne $env{'form.coursecat_'.$item}) {
14963:                     $changes{$item} = 1;
14964:                     $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
14965:                 }
14966:             }
14967:         }
14968:     } else {
14969:         $changes{'togglecats'} = 1;
14970:         $changes{'categorize'} = 1;
14971:         $changes{'togglecatscomm'} = 1;
14972:         $changes{'categorizecomm'} = 1;
14973:         $domconfig{'coursecategories'} = {
14974:                                              togglecats => $env{'form.togglecats'},
14975:                                              categorize => $env{'form.categorize'},
14976:                                              togglecatscomm => $env{'form.togglecatscomm'},
14977:                                              categorizecomm => $env{'form.categorizecomm'},
14978:                                          };
14979:         foreach my $item (@catitems) {
14980:             if ($env{'form.coursecat_'.$item} ne 'std') {
14981:                 $changes{$item} = 1;
14982:             }
14983:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
14984:                 $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
14985:             }
14986:         }
14987:     }
14988:     if (ref($cathash) eq 'HASH') {
14989:         if (($domconfig{'coursecategories'}{'cats'}{'instcode::0'} ne '')  && ($env{'form.instcode'} == 0)) {
14990:             push (@deletecategory,'instcode::0');
14991:         }
14992:         if (($domconfig{'coursecategories'}{'cats'}{'communities::0'} ne '')  && ($env{'form.communities'} == 0)) {
14993:             push(@deletecategory,'communities::0');
14994:         }
14995:     }
14996:     my (@predelcats,@predeltrails,%predelallitems,%sort_by_deltrail);
14997:     if (ref($cathash) eq 'HASH') {
14998:         if (@deletecategory > 0) {
14999:             #FIXME Need to remove category from all courses using a deleted category 
15000:             &Apache::loncommon::extract_categories($cathash,\@predelcats,\@predeltrails,\%predelallitems);
15001:             foreach my $item (@deletecategory) {
15002:                 if ($domconfig{'coursecategories'}{'cats'}{$item} ne '') {
15003:                     delete($domconfig{'coursecategories'}{'cats'}{$item});
15004:                     $deletions{$item} = 1;
15005:                     &recurse_cat_deletes($item,$cathash,\%deletions);
15006:                 }
15007:             }
15008:         }
15009:         foreach my $item (keys(%{$cathash})) {
15010:             my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
15011:             if ($cathash->{$item} ne $env{'form.'.$item}) {
15012:                 $reorderings{$item} = 1;
15013:                 $domconfig{'coursecategories'}{'cats'}{$item} = $env{'form.'.$item};
15014:             }
15015:             if ($env{'form.addcategory_name_'.$item} ne '') {
15016:                 my $newcat = $env{'form.addcategory_name_'.$item};
15017:                 my $newdepth = $depth+1;
15018:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
15019:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos_'.$item};
15020:                 $adds{$newitem} = 1; 
15021:             }
15022:             if ($env{'form.subcat_'.$item} ne '') {
15023:                 my $newcat = $env{'form.subcat_'.$item};
15024:                 my $newdepth = $depth+1;
15025:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
15026:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = 0;
15027:                 $adds{$newitem} = 1;
15028:             }
15029:         }
15030:     }
15031:     if ($env{'form.instcode'} eq '1') {
15032:         if (ref($cathash) eq 'HASH') {
15033:             my $newitem = 'instcode::0';
15034:             if ($cathash->{$newitem} eq '') {  
15035:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
15036:                 $adds{$newitem} = 1;
15037:             }
15038:         } else {
15039:             my $newitem = 'instcode::0';
15040:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
15041:             $adds{$newitem} = 1;
15042:         }
15043:     }
15044:     if ($env{'form.communities'} eq '1') {
15045:         if (ref($cathash) eq 'HASH') {
15046:             my $newitem = 'communities::0';
15047:             if ($cathash->{$newitem} eq '') {
15048:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
15049:                 $adds{$newitem} = 1;
15050:             }
15051:         } else {
15052:             my $newitem = 'communities::0';
15053:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
15054:             $adds{$newitem} = 1;
15055:         }
15056:     }
15057:     if ($env{'form.addcategory_name'} ne '') {
15058:         if (($env{'form.addcategory_name'} ne 'instcode') &&
15059:             ($env{'form.addcategory_name'} ne 'communities')) {
15060:             my $newitem = &escape($env{'form.addcategory_name'}).'::0';
15061:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos'};
15062:             $adds{$newitem} = 1;
15063:         }
15064:     }
15065:     my $putresult;
15066:     if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
15067:         if (keys(%deletions) > 0) {
15068:             foreach my $key (keys(%deletions)) {
15069:                 if ($predelallitems{$key} ne '') {
15070:                     $sort_by_deltrail{$predelallitems{$key}} = $predeltrails[$predelallitems{$key}];
15071:                 }
15072:             }
15073:         }
15074:         my (@chkcats,@chktrails,%chkallitems);
15075:         &Apache::loncommon::extract_categories($domconfig{'coursecategories'}{'cats'},\@chkcats,\@chktrails,\%chkallitems);
15076:         if (ref($chkcats[0]) eq 'ARRAY') {
15077:             my $depth = 0;
15078:             my $chg = 0;
15079:             for (my $i=0; $i<@{$chkcats[0]}; $i++) {
15080:                 my $name = $chkcats[0][$i];
15081:                 my $item;
15082:                 if ($name eq '') {
15083:                     $chg ++;
15084:                 } else {
15085:                     $item = &escape($name).'::0';
15086:                     if ($chg) {
15087:                         $domconfig{'coursecategories'}{'cats'}{$item} -= $chg;
15088:                     }
15089:                     $depth ++; 
15090:                     &recurse_check(\@chkcats,$domconfig{'coursecategories'}{'cats'},$depth,$name);
15091:                     $depth --;
15092:                 }
15093:             }
15094:         }
15095:     }
15096:     if ((keys(%changes) > 0) || (keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
15097:         $putresult = &Apache::lonnet::put_dom('configuration',\%domconfig,$dom);
15098:         if ($putresult eq 'ok') {
15099:             my %title = (
15100:                          togglecats     => 'Show/Hide a course in catalog',
15101:                          categorize     => 'Assign a category to a course',
15102:                          togglecatscomm => 'Show/Hide a community in catalog',
15103:                          categorizecomm => 'Assign a category to a community',
15104:                         );
15105:             my %level = (
15106:                          dom  => 'set in Domain ("Modify Course/Community")',
15107:                          crs  => 'set in Course ("Course Configuration")',
15108:                          comm => 'set in Community ("Community Configuration")',
15109:                          none     => 'No catalog',
15110:                          std      => 'Standard catalog',
15111:                          domonly  => 'Domain-only catalog',
15112:                          codesrch => 'Code search form',
15113:                         );
15114:             $resulttext = &mt('Changes made:').'<ul>';
15115:             if ($changes{'togglecats'}) {
15116:                 $resulttext .= '<li>'.&mt("$title{'togglecats'} $level{$env{'form.togglecats'}}").'</li>'; 
15117:             }
15118:             if ($changes{'categorize'}) {
15119:                 $resulttext .= '<li>'.&mt("$title{'categorize'} $level{$env{'form.categorize'}}").'</li>';
15120:             }
15121:             if ($changes{'togglecatscomm'}) {
15122:                 $resulttext .= '<li>'.&mt("$title{'togglecatscomm'} $level{$env{'form.togglecatscomm'}}").'</li>';
15123:             }
15124:             if ($changes{'categorizecomm'}) {
15125:                 $resulttext .= '<li>'.&mt("$title{'categorizecomm'} $level{$env{'form.categorizecomm'}}").'</li>';
15126:             }
15127:             if ($changes{'unauth'}) {
15128:                 $resulttext .= '<li>'.&mt('Catalog type for unauthenticated users set to "'.$level{$env{'form.coursecat_unauth'}}.'"').'</li>';
15129:             }
15130:             if ($changes{'auth'}) {
15131:                 $resulttext .= '<li>'.&mt('Catalog type for authenticated users set to "'.$level{$env{'form.coursecat_auth'}}.'"').'</li>';
15132:             }
15133:             if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
15134:                 my $cathash;
15135:                 if (ref($domconfig{'coursecategories'}) eq 'HASH') {
15136:                     $cathash = $domconfig{'coursecategories'}{'cats'};
15137:                 } else {
15138:                     $cathash = {};
15139:                 } 
15140:                 my (@cats,@trails,%allitems);
15141:                     &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,\%allitems);
15142:                 if (keys(%deletions) > 0) {
15143:                     $resulttext .= '<li>'.&mt('Deleted categories:').'<ul>';
15144:                     foreach my $predeltrail (sort {$a <=> $b } (keys(%sort_by_deltrail))) { 
15145:                         $resulttext .= '<li>'.$predeltrails[$predeltrail].'</li>';
15146:                     }
15147:                     $resulttext .= '</ul></li>';
15148:                 }
15149:                 if (keys(%reorderings) > 0) {
15150:                     my %sort_by_trail;
15151:                     $resulttext .= '<li>'.&mt('Reordered categories:').'<ul>';
15152:                     foreach my $key (keys(%reorderings)) {
15153:                         if ($allitems{$key} ne '') {
15154:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
15155:                         }
15156:                     }
15157:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
15158:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
15159:                     }
15160:                     $resulttext .= '</ul></li>';
15161:                 }
15162:                 if (keys(%adds) > 0) {
15163:                     my %sort_by_trail;
15164:                     $resulttext .= '<li>'.&mt('Added categories:').'<ul>';
15165:                     foreach my $key (keys(%adds)) {
15166:                         if ($allitems{$key} ne '') {
15167:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
15168:                         }
15169:                     }
15170:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
15171:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
15172:                     }
15173:                     $resulttext .= '</ul></li>';
15174:                 }
15175:                 &Apache::lonnet::do_cache_new('cats',$dom,$cathash,3600);
15176:                 if (ref($lastactref) eq 'HASH') {
15177:                     $lastactref->{'cats'} = 1;
15178:                 }
15179:             }
15180:             $resulttext .= '</ul>';
15181:             if ($changes{'unauth'} || $changes{'auth'}) {
15182:                 my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
15183:                 if ($changes{'auth'}) {
15184:                     $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
15185:                 }
15186:                 if ($changes{'unauth'}) {
15187:                     $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
15188:                 }
15189:                 my $cachetime = 24*60*60;
15190:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
15191:                 if (ref($lastactref) eq 'HASH') {
15192:                     $lastactref->{'domdefaults'} = 1;
15193:                 }
15194:             }
15195:         } else {
15196:             $resulttext = '<span class="LC_error">'.
15197:                           &mt('An error occurred: [_1]',$putresult).'</span>';
15198:         }
15199:     } else {
15200:         $resulttext = &mt('No changes made to course and community categories');
15201:     }
15202:     return $resulttext;
15203: }
15204: 
15205: sub modify_serverstatuses {
15206:     my ($dom,%domconfig) = @_;
15207:     my ($resulttext,%changes,%currserverstatus,%newserverstatus);
15208:     if (ref($domconfig{'serverstatuses'}) eq 'HASH') {
15209:         %currserverstatus = %{$domconfig{'serverstatuses'}};
15210:     }
15211:     my @pages = &serverstatus_pages();
15212:     foreach my $type (@pages) {
15213:         $newserverstatus{$type}{'namedusers'} = '';
15214:         $newserverstatus{$type}{'machines'} = '';
15215:         if (defined($env{'form.'.$type.'_namedusers'})) {
15216:             my @users = split(/,/,$env{'form.'.$type.'_namedusers'});
15217:             my @okusers;
15218:             foreach my $user (@users) {
15219:                 my ($uname,$udom) = split(/:/,$user);
15220:                 if (($udom =~ /^$match_domain$/) &&   
15221:                     (&Apache::lonnet::domain($udom)) &&
15222:                     ($uname =~ /^$match_username$/)) {
15223:                     if (!grep(/^\Q$user\E/,@okusers)) {
15224:                         push(@okusers,$user);
15225:                     }
15226:                 }
15227:             }
15228:             if (@okusers > 0) {
15229:                  @okusers = sort(@okusers);
15230:                  $newserverstatus{$type}{'namedusers'} = join(',',@okusers);
15231:             }
15232:         }
15233:         if (defined($env{'form.'.$type.'_machines'})) {
15234:             my @machines = split(/,/,$env{'form.'.$type.'_machines'});
15235:             my @okmachines;
15236:             foreach my $ip (@machines) {
15237:                 my @parts = split(/\./,$ip);
15238:                 next if (@parts < 4);
15239:                 my $badip = 0;
15240:                 for (my $i=0; $i<4; $i++) {
15241:                     if (!(($parts[$i] >= 0) && ($parts[$i] <= 255))) {
15242:                         $badip = 1;
15243:                         last;
15244:                     }
15245:                 }
15246:                 if (!$badip) {
15247:                     push(@okmachines,$ip);     
15248:                 }
15249:             }
15250:             @okmachines = sort(@okmachines);
15251:             $newserverstatus{$type}{'machines'} = join(',',@okmachines);
15252:         }
15253:     }
15254:     my %serverstatushash =  (
15255:                                 serverstatuses => \%newserverstatus,
15256:                             );
15257:     foreach my $type (@pages) {
15258:         foreach my $setting ('namedusers','machines') {
15259:             my (@current,@new);
15260:             if (ref($currserverstatus{$type}) eq 'HASH') {
15261:                 if ($currserverstatus{$type}{$setting} ne '') { 
15262:                     @current = split(/,/,$currserverstatus{$type}{$setting});
15263:                 }
15264:             }
15265:             if ($newserverstatus{$type}{$setting} ne '') {
15266:                 @new = split(/,/,$newserverstatus{$type}{$setting});
15267:             }
15268:             if (@current > 0) {
15269:                 if (@new > 0) {
15270:                     foreach my $item (@current) {
15271:                         if (!grep(/^\Q$item\E$/,@new)) {
15272:                             $changes{$type}{$setting} = 1;
15273:                             last;
15274:                         }
15275:                     }
15276:                     foreach my $item (@new) {
15277:                         if (!grep(/^\Q$item\E$/,@current)) {
15278:                             $changes{$type}{$setting} = 1;
15279:                             last;
15280:                         }
15281:                     }
15282:                 } else {
15283:                     $changes{$type}{$setting} = 1;
15284:                 }
15285:             } elsif (@new > 0) {
15286:                 $changes{$type}{$setting} = 1;
15287:             }
15288:         }
15289:     }
15290:     if (keys(%changes) > 0) {
15291:         my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
15292:         my $putresult = &Apache::lonnet::put_dom('configuration',
15293:                                                  \%serverstatushash,$dom);
15294:         if ($putresult eq 'ok') {
15295:             $resulttext .= &mt('Changes made:').'<ul>';
15296:             foreach my $type (@pages) {
15297:                 if (ref($changes{$type}) eq 'HASH') {
15298:                     $resulttext .= '<li>'.$titles->{$type}.'<ul>';
15299:                     if ($changes{$type}{'namedusers'}) {
15300:                         if ($newserverstatus{$type}{'namedusers'} eq '') {
15301:                             $resulttext .= '<li>'.&mt("Access terminated for all specific (named) users").'</li>'."\n";
15302:                         } else {
15303:                             $resulttext .= '<li>'.&mt("Access available for the following specified users: ").$newserverstatus{$type}{'namedusers'}.'</li>'."\n";
15304:                         }
15305:                     }
15306:                     if ($changes{$type}{'machines'}) {
15307:                         if ($newserverstatus{$type}{'machines'} eq '') {
15308:                             $resulttext .= '<li>'.&mt("Access terminated for all specific IP addresses").'</li>'."\n";
15309:                         } else {
15310:                             $resulttext .= '<li>'.&mt("Access available for the following specified IP addresses: ").$newserverstatus{$type}{'machines'}.'</li>'."\n";
15311:                         }
15312: 
15313:                     }
15314:                     $resulttext .= '</ul></li>';
15315:                 }
15316:             }
15317:             $resulttext .= '</ul>';
15318:         } else {
15319:             $resulttext = '<span class="LC_error">'.
15320:                           &mt('An error occurred saving access settings for server status pages: [_1].',$putresult).'</span>';
15321: 
15322:         }
15323:     } else {
15324:         $resulttext = &mt('No changes made to access to server status pages');
15325:     }
15326:     return $resulttext;
15327: }
15328: 
15329: sub modify_helpsettings {
15330:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
15331:     my ($resulttext,$errors,%changes,%helphash);
15332:     my %defaultchecked = ('submitbugs' => 'on');
15333:     my @offon = ('off','on');
15334:     my @toggles = ('submitbugs');
15335:     my %current = ('submitbugs' => '',
15336:                    'adhoc'      => {},
15337:                   );
15338:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
15339:         %current = %{$domconfig{'helpsettings'}};
15340:     }
15341:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
15342:     foreach my $item (@toggles) {
15343:         if ($defaultchecked{$item} eq 'on') { 
15344:             if ($current{$item} eq '') {
15345:                 if ($env{'form.'.$item} eq '0') {
15346:                     $changes{$item} = 1;
15347:                 }
15348:             } elsif ($current{$item} ne $env{'form.'.$item}) {
15349:                 $changes{$item} = 1;
15350:             }
15351:         } elsif ($defaultchecked{$item} eq 'off') {
15352:             if ($current{$item} eq '') {
15353:                 if ($env{'form.'.$item} eq '1') {
15354:                     $changes{$item} = 1;
15355:                 }
15356:             } elsif ($current{$item} ne $env{'form.'.$item}) {
15357:                 $changes{$item} = 1;
15358:             }
15359:         }
15360:         if (($env{'form.'.$item} eq '0') || ($env{'form.'.$item} eq '1')) {
15361:             $helphash{'helpsettings'}{$item} = $env{'form.'.$item};
15362:         }
15363:     }
15364:     my $maxnum = $env{'form.helproles_maxnum'};
15365:     my $confname = $dom.'-domainconfig';
15366:     my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
15367:     my (@allpos,%newsettings,%changedprivs,$newrole);
15368:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
15369:     my @accesstypes = ('all','dh','da','none','status','inc','exc');
15370:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh','da']);
15371:     my %lt = &Apache::lonlocal::texthash(
15372:                     s      => 'system',
15373:                     d      => 'domain',
15374:                     order  => 'Display order',
15375:                     access => 'Role usage',
15376:                     all    => 'All with domain helpdesk or helpdesk assistant role',
15377:                     dh     => 'All with domain helpdesk role',
15378:                     da     => 'All with domain helpdesk assistant role',
15379:                     none   => 'None',
15380:                     status => 'Determined based on institutional status',
15381:                     inc    => 'Include all, but exclude specific personnel',
15382:                     exc    => 'Exclude all, but include specific personnel',
15383:     );
15384:     for (my $num=0; $num<=$maxnum; $num++) {
15385:         my ($prefix,$identifier,$rolename,%curr);
15386:         if ($num == $maxnum) {
15387:             next unless ($env{'form.newcusthelp'} == $maxnum);
15388:             $identifier = 'custhelp'.$num;
15389:             $prefix = 'helproles_'.$num;
15390:             $rolename = $env{'form.custhelpname'.$num};
15391:             $rolename=~s/[^A-Za-z0-9]//gs;
15392:             next if ($rolename eq '');
15393:             next if (exists($existing{'rolesdef_'.$rolename}));
15394:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
15395:             my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
15396:                                                      $newprivs{'c'},$confname,$dom);
15397:             if ($result ne 'ok') {
15398:                 $errors .= '<li><span class="LC_error">'.
15399:                            &mt('An error occurred storing the new custom role: [_1]',
15400:                            $result).'</span></li>';
15401:                 next;
15402:             } else {
15403:                 $changedprivs{$rolename} = \%newprivs;
15404:                 $newrole = $rolename;
15405:             }
15406:         } else {
15407:             $prefix = 'helproles_'.$num;
15408:             $rolename = $env{'form.'.$prefix};
15409:             next if ($rolename eq '');
15410:             next unless (exists($existing{'rolesdef_'.$rolename}));
15411:             $identifier = 'custhelp'.$num;
15412:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
15413:             my %currprivs;
15414:             ($currprivs{'s'},$currprivs{'d'},$currprivs{'c'}) =
15415:                 split(/\_/,$existing{'rolesdef_'.$rolename});
15416:             foreach my $level ('c','d','s') {
15417:                 if ($newprivs{$level} ne $currprivs{$level}) {
15418:                     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
15419:                                                              $newprivs{'c'},$confname,$dom);
15420:                     if ($result ne 'ok') {
15421:                         $errors .= '<li><span class="LC_error">'.
15422:                                    &mt('An error occurred storing privileges for existing role [_1]: [_2]',
15423:                                        $rolename,$result).'</span></li>';
15424:                     } else {
15425:                         $changedprivs{$rolename} = \%newprivs;
15426:                     }
15427:                     last;
15428:                 }
15429:             }
15430:             if (ref($current{'adhoc'}) eq 'HASH') {
15431:                 if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
15432:                     %curr = %{$current{'adhoc'}{$rolename}};
15433:                 }
15434:             }
15435:         }
15436:         my $newpos = $env{'form.'.$prefix.'_pos'};
15437:         $newpos =~ s/\D+//g;
15438:         $allpos[$newpos] = $rolename;
15439:         my $newdesc = $env{'form.'.$prefix.'_desc'};
15440:         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'desc'} = $newdesc;
15441:         if ($curr{'desc'}) {
15442:             if ($curr{'desc'} ne $newdesc) {
15443:                 $changes{'customrole'}{$rolename}{'desc'} = 1;
15444:                 $newsettings{$rolename}{'desc'} = $newdesc;
15445:             }
15446:         } elsif ($newdesc ne '') {
15447:             $changes{'customrole'}{$rolename}{'desc'} = 1;
15448:             $newsettings{$rolename}{'desc'} = $newdesc;
15449:         }
15450:         my $access = $env{'form.'.$prefix.'_access'};
15451:         if (grep(/^\Q$access\E$/,@accesstypes)) {
15452:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = $access;
15453:             if ($access eq 'status') {
15454:                 my @statuses = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_status');
15455:                 if (scalar(@statuses) == 0) {
15456:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'none';
15457:                 } else {
15458:                     my (@shownstatus,$numtypes);
15459:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
15460:                     if (ref($types) eq 'ARRAY') {
15461:                         $numtypes = scalar(@{$types});
15462:                         foreach my $type (sort(@statuses)) {
15463:                             if ($type eq 'default') {
15464:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
15465:                             } elsif (grep(/^\Q$type\E$/,@{$types})) {
15466:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
15467:                                 push(@shownstatus,$usertypes->{$type});
15468:                             }
15469:                         }
15470:                     }
15471:                     if (grep(/^default$/,@statuses)) {
15472:                         push(@shownstatus,$othertitle);
15473:                     }
15474:                     if (scalar(@shownstatus) == 1+$numtypes) {
15475:                         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'all';
15476:                         delete($helphash{'helpsettings'}{'adhoc'}{$rolename}{'status'});
15477:                     } else {
15478:                         $newsettings{$rolename}{'status'} = join(' '.&mt('or').' ',@shownstatus);
15479:                         if (ref($curr{'status'}) eq 'ARRAY') {
15480:                             my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
15481:                             if (@diffs) {
15482:                                 $changes{'customrole'}{$rolename}{$access} = 1;
15483:                             }
15484:                         } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
15485:                             $changes{'customrole'}{$rolename}{$access} = 1;
15486:                         }
15487:                     }
15488:                 }
15489:             } elsif (($access eq 'inc') || ($access eq 'exc')) {
15490:                 my @personnel = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_staff_'.$access);
15491:                 my @newspecstaff;
15492:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
15493:                 foreach my $person (sort(@personnel)) {
15494:                     if ($domhelpdesk{$person}) {
15495:                         push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$person);
15496:                     }
15497:                 }
15498:                 if (ref($curr{$access}) eq 'ARRAY') {
15499:                     my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
15500:                     if (@diffs) {
15501:                         $changes{'customrole'}{$rolename}{$access} = 1;
15502:                     }
15503:                 } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
15504:                     $changes{'customrole'}{$rolename}{$access} = 1;
15505:                 }
15506:                 foreach my $person (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
15507:                     my ($uname,$udom) = split(/:/,$person);
15508:                         push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
15509:                 }
15510:                 $newsettings{$rolename}{$access} = join(', ',sort(@newspecstaff));
15511:             }
15512:         } else {
15513:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}= 'all';
15514:         }
15515:         unless ($curr{'access'} eq $access) {
15516:             $changes{'customrole'}{$rolename}{'access'} = 1;
15517:             $newsettings{$rolename}{'access'} = $lt{$helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}};
15518:         }
15519:     }
15520:     if (@allpos > 0) {
15521:         my $idx = 0;
15522:         foreach my $rolename (@allpos) {
15523:             if ($rolename ne '') {
15524:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{'order'} = $idx;
15525:                 if (ref($current{'adhoc'}) eq 'HASH') {
15526:                     if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
15527:                         if ($current{'adhoc'}{$rolename}{'order'} ne $idx) {
15528:                             $changes{'customrole'}{$rolename}{'order'} = 1;
15529:                             $newsettings{$rolename}{'order'} = $idx+1;
15530:                         }
15531:                     }
15532:                 }
15533:                 $idx ++;
15534:             }
15535:         }
15536:     }
15537:     my $putresult;
15538:     if (keys(%changes) > 0) {
15539:         $putresult = &Apache::lonnet::put_dom('configuration',\%helphash,$dom);
15540:         if ($putresult eq 'ok') {
15541:             if (ref($helphash{'helpsettings'}) eq 'HASH') {
15542:                 $domdefaults{'submitbugs'} = $helphash{'helpsettings'}{'submitbugs'};
15543:                 if (ref($helphash{'helpsettings'}{'adhoc'}) eq 'HASH') {
15544:                     $domdefaults{'adhocroles'} = $helphash{'helpsettings'}{'adhoc'};
15545:                 }
15546:             }
15547:             my $cachetime = 24*60*60;
15548:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
15549:             if (ref($lastactref) eq 'HASH') {
15550:                 $lastactref->{'domdefaults'} = 1;
15551:             }
15552:         } else {
15553:             $errors .= '<li><span class="LC_error">'.
15554:                        &mt('An error occurred storing the settings: [_1]',
15555:                            $putresult).'</span></li>';
15556:         }
15557:     }
15558:     if ((keys(%changes) && ($putresult eq 'ok')) || (keys(%changedprivs))) {
15559:         $resulttext = &mt('Changes made:').'<ul>';
15560:         my (%shownprivs,@levelorder);
15561:         @levelorder = ('c','d','s');
15562:         if ((keys(%changes)) && ($putresult eq 'ok')) {
15563:             foreach my $item (sort(keys(%changes))) {
15564:                 if ($item eq 'submitbugs') {
15565:                     $resulttext .= '<li>'.&mt('Display link to: [_1] set to "'.$offon[$env{'form.'.$item}].'".',
15566:                                               &Apache::loncommon::modal_link('http://bugs.loncapa.org',
15567:                                               &mt('LON-CAPA bug tracker'),600,500)).'</li>';
15568:                 } elsif ($item eq 'customrole') {
15569:                     if (ref($changes{'customrole'}) eq 'HASH') {
15570:                         my @keyorder = ('order','desc','access','status','exc','inc');
15571:                         my %keytext = &Apache::lonlocal::texthash(
15572:                                                                    order  => 'Order',
15573:                                                                    desc   => 'Role description',
15574:                                                                    access => 'Role usage',
15575:                                                                    status => 'Allowed institutional types',
15576:                                                                    exc    => 'Allowed personnel',
15577:                                                                    inc    => 'Disallowed personnel',
15578:                         );
15579:                         foreach my $role (sort(keys(%{$changes{'customrole'}}))) {
15580:                             if (ref($changes{'customrole'}{$role}) eq 'HASH') {
15581:                                 if ($role eq $newrole) {
15582:                                     $resulttext .= '<li>'.&mt('New custom role added: [_1]',
15583:                                                               $role).'<ul>';
15584:                                 } else {
15585:                                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
15586:                                                               $role).'<ul>';
15587:                                 }
15588:                                 foreach my $key (@keyorder) {
15589:                                     if ($changes{'customrole'}{$role}{$key}) {
15590:                                         $resulttext .= '<li>'.&mt("[_1] set to: [_2]",
15591:                                                                   $keytext{$key},$newsettings{$role}{$key}).
15592:                                                        '</li>';
15593:                                     }
15594:                                 }
15595:                                 if (ref($changedprivs{$role}) eq 'HASH') {
15596:                                     $shownprivs{$role} = 1;
15597:                                     $resulttext .= '<li>'.&mt('Privileges set to :').'<ul>';
15598:                                     foreach my $level (@levelorder) {
15599:                                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
15600:                                             next if ($item eq '');
15601:                                             my ($priv) = split(/\&/,$item,2);
15602:                                             if (&Apache::lonnet::plaintext($priv)) {
15603:                                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
15604:                                                 unless ($level eq 'c') {
15605:                                                     $resulttext .= ' ('.$lt{$level}.')';
15606:                                                 }
15607:                                                 $resulttext .= '</li>';
15608:                                             }
15609:                                         }
15610:                                     }
15611:                                     $resulttext .= '</ul>';
15612:                                 }
15613:                                 $resulttext .= '</ul></li>';
15614:                             }
15615:                         }
15616:                     }
15617:                 }
15618:             }
15619:         }
15620:         if (keys(%changedprivs)) {
15621:             foreach my $role (sort(keys(%changedprivs))) {
15622:                 unless ($shownprivs{$role}) {
15623:                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
15624:                                               $role).'<ul>'.
15625:                                    '<li>'.&mt('Privileges set to :').'<ul>';
15626:                     foreach my $level (@levelorder) {
15627:                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
15628:                             next if ($item eq '');
15629:                             my ($priv) = split(/\&/,$item,2);
15630:                             if (&Apache::lonnet::plaintext($priv)) {
15631:                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
15632:                                 unless ($level eq 'c') {
15633:                                     $resulttext .= ' ('.$lt{$level}.')';
15634:                                 }
15635:                                 $resulttext .= '</li>';
15636:                             }
15637:                         }
15638:                     }
15639:                     $resulttext .= '</ul></li></ul></li>';
15640:                 }
15641:             }
15642:         }
15643:         $resulttext .= '</ul>';
15644:     } else {
15645:         $resulttext = &mt('No changes made to help settings');
15646:     }
15647:     if ($errors) {
15648:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
15649:                                     $errors.'</ul>';
15650:     }
15651:     return $resulttext;
15652: }
15653: 
15654: sub modify_coursedefaults {
15655:     my ($dom,$lastactref,%domconfig) = @_;
15656:     my ($resulttext,$errors,%changes,%defaultshash);
15657:     my %defaultchecked = (
15658:                            'uselcmath'       => 'on',
15659:                            'usejsme'         => 'on',
15660:                            'inline_chem'     => 'on',
15661:                          );
15662:     my @toggles = ('uselcmath','usejsme','inline_chem');
15663:     my @numbers = ('anonsurvey_threshold','uploadquota_official','uploadquota_unofficial',
15664:                    'uploadquota_community','uploadquota_textbook','mysqltables_official',
15665:                    'mysqltables_unofficial','mysqltables_community','mysqltables_textbook');
15666:     my @types = ('official','unofficial','community','textbook');
15667:     my %staticdefaults = (
15668:                            anonsurvey_threshold => 10,
15669:                            uploadquota          => 500,
15670:                            postsubmit           => 60,
15671:                            mysqltables          => 172800,
15672:                          );
15673:     my %texoptions = (
15674:                         MathJax  => 'MathJax',
15675:                         mimetex  => &mt('Convert to Images'),
15676:                         tth      => &mt('TeX to HTML'),
15677:                      );
15678:     $defaultshash{'coursedefaults'} = {};
15679: 
15680:     if (ref($domconfig{'coursedefaults'}) ne 'HASH') {
15681:         if ($domconfig{'coursedefaults'} eq '') {
15682:             $domconfig{'coursedefaults'} = {};
15683:         }
15684:     }
15685: 
15686:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
15687:         foreach my $item (@toggles) {
15688:             if ($defaultchecked{$item} eq 'on') {
15689:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
15690:                     ($env{'form.'.$item} eq '0')) {
15691:                     $changes{$item} = 1;
15692:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
15693:                     $changes{$item} = 1;
15694:                 }
15695:             } elsif ($defaultchecked{$item} eq 'off') {
15696:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
15697:                     ($env{'form.'.$item} eq '1')) {
15698:                     $changes{$item} = 1;
15699:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
15700:                     $changes{$item} = 1;
15701:                 }
15702:             }
15703:             $defaultshash{'coursedefaults'}{$item} = $env{'form.'.$item};
15704:         }
15705:         foreach my $item (@numbers) {
15706:             my ($currdef,$newdef);
15707:             $newdef = $env{'form.'.$item};
15708:             if ($item eq 'anonsurvey_threshold') {
15709:                 $currdef = $domconfig{'coursedefaults'}{$item};
15710:                 $newdef =~ s/\D//g;
15711:                 if ($newdef eq '' || $newdef < 1) {
15712:                     $newdef = 1;
15713:                 }
15714:                 $defaultshash{'coursedefaults'}{$item} = $newdef;
15715:             } else {
15716:                 my ($setting,$type) = ($item =~ /^(uploadquota|mysqltables)_(\w+)$/);
15717:                 if (ref($domconfig{'coursedefaults'}{$setting}) eq 'HASH') {
15718:                     $currdef = $domconfig{'coursedefaults'}{$setting}{$type};
15719:                 }
15720:                 $newdef =~ s/[^\w.\-]//g;
15721:                 $defaultshash{'coursedefaults'}{$setting}{$type} = $newdef;
15722:             }
15723:             if ($currdef ne $newdef) {
15724:                 if ($item eq 'anonsurvey_threshold') {
15725:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$item})) {
15726:                         $changes{$item} = 1;
15727:                     }
15728:                 } elsif ($item =~ /^(uploadquota|mysqltables)_/) {
15729:                     my $setting = $1;
15730:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$setting})) {
15731:                         $changes{$setting} = 1;
15732:                     }
15733:                 }
15734:             }
15735:         }
15736:         my $texengine;
15737:         if ($env{'form.texengine'} =~ /^(MathJax|mimetex|tth)$/) {
15738:             $texengine = $env{'form.texengine'};
15739:             my $currdef = $domconfig{'coursedefaults'}{'texengine'};
15740:             if ($currdef eq '') {
15741:                 unless ($texengine eq $Apache::lonnet::deftex) {
15742:                     $changes{'texengine'} = 1;
15743:                 }
15744:             } elsif ($currdef ne $texengine) {
15745:                 $changes{'texengine'} = 1;
15746:             }
15747:         }
15748:         if ($texengine ne '') {
15749:             $defaultshash{'coursedefaults'}{'texengine'} = $texengine;
15750:         }
15751:         my $currclone = $domconfig{'coursedefaults'}{'canclone'};
15752:         my @currclonecode;
15753:         if (ref($currclone) eq 'HASH') {
15754:             if (ref($currclone->{'instcode'}) eq 'ARRAY') {
15755:                 @currclonecode = @{$currclone->{'instcode'}};
15756:             }
15757:         }
15758:         my $newclone;
15759:         if ($env{'form.canclone'} =~ /^(none|domain|instcode)$/) {
15760:             $newclone = $env{'form.canclone'};
15761:         }
15762:         if ($newclone eq 'instcode') {
15763:             my @newcodes = &Apache::loncommon::get_env_multiple('form.clonecode');
15764:             my (%codedefaults,@code_order,@clonecode);
15765:             &Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
15766:                                                     \@code_order);
15767:             foreach my $item (@code_order) {
15768:                 if (grep(/^\Q$item\E$/,@newcodes)) {
15769:                     push(@clonecode,$item);
15770:                 }
15771:             }
15772:             if (@clonecode) {
15773:                 $defaultshash{'coursedefaults'}{'canclone'} = { $newclone => \@clonecode };
15774:                 my @diffs = &Apache::loncommon::compare_arrays(\@currclonecode,\@clonecode);
15775:                 if (@diffs) {
15776:                     $changes{'canclone'} = 1;
15777:                 }
15778:             } else {
15779:                 $newclone eq '';
15780:             }
15781:         } elsif ($newclone ne '') {
15782:             $defaultshash{'coursedefaults'}{'canclone'} = $newclone;
15783:         }
15784:         if ($newclone ne $currclone) {
15785:             $changes{'canclone'} = 1;
15786:         }
15787:         my %credits;
15788:         foreach my $type (@types) {
15789:             unless ($type eq 'community') {
15790:                 $credits{$type} = $env{'form.'.$type.'_credits'};
15791:                 $credits{$type} =~ s/[^\d.]+//g;
15792:             }
15793:         }
15794:         if ((ref($domconfig{'coursedefaults'}{'coursecredits'}) ne 'HASH') &&
15795:             ($env{'form.coursecredits'} eq '1')) {
15796:             $changes{'coursecredits'} = 1;
15797:             foreach my $type (keys(%credits)) {
15798:                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
15799:             }
15800:         } else {
15801:             if ($env{'form.coursecredits'} eq '1') {
15802:                 foreach my $type (@types) {
15803:                     unless ($type eq 'community') {
15804:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type} ne $credits{$type}) {
15805:                             $changes{'coursecredits'} = 1;
15806:                         }
15807:                         $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
15808:                     }
15809:                 }
15810:             } elsif (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
15811:                 foreach my $type (@types) {
15812:                     unless ($type eq 'community') {
15813:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type}) {
15814:                             $changes{'coursecredits'} = 1;
15815:                             last;
15816:                         }
15817:                     }
15818:                 }
15819:             }
15820:         }
15821:         if ($env{'form.postsubmit'} eq '1') {
15822:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'on';
15823:             my %currtimeout;
15824:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
15825:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'off') {
15826:                     $changes{'postsubmit'} = 1;
15827:                 }
15828:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
15829:                     %currtimeout = %{$domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}};
15830:                 }
15831:             } else {
15832:                 $changes{'postsubmit'} = 1;
15833:             }
15834:             foreach my $type (@types) {
15835:                 my $timeout = $env{'form.'.$type.'_timeout'};
15836:                 $timeout =~ s/\D//g;
15837:                 if ($timeout == $staticdefaults{'postsubmit'}) {
15838:                     $timeout = '';
15839:                 } elsif (($timeout eq '') || ($timeout =~ /^0+$/)) {
15840:                     $timeout = '0';
15841:                 }
15842:                 unless ($timeout eq '') {
15843:                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type} = $timeout;
15844:                 }
15845:                 if (exists($currtimeout{$type})) {
15846:                     if ($timeout ne $currtimeout{$type}) {
15847:                         $changes{'postsubmit'} = 1;
15848:                     }
15849:                 } elsif ($timeout ne '') {
15850:                     $changes{'postsubmit'} = 1;
15851:                 }
15852:             }
15853:         } else {
15854:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'off';
15855:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
15856:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'on') {
15857:                     $changes{'postsubmit'} = 1;
15858:                 }
15859:             } else {
15860:                 $changes{'postsubmit'} = 1;
15861:             }
15862:         }
15863:     }
15864:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
15865:                                              $dom);
15866:     if ($putresult eq 'ok') {
15867:         if (keys(%changes) > 0) {
15868:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
15869:             if (($changes{'uploadquota'}) || ($changes{'postsubmit'}) ||
15870:                 ($changes{'coursecredits'}) || ($changes{'uselcmath'}) || ($changes{'usejsme'}) ||
15871:                 ($changes{'canclone'}) || ($changes{'mysqltables'}) || ($changes{'texengine'}) ||
15872:                 ($changes{'inline_chem'})) {
15873:                 foreach my $item ('uselcmath','usejsme','inline_chem','texengine') {
15874:                     if ($changes{$item}) {
15875:                         $domdefaults{$item}=$defaultshash{'coursedefaults'}{$item};
15876:                     }
15877:                 }
15878:                 if ($changes{'coursecredits'}) {
15879:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
15880:                         foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'coursecredits'}})) {
15881:                             $domdefaults{$type.'credits'} =
15882:                                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type};
15883:                         }
15884:                     }
15885:                 }
15886:                 if ($changes{'postsubmit'}) {
15887:                     if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
15888:                         $domdefaults{'postsubmit'} = $defaultshash{'coursedefaults'}{'postsubmit'}{'client'};
15889:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
15890:                             foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}})) {
15891:                                 $domdefaults{$type.'postsubtimeout'} =
15892:                                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
15893:                             }
15894:                         }
15895:                     }
15896:                 }
15897:                 if ($changes{'uploadquota'}) {
15898:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
15899:                         foreach my $type (@types) {
15900:                             $domdefaults{$type.'quota'}=$defaultshash{'coursedefaults'}{'uploadquota'}{$type};
15901:                         }
15902:                     }
15903:                 }
15904:                 if ($changes{'canclone'}) {
15905:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
15906:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
15907:                             my @clonecodes = @{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}};
15908:                             if (@clonecodes) {
15909:                                 $domdefaults{'canclone'} = join('+',@clonecodes);
15910:                             }
15911:                         }
15912:                     } else {
15913:                         $domdefaults{'canclone'}=$defaultshash{'coursedefaults'}{'canclone'};
15914:                     }
15915:                 }
15916:                 my $cachetime = 24*60*60;
15917:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
15918:                 if (ref($lastactref) eq 'HASH') {
15919:                     $lastactref->{'domdefaults'} = 1;
15920:                 }
15921:             }
15922:             $resulttext = &mt('Changes made:').'<ul>';
15923:             foreach my $item (sort(keys(%changes))) {
15924:                 if ($item eq 'uselcmath') {
15925:                     if ($env{'form.'.$item} eq '1') {
15926:                         $resulttext .= '<li>'.&mt('Math preview uses LON-CAPA previewer (javascript), if supported by browser.').'</li>';
15927:                     } else {
15928:                         $resulttext .= '<li>'.&mt('Math preview uses DragMath (Java), if supported by client OS.').'</li>';
15929:                     }
15930:                 } elsif ($item eq 'usejsme') {
15931:                     if ($env{'form.'.$item} eq '1') {
15932:                         $resulttext .= '<li>'.&mt('Molecule editor uses JSME (HTML5), if supported by browser.').'</li>';
15933:                     } else {
15934:                         $resulttext .= '<li>'.&mt('Molecule editor uses JME (Java), if supported by client OS.').'</li>';
15935:                     }
15936:                 } elsif ($item eq 'inline_chem') {
15937:                     if ($env{'form.'.$item} eq '1') {
15938:                         $resulttext .= '<li>'.&mt('Chemical Reaction Response uses inline previewer').'</li>';
15939:                     } else {
15940:                         $resulttext .= '<li>'.&mt('Chemical Reaction Response uses pop-up previewer').'</li>';
15941:                     }
15942:                 } elsif ($item eq 'texengine') {
15943:                     if ($defaultshash{'coursedefaults'}{'texengine'} ne '') {
15944:                         $resulttext .= '<li>'.&mt('Default method to display mathematics set to: "[_1]"',
15945:                                                   $texoptions{$defaultshash{'coursedefaults'}{'texengine'}}).'</li>';
15946:                     }
15947:                 } elsif ($item eq 'anonsurvey_threshold') {
15948:                     $resulttext .= '<li>'.&mt('Responder count required for display of anonymous survey submissions set to [_1].',$defaultshash{'coursedefaults'}{'anonsurvey_threshold'}).'</li>';
15949:                 } elsif ($item eq 'uploadquota') {
15950:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
15951:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded to a course/community via Course Editor set as follows:').'<ul>'.
15952:                                        '<li>'.&mt('Official courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'official'}.'</b>').'</li>'.
15953:                                        '<li>'.&mt('Unofficial courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'unofficial'}.'</b>').'</li>'.
15954:                                        '<li>'.&mt('Textbook courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'textbook'}.'</b>').'</li>'.
15955: 
15956:                                        '<li>'.&mt('Communities: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'community'}.'</b>').'</li>'.
15957:                                        '</ul>'.
15958:                                        '</li>';
15959:                     } else {
15960:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded via Course Editor remains default: [_1] MB',$staticdefaults{'uploadquota'}).'</li>';
15961:                     }
15962:                 } elsif ($item eq 'mysqltables') {
15963:                     if (ref($defaultshash{'coursedefaults'}{'mysqltables'}) eq 'HASH') {
15964:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver').'<ul>'.
15965:                                        '<li>'.&mt('Official courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'official'}.'</b>').'</li>'.
15966:                                        '<li>'.&mt('Unofficial courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'unofficial'}.'</b>').'</li>'.
15967:                                        '<li>'.&mt('Textbook courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'textbook'}.'</b>').'</li>'.
15968:                                        '<li>'.&mt('Communities: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'community'}.'</b>').'</li>'.
15969:                                        '</ul>'.
15970:                                        '</li>';
15971:                     } else {
15972:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver remains default: [_1] s',$staticdefaults{'uploadquota'}).'</li>';
15973:                     }
15974:                 } elsif ($item eq 'postsubmit') {
15975:                     if ($domdefaults{'postsubmit'} eq 'off') {
15976:                         $resulttext .= '<li>'.&mt('Submit button(s) remain enabled on page after student makes submission.');
15977:                     } else {
15978:                         $resulttext .= '<li>'.&mt('Submit button(s) disabled on page after student makes submission').'; ';
15979:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
15980:                             $resulttext .= &mt('durations:').'<ul>';
15981:                             foreach my $type (@types) {
15982:                                 $resulttext .= '<li>';
15983:                                 my $timeout;
15984:                                 if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
15985:                                     $timeout = $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
15986:                                 }
15987:                                 my $display;
15988:                                 if ($timeout eq '0') {
15989:                                     $display = &mt('unlimited');
15990:                                 } elsif ($timeout eq '') {
15991:                                     $display = &mt('[quant,_1,second] (default)',$staticdefaults{'postsubmit'});
15992:                                 } else {
15993:                                     $display = &mt('[quant,_1,second]',$timeout);
15994:                                 }
15995:                                 if ($type eq 'community') {
15996:                                     $resulttext .= &mt('Communities');
15997:                                 } elsif ($type eq 'official') {
15998:                                     $resulttext .= &mt('Official courses');
15999:                                 } elsif ($type eq 'unofficial') {
16000:                                     $resulttext .= &mt('Unofficial courses');
16001:                                 } elsif ($type eq 'textbook') {
16002:                                     $resulttext .= &mt('Textbook courses');
16003:                                 }
16004:                                 $resulttext .= ' -- '.$display.'</li>';
16005:                             }
16006:                             $resulttext .= '</ul>';
16007:                         }
16008:                         $resulttext .= '</li>';
16009:                     }
16010:                 } elsif ($item eq 'coursecredits') {
16011:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
16012:                         if (($domdefaults{'officialcredits'} eq '') &&
16013:                             ($domdefaults{'unofficialcredits'} eq '') &&
16014:                             ($domdefaults{'textbookcredits'} eq '')) {
16015:                             $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
16016:                         } else {
16017:                             $resulttext .= '<li>'.&mt('Student credits can be set per course by a Domain Coordinator, with the following defaults applying:').'<ul>'.
16018:                                            '<li>'.&mt('Official courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'official'}).'</li>'.
16019:                                            '<li>'.&mt('Unofficial courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'unofficial'}).'</li>'.
16020:                                            '<li>'.&mt('Textbook courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'textbook'}).'</li>'.
16021:                                            '</ul>'.
16022:                                            '</li>';
16023:                         }
16024:                     } else {
16025:                         $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
16026:                     }
16027:                 } elsif ($item eq 'canclone') {
16028:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
16029:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
16030:                             my $clonecodes = join(' '.&mt('and').' ',@{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}});
16031:                             $resulttext .= '<li>'.&mt('By default, official courses can be cloned from existing courses with the same: [_1]','<b>'.$clonecodes.'</b>').'</li>';
16032:                         }
16033:                     } elsif ($defaultshash{'coursedefaults'}{'canclone'} eq 'domain') {
16034:                         $resulttext .= '<li>'.&mt('By default, a course requester can clone any course from his/her domain.').'</li>';
16035:                     } else {
16036:                         $resulttext .= '<li>'.&mt('By default, only course owner and coordinators may clone a course.').'</li>';
16037:                     }
16038:                 }
16039:             }
16040:             $resulttext .= '</ul>';
16041:         } else {
16042:             $resulttext = &mt('No changes made to course defaults');
16043:         }
16044:     } else {
16045:         $resulttext = '<span class="LC_error">'.
16046:             &mt('An error occurred: [_1]',$putresult).'</span>';
16047:     }
16048:     return $resulttext;
16049: }
16050: 
16051: sub modify_selfenrollment {
16052:     my ($dom,$lastactref,%domconfig) = @_;
16053:     my ($resulttext,$errors,%changes,%selfenrollhash,%ordered);
16054:     my @types = ('official','unofficial','community','textbook');
16055:     my %titles = &tool_titles();
16056:     my %descs = &Apache::lonuserutils::selfenroll_default_descs();
16057:     ($ordered{'admin'},my $titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
16058:     $ordered{'default'} = ['types','registered','approval','limit'];
16059: 
16060:     my (%roles,%shown,%toplevel);
16061:     $roles{'0'} = &Apache::lonnet::plaintext('dc');
16062: 
16063:     if (ref($domconfig{'selfenrollment'}) ne 'HASH') {
16064:         if ($domconfig{'selfenrollment'} eq '') {
16065:             $domconfig{'selfenrollment'} = {};
16066:         }
16067:     }
16068:     %toplevel = (
16069:                   admin      => 'Configuration Rights',
16070:                   default    => 'Default settings',
16071:                   validation => 'Validation of self-enrollment requests',
16072:                 );
16073:     my ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
16074: 
16075:     if (ref($ordered{'admin'}) eq 'ARRAY') {
16076:         foreach my $item (@{$ordered{'admin'}}) {
16077:             foreach my $type (@types) {
16078:                 if ($env{'form.selfenrolladmin_'.$item.'_'.$type}) {
16079:                     $selfenrollhash{'admin'}{$type}{$item} = 1;
16080:                 } else {
16081:                     $selfenrollhash{'admin'}{$type}{$item} = 0;
16082:                 }
16083:                 if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
16084:                     if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
16085:                         if ($selfenrollhash{'admin'}{$type}{$item} ne
16086:                             $domconfig{'selfenrollment'}{'admin'}{$type}{$item})  {
16087:                             push(@{$changes{'admin'}{$type}},$item);
16088:                         }
16089:                     } else {
16090:                         if (!$selfenrollhash{'admin'}{$type}{$item}) {
16091:                             push(@{$changes{'admin'}{$type}},$item);
16092:                         }
16093:                     }
16094:                 } elsif (!$selfenrollhash{'admin'}{$type}{$item}) {
16095:                     push(@{$changes{'admin'}{$type}},$item);
16096:                 }
16097:             }
16098:         }
16099:     }
16100: 
16101:     foreach my $item (@{$ordered{'default'}}) {
16102:         foreach my $type (@types) {
16103:             my $value = $env{'form.selfenrolldefault_'.$item.'_'.$type};
16104:             if ($item eq 'types') {
16105:                 unless (($value eq 'all') || ($value eq 'dom')) {
16106:                     $value = '';
16107:                 }
16108:             } elsif ($item eq 'registered') {
16109:                 unless ($value eq '1') {
16110:                     $value = 0;
16111:                 }
16112:             } elsif ($item eq 'approval') {
16113:                 unless ($value =~ /^[012]$/) {
16114:                     $value = 0;
16115:                 }
16116:             } else {
16117:                 unless (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
16118:                     $value = 'none';
16119:                 }
16120:             }
16121:             $selfenrollhash{'default'}{$type}{$item} = $value;
16122:             if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
16123:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
16124:                     if ($selfenrollhash{'default'}{$type}{$item} ne
16125:                          $domconfig{'selfenrollment'}{'default'}{$type}{$item})  {
16126:                          push(@{$changes{'default'}{$type}},$item);
16127:                     }
16128:                 } else {
16129:                     push(@{$changes{'default'}{$type}},$item);
16130:                 }
16131:             } else {
16132:                 push(@{$changes{'default'}{$type}},$item);
16133:             }
16134:             if ($item eq 'limit') {
16135:                 if (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
16136:                     $env{'form.selfenrolldefault_cap_'.$type} =~ s/\D//g;
16137:                     if ($env{'form.selfenrolldefault_cap_'.$type} ne '') {
16138:                         $selfenrollhash{'default'}{$type}{'cap'} = $env{'form.selfenrolldefault_cap_'.$type};
16139:                     }
16140:                 } else {
16141:                     $selfenrollhash{'default'}{$type}{'cap'} = '';
16142:                 }
16143:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
16144:                     if ($selfenrollhash{'default'}{$type}{'cap'} ne
16145:                          $domconfig{'selfenrollment'}{'admin'}{$type}{'cap'})  {
16146:                          push(@{$changes{'default'}{$type}},'cap');
16147:                     }
16148:                 } elsif ($selfenrollhash{'default'}{$type}{'cap'} ne '') {
16149:                     push(@{$changes{'default'}{$type}},'cap');
16150:                 }
16151:             }
16152:         }
16153:     }
16154: 
16155:     foreach my $item (@{$itemsref}) {
16156:         if ($item eq 'fields') {
16157:             my @changed;
16158:             @{$selfenrollhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.selfenroll_validation_'.$item);
16159:             if (@{$selfenrollhash{'validation'}{$item}} > 0) {
16160:                 @{$selfenrollhash{'validation'}{$item}} = sort(@{$selfenrollhash{'validation'}{$item}});
16161:             }
16162:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
16163:                 if (ref($domconfig{'selfenrollment'}{'validation'}{$item}) eq 'ARRAY') {
16164:                     @changed = &Apache::loncommon::compare_arrays($selfenrollhash{'validation'}{$item},
16165:                                                                   $domconfig{'selfenrollment'}{'validation'}{$item});
16166:                 } else {
16167:                     @changed = @{$selfenrollhash{'validation'}{$item}};
16168:                 }
16169:             } else {
16170:                 @changed = @{$selfenrollhash{'validation'}{$item}};
16171:             }
16172:             if (@changed) {
16173:                 if ($selfenrollhash{'validation'}{$item}) { 
16174:                     $changes{'validation'}{$item} = join(', ',@{$selfenrollhash{'validation'}{$item}});
16175:                 } else {
16176:                     $changes{'validation'}{$item} = &mt('None');
16177:                 }
16178:             }
16179:         } else {
16180:             $selfenrollhash{'validation'}{$item} = $env{'form.selfenroll_validation_'.$item};
16181:             if ($item eq 'markup') {
16182:                if ($env{'form.selfenroll_validation_'.$item}) {
16183:                    $env{'form.selfenroll_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
16184:                }
16185:             }
16186:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
16187:                 if ($domconfig{'selfenrollment'}{'validation'}{$item} ne $selfenrollhash{'validation'}{$item}) {
16188:                     $changes{'validation'}{$item} = $selfenrollhash{'validation'}{$item};
16189:                 }
16190:             }
16191:         }
16192:     }
16193: 
16194:     my $putresult = &Apache::lonnet::put_dom('configuration',{'selfenrollment' => \%selfenrollhash},
16195:                                              $dom);
16196:     if ($putresult eq 'ok') {
16197:         if (keys(%changes) > 0) {
16198:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
16199:             $resulttext = &mt('Changes made:').'<ul>';
16200:             foreach my $key ('admin','default','validation') {
16201:                 if (ref($changes{$key}) eq 'HASH') {
16202:                     $resulttext .= '<li>'.$toplevel{$key}.'<ul>';
16203:                     if ($key eq 'validation') {
16204:                         foreach my $item (@{$itemsref}) {
16205:                             if (exists($changes{$key}{$item})) {
16206:                                 if ($item eq 'markup') {
16207:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
16208:                                                               '<br /><pre>'.$changes{$key}{$item}.'</pre>').'</li>';
16209:                                 } else {  
16210:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
16211:                                                               '<b>'.$changes{$key}{$item}.'</b>').'</li>';
16212:                                 }
16213:                             }
16214:                         }
16215:                     } else {
16216:                         foreach my $type (@types) {
16217:                             if ($type eq 'community') {
16218:                                 $roles{'1'} = &mt('Community personnel');
16219:                             } else {
16220:                                 $roles{'1'} = &mt('Course personnel');
16221:                             }
16222:                             if (ref($changes{$key}{$type}) eq 'ARRAY') {
16223:                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') {
16224:                                     if ($key eq 'admin') {
16225:                                         my @mgrdc = ();
16226:                                         if (ref($ordered{$key}) eq 'ARRAY') {
16227:                                             foreach my $item (@{$ordered{'admin'}}) {
16228:                                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') { 
16229:                                                     if ($selfenrollhash{$key}{$type}{$item} eq '0') {
16230:                                                         push(@mgrdc,$item);
16231:                                                     }
16232:                                                 }
16233:                                             }
16234:                                             if (@mgrdc) {
16235:                                                 $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
16236:                                             } else {
16237:                                                 delete($domdefaults{$type.'selfenrolladmdc'});
16238:                                             }
16239:                                         }
16240:                                     } else {
16241:                                         if (ref($ordered{$key}) eq 'ARRAY') {
16242:                                             foreach my $item (@{$ordered{$key}}) {
16243:                                                 if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
16244:                                                     $domdefaults{$type.'selfenroll'.$item} =
16245:                                                         $selfenrollhash{$key}{$type}{$item};
16246:                                                 }
16247:                                             }
16248:                                         }
16249:                                     }
16250:                                 }
16251:                                 $resulttext .= '<li>'.$titles{$type}.'<ul>';
16252:                                 foreach my $item (@{$ordered{$key}}) {
16253:                                     if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
16254:                                         $resulttext .= '<li>';
16255:                                         if ($key eq 'admin') {
16256:                                             $resulttext .= &mt('[_1] -- management by: [_2]',$titlesref->{$item},
16257:                                                                '<b>'.$roles{$selfenrollhash{'admin'}{$type}{$item}}.'</b>');
16258:                                         } else {
16259:                                             $resulttext .= &mt('[_1] set to: [_2]',$titlesref->{$item},
16260:                                                                '<b>'.$descs{$item}{$selfenrollhash{'default'}{$type}{$item}}.'</b>');
16261:                                         }
16262:                                         $resulttext .= '</li>';
16263:                                     }
16264:                                 }
16265:                                 $resulttext .= '</ul></li>';
16266:                             }
16267:                         }
16268:                         $resulttext .= '</ul></li>'; 
16269:                     }
16270:                 }
16271:             }
16272:             if ((exists($changes{'admin'})) || (exists($changes{'default'}))) {
16273:                 my $cachetime = 24*60*60;
16274:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
16275:                 if (ref($lastactref) eq 'HASH') {
16276:                     $lastactref->{'domdefaults'} = 1;
16277:                 }
16278:             }
16279:             $resulttext .= '</ul>';
16280:         } else {
16281:             $resulttext = &mt('No changes made to self-enrollment settings');
16282:         }
16283:     } else {
16284:         $resulttext = '<span class="LC_error">'.
16285:             &mt('An error occurred: [_1]',$putresult).'</span>';
16286:     }
16287:     return $resulttext;
16288: }
16289: 
16290: sub modify_wafproxy {
16291:     my ($dom,$action,$lastactref,%domconfig) = @_;
16292:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
16293:     my (%othercontrol,%canset,%values,%curralias,%currsaml,%currvalue,@warnings,
16294:         %wafproxy,%changes,%expirecache,%expiresaml);
16295:     foreach my $server (sort(keys(%servers))) {
16296:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
16297:         if ($serverhome eq $server) {
16298:             my $serverdom = &Apache::lonnet::host_domain($server);
16299:             if ($serverdom eq $dom) {
16300:                 $canset{$server} = 1;
16301:             }
16302:         }
16303:     }
16304:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
16305:         %{$values{$dom}} = ();
16306:         if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
16307:             %curralias = %{$domconfig{'wafproxy'}{'alias'}};
16308:         }
16309:         if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
16310:             %currsaml = %{$domconfig{'wafproxy'}{'saml'}};
16311:         }
16312:         foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
16313:             $currvalue{$item} = $domconfig{'wafproxy'}{$item};
16314:         }
16315:     }
16316:     my $output;
16317:     if (keys(%canset)) {
16318:         %{$wafproxy{'alias'}} = ();
16319:         %{$wafproxy{'saml'}} = ();
16320:         foreach my $key (sort(keys(%canset))) {
16321:             if ($env{'form.wafproxy_'.$dom}) {
16322:                 $wafproxy{'alias'}{$key} = $env{'form.wafproxy_alias_'.$key};
16323:                 $wafproxy{'alias'}{$key} =~ s/^\s+|\s+$//g;
16324:                 if ($wafproxy{'alias'}{$key} ne $curralias{$key}) {
16325:                     $changes{'alias'} = 1;
16326:                 }
16327:                 if ($env{'form.wafproxy_alias_saml_'.$key}) {
16328:                     $wafproxy{'saml'}{$key} = 1;
16329:                 }
16330:                 if ($wafproxy{'saml'}{$key} ne $currsaml{$key}) {
16331:                     $changes{'saml'} = 1;
16332:                 }
16333:             } else {
16334:                 $wafproxy{'alias'}{$key} = '';
16335:                 $wafproxy{'saml'}{$key} = '';
16336:                 if ($curralias{$key}) {
16337:                     $changes{'alias'} = 1;
16338:                 }
16339:                 if ($currsaml{$key}) {
16340:                     $changes{'saml'} = 1;
16341:                 }
16342:             }
16343:             if ($wafproxy{'alias'}{$key} eq '') {
16344:                 if ($curralias{$key}) {
16345:                     $expirecache{$key} = 1;
16346:                 }
16347:                 delete($wafproxy{'alias'}{$key});
16348:             }
16349:             if ($wafproxy{'saml'}{$key} eq '') {
16350:                 if ($currsaml{$key}) {
16351:                     $expiresaml{$key} = 1;
16352:                 }
16353:                 delete($wafproxy{'saml'}{$key});
16354:             }
16355:         }
16356:         unless (keys(%{$wafproxy{'alias'}})) {
16357:             delete($wafproxy{'alias'});
16358:         }
16359:         unless (keys(%{$wafproxy{'saml'}})) {
16360:             delete($wafproxy{'saml'});
16361:         }
16362:         # Localization for values in %warn occurs in &mt() calls separately.
16363:         my %warn = (
16364:                      trusted => 'trusted IP range(s)',
16365:                      vpnint => 'internal IP range(s) for VPN sessions(s)',
16366:                      vpnext => 'IP range(s) for backend WAF connections',
16367:                    );
16368:         foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
16369:             my $possible = $env{'form.wafproxy_'.$item};
16370:             $possible =~ s/^\s+|\s+$//g;
16371:             if ($possible ne '') {
16372:                 if ($item eq 'remoteip') {
16373:                     if ($possible =~ /^[mhn]$/) {
16374:                         $wafproxy{$item} = $possible;
16375:                     }
16376:                 } elsif ($item eq 'ipheader') {
16377:                     if ($wafproxy{'remoteip'} eq 'h') {
16378:                         $wafproxy{$item} = $possible;
16379:                     }
16380:                 } elsif ($item eq 'sslopt') {
16381:                     if ($possible =~ /^0|1$/) {
16382:                         $wafproxy{$item} = $possible;
16383:                     }
16384:                 } else {
16385:                     my (@ok,$count);
16386:                     if (($item eq 'vpnint') || ($item eq 'vpnext')) {
16387:                         unless ($env{'form.wafproxy_vpnaccess'}) {
16388:                             $possible = '';
16389:                         }
16390:                     } elsif ($item eq 'trusted') {
16391:                         unless ($wafproxy{'remoteip'} eq 'h') {
16392:                             $possible = '';
16393:                         }
16394:                     }
16395:                     unless ($possible eq '') {
16396:                         $possible =~ s/[\r\n]+/\s/g;
16397:                         $possible =~ s/\s*-\s*/-/g;
16398:                         $possible =~ s/\s+/,/g;
16399:                         $possible =~ s/,+/,/g;
16400:                     }
16401:                     $count = 0;
16402:                     if ($possible ne '') {
16403:                         foreach my $poss (split(/\,/,$possible)) {
16404:                             $count ++;
16405:                             $poss = &validate_ip_pattern($poss);
16406:                             if ($poss ne '') {
16407:                                 push(@ok,$poss);
16408:                             }
16409:                         }
16410:                         my $diff = $count - scalar(@ok);
16411:                         if ($diff) {
16412:                             push(@warnings,'<li>'.
16413:                                  &mt('[quant,_1,IP] invalid and excluded from saved value for [_2]',
16414:                                      $diff,$warn{$item}).
16415:                                  '</li>');
16416:                         }
16417:                         if (@ok) {
16418:                             my @cidr_list;
16419:                             foreach my $item (@ok) {
16420:                                 @cidr_list = &Net::CIDR::cidradd($item,@cidr_list);
16421:                             }
16422:                             $wafproxy{$item} = join(',',@cidr_list);
16423:                         }
16424:                     }
16425:                 }
16426:                 if ($wafproxy{$item} ne $currvalue{$item}) {
16427:                     $changes{$item} = 1;
16428:                 }
16429:             } elsif ($currvalue{$item}) {
16430:                 $changes{$item} = 1;
16431:             }
16432:         }
16433:     } else {
16434:         if (keys(%curralias)) {
16435:             $changes{'alias'} = 1;
16436:         }
16437:         if (keys(%currsaml)) {
16438:             $changes{'saml'} = 1;
16439:         }
16440:         if (keys(%currvalue)) {
16441:             foreach my $key (keys(%currvalue)) {
16442:                 $changes{$key} = 1;
16443:             }
16444:         }
16445:     }
16446:     if (keys(%changes)) {
16447:         my %defaultshash = (
16448:                               wafproxy => \%wafproxy,
16449:                            );
16450:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
16451:                                                  $dom);
16452:         if ($putresult eq 'ok') {
16453:             my $cachetime = 24*60*60;
16454:             my (%domdefaults,$updatedomdefs);
16455:             foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
16456:                 if ($changes{$item}) {
16457:                     unless ($updatedomdefs) {
16458:                         %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
16459:                         $updatedomdefs = 1;
16460:                     }
16461:                     if ($wafproxy{$item}) {
16462:                         $domdefaults{'waf_'.$item} = $wafproxy{$item};
16463:                     } elsif (exists($domdefaults{'waf_'.$item})) {
16464:                         delete($domdefaults{'waf_'.$item});
16465:                     }
16466:                 }
16467:             }
16468:             if ($updatedomdefs) {
16469:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
16470:                 if (ref($lastactref) eq 'HASH') {
16471:                     $lastactref->{'domdefaults'} = 1;
16472:                 }
16473:             }
16474:             if ((exists($wafproxy{'alias'})) || (keys(%expirecache))) {
16475:                 my %updates = %expirecache;
16476:                 foreach my $key (keys(%expirecache)) {
16477:                     &Apache::lonnet::devalidate_cache_new('proxyalias',$key);
16478:                 }
16479:                 if (ref($wafproxy{'alias'}) eq 'HASH') {
16480:                     my $cachetime = 24*60*60;
16481:                     foreach my $key (keys(%{$wafproxy{'alias'}})) {
16482:                         $updates{$key} = 1;
16483:                         &Apache::lonnet::do_cache_new('proxyalias',$key,$wafproxy{'alias'}{$key},
16484:                                                       $cachetime);
16485:                     }
16486:                 }
16487:                 if (ref($lastactref) eq 'HASH') {
16488:                     $lastactref->{'proxyalias'} = \%updates;
16489:                 }
16490:             }
16491:             if ((exists($wafproxy{'saml'})) || (keys(%expiresaml))) {
16492:                 my %samlupdates = %expiresaml;
16493:                 foreach my $key (keys(%expiresaml)) {
16494:                     &Apache::lonnet::devalidate_cache_new('proxysaml',$key);
16495:                 }
16496:                 if (ref($wafproxy{'saml'}) eq 'HASH') {
16497:                     my $cachetime = 24*60*60;
16498:                     foreach my $key (keys(%{$wafproxy{'saml'}})) {
16499:                         $samlupdates{$key} = 1;
16500:                         &Apache::lonnet::do_cache_new('proxysaml',$key,$wafproxy{'saml'}{$key},
16501:                                                       $cachetime);
16502:                     }
16503:                 }
16504:                 if (ref($lastactref) eq 'HASH') {
16505:                     $lastactref->{'proxysaml'} = \%samlupdates;
16506:                 }
16507:             }
16508:             $output = &mt('Changes were made to Web Application Firewall/Reverse Proxy').'<ul>';
16509:             foreach my $item ('alias','saml','remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
16510:                 if ($changes{$item}) {
16511:                     if ($item eq 'alias') {
16512:                         my $numaliased = 0;
16513:                         if (ref($wafproxy{'alias'}) eq 'HASH') {
16514:                             my $shown;
16515:                             if (keys(%{$wafproxy{'alias'}})) {
16516:                                 foreach my $server (sort(keys(%{$wafproxy{'alias'}}))) {
16517:                                     $shown .= '<li>'.&mt('[_1] aliased by [_2]',
16518:                                                          &Apache::lonnet::hostname($server),
16519:                                                          $wafproxy{'alias'}{$server}).'</li>';
16520:                                     $numaliased ++;
16521:                                 }
16522:                                 if ($numaliased) {
16523:                                     $output .= '<li>'.&mt('Aliases for hostnames set to: [_1]',
16524:                                                           '<ul>'.$shown.'</ul>').'</li>';
16525:                                 }
16526:                             }
16527:                         }
16528:                         unless ($numaliased) {
16529:                             $output .= '<li>'.&mt('Aliases deleted for hostnames').'</li>';
16530:                         }
16531:                     } elsif ($item eq 'saml') {
16532:                         my $shown;
16533:                         if (ref($wafproxy{'saml'}) eq 'HASH') {
16534:                             if (keys(%{$wafproxy{'saml'}})) {
16535:                                 $shown = join(', ',sort(keys(%{$wafproxy{'saml'}})));
16536:                             }
16537:                         }
16538:                         if ($shown) {
16539:                             $output .= '<li>'.&mt('Alias used by SSO Auth for: [_1]',
16540:                                                   $shown).'</li>';
16541:                         } else {
16542:                             $output .= '<li>'.&mt('No alias used for SSO Auth').'</li>';
16543:                         }
16544:                     } else {
16545:                         if ($item eq 'remoteip') {
16546:                             my %ip_methods = &remoteip_methods();
16547:                             if ($wafproxy{$item} =~ /^[mh]$/) {
16548:                                 $output .= '<li>'.&mt("Method for determining user's IP set to: [_1]",
16549:                                                       $ip_methods{$wafproxy{$item}}).'</li>';
16550:                             } else {
16551:                                 if (($env{'form.wafproxy_'.$dom}) && (ref($wafproxy{'alias'}) eq 'HASH')) {
16552:                                     $output .= '<li>'.&mt("No method in use to get user's real IP (will report IP used by WAF).").
16553:                                                '</li>';
16554:                                 } else {
16555:                                     $output .= '<li>'.&mt('WAF/Reverse Proxy not in use').'</li>';
16556:                                 }
16557:                             }
16558:                         } elsif ($item eq 'ipheader') {
16559:                             if ($wafproxy{$item}) {
16560:                                 $output .= '<li>'.&mt('Request header with remote IP set to: [_1]',
16561:                                                       $wafproxy{$item}).'</li>';
16562:                             } else {
16563:                                 $output .= '<li>'.&mt('Request header with remote IP deleted').'</li>';
16564:                             }
16565:                         } elsif ($item eq 'trusted') {
16566:                             if ($wafproxy{$item}) {
16567:                                 $output .= '<li>'.&mt('Trusted IP range(s) set to: [_1]',
16568:                                                       $wafproxy{$item}).'</li>';
16569:                             } else {
16570:                                 $output .= '<li>'.&mt('Trusted IP range(s) deleted').'</li>';
16571:                             }
16572:                         } elsif ($item eq 'vpnint') {
16573:                             if ($wafproxy{$item}) {
16574:                                 $output .= '<li>'.&mt('Internal IP Range(s) for VPN sessions set to: [_1]',
16575:                                                        $wafproxy{$item}).'</li>';
16576:                             } else {
16577:                                 $output .= '<li>'.&mt('Internal IP Range(s) for VPN sessions deleted').'</li>';
16578:                             }
16579:                         } elsif ($item eq 'vpnext') {
16580:                             if ($wafproxy{$item}) {
16581:                                 $output .= '<li>'.&mt('IP Range(s) for backend WAF connections set to: [_1]',
16582:                                                        $wafproxy{$item}).'</li>';
16583:                             } else {
16584:                                 $output .= '<li>'.&mt('IP Range(s) for backend WAF connections deleted').'</li>';
16585:                             }
16586:                         } elsif ($item eq 'sslopt') {
16587:                             if ($wafproxy{$item}) {
16588:                                 $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>';
16589:                             } else {
16590:                                 $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>';
16591:                             }
16592:                         }
16593:                     }
16594:                 }
16595:             }
16596:         } else {
16597:             $output = '<span class="LC_error">'.
16598:                       &mt('An error occurred: [_1]',$putresult).'</span>';
16599:         }
16600:     } elsif (keys(%canset)) {
16601:         $output = &mt('No changes made to Web Application Firewall/Reverse Proxy settings');
16602:     }
16603:     if (@warnings) {
16604:         $output .= '<br />'.&mt('Warnings:').'<ul>'.
16605:                        join("\n",@warnings).'</ul>';
16606:     }
16607:     return $output;
16608: }
16609: 
16610: sub validate_ip_pattern {
16611:     my ($pattern) = @_;
16612:     if ($pattern =~ /^([^-]+)\-([^-]+)$/) {
16613:         my ($start,$end) = ($1,$2);
16614:         if ((&Net::CIDR::cidrvalidate($start)) && (&Net::CIDR::cidrvalidate($end))) {
16615:             if (($start !~ m{/}) && ($end !~ m{/})) {
16616:                 return $start.'-'.$end;
16617:             }
16618:         }
16619:     } elsif ($pattern ne '') {
16620:         $pattern = &Net::CIDR::cidrvalidate($pattern);
16621:         if ($pattern ne '') {
16622:             return $pattern;
16623:         }
16624:     }
16625:     return;
16626: }
16627: 
16628: sub modify_usersessions {
16629:     my ($dom,$lastactref,%domconfig) = @_;
16630:     my @hostingtypes = ('version','excludedomain','includedomain');
16631:     my @offloadtypes = ('primary','default');
16632:     my %types = (
16633:                   remote => \@hostingtypes,
16634:                   hosted => \@hostingtypes,
16635:                   spares => \@offloadtypes,
16636:                 );
16637:     my @prefixes = ('remote','hosted','spares');
16638:     my @lcversions = &Apache::lonnet::all_loncaparevs();
16639:     my (%by_ip,%by_location,@intdoms);
16640:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location);
16641:     my @locations = sort(keys(%by_location));
16642:     my (%defaultshash,%changes);
16643:     foreach my $prefix (@prefixes) {
16644:         $defaultshash{'usersessions'}{$prefix} = {};
16645:     }
16646:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
16647:     my $resulttext;
16648:     my %iphost = &Apache::lonnet::get_iphost();
16649:     foreach my $prefix (@prefixes) {
16650:         next if ($prefix eq 'spares');
16651:         foreach my $type (@{$types{$prefix}}) {
16652:             my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
16653:             if ($type eq 'version') {
16654:                 my $value = $env{'form.'.$prefix.'_'.$type};
16655:                 my $okvalue;
16656:                 if ($value ne '') {
16657:                     if (grep(/^\Q$value\E$/,@lcversions)) {
16658:                         $okvalue = $value;
16659:                     }
16660:                 }
16661:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
16662:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
16663:                         if ($domconfig{'usersessions'}{$prefix}{$type} ne '') {
16664:                             if ($inuse == 0) {
16665:                                 $changes{$prefix}{$type} = 1;
16666:                             } else {
16667:                                 if ($okvalue ne $domconfig{'usersessions'}{$prefix}{$type}) {
16668:                                     $changes{$prefix}{$type} = 1;
16669:                                 }
16670:                                 if ($okvalue ne '') {
16671:                                     $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
16672:                                 } 
16673:                             }
16674:                         } else {
16675:                             if (($inuse == 1) && ($okvalue ne '')) {
16676:                                 $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
16677:                                 $changes{$prefix}{$type} = 1;
16678:                             }
16679:                         }
16680:                     } else {
16681:                         if (($inuse == 1) && ($okvalue ne '')) {
16682:                             $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
16683:                             $changes{$prefix}{$type} = 1;
16684:                         }
16685:                     }
16686:                 } else {
16687:                     if (($inuse == 1) && ($okvalue ne '')) {
16688:                         $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
16689:                         $changes{$prefix}{$type} = 1;
16690:                     }
16691:                 }
16692:             } else {
16693:                 my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
16694:                 my @okvals;
16695:                 foreach my $val (@vals) {
16696:                     if ($val =~ /:/) {
16697:                         my @items = split(/:/,$val);
16698:                         foreach my $item (@items) {
16699:                             if (ref($by_location{$item}) eq 'ARRAY') {
16700:                                 push(@okvals,$item);
16701:                             }
16702:                         }
16703:                     } else {
16704:                         if (ref($by_location{$val}) eq 'ARRAY') {
16705:                             push(@okvals,$val);
16706:                         }
16707:                     }
16708:                 }
16709:                 @okvals = sort(@okvals);
16710:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
16711:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
16712:                         if (ref($domconfig{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
16713:                             if ($inuse == 0) {
16714:                                 $changes{$prefix}{$type} = 1; 
16715:                             } else {
16716:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
16717:                                 my @changed = &Apache::loncommon::compare_arrays($domconfig{'usersessions'}{$prefix}{$type},$defaultshash{'usersessions'}{$prefix}{$type});
16718:                                 if (@changed > 0) {
16719:                                     $changes{$prefix}{$type} = 1;
16720:                                 }
16721:                             }
16722:                         } else {
16723:                             if ($inuse == 1) {
16724:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
16725:                                 $changes{$prefix}{$type} = 1;
16726:                             }
16727:                         } 
16728:                     } else {
16729:                         if ($inuse == 1) {
16730:                             $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
16731:                             $changes{$prefix}{$type} = 1;
16732:                         }
16733:                     }
16734:                 } else {
16735:                     if ($inuse == 1) {
16736:                         $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
16737:                         $changes{$prefix}{$type} = 1;
16738:                     }
16739:                 }
16740:             }
16741:         }
16742:     }
16743: 
16744:     my @alldoms = &Apache::lonnet::all_domains();
16745:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
16746:     my %spareid = &current_offloads_to($dom,$domconfig{'usersessions'},\%servers);
16747:     my $savespares;
16748: 
16749:     foreach my $lonhost (sort(keys(%servers))) {
16750:         my $serverhomeID =
16751:             &Apache::lonnet::get_server_homeID($servers{$lonhost});
16752:         my $serverhostname = &Apache::lonnet::hostname($lonhost);
16753:         $defaultshash{'usersessions'}{'spares'}{$lonhost} = {};
16754:         my %spareschg;
16755:         foreach my $type (@{$types{'spares'}}) {
16756:             my @okspares;
16757:             my @checked = &Apache::loncommon::get_env_multiple('form.spare_'.$type.'_'.$lonhost);
16758:             foreach my $server (@checked) {
16759:                 if (&Apache::lonnet::hostname($server) ne '') {
16760:                     unless (&Apache::lonnet::hostname($server) eq $serverhostname) {
16761:                         unless (grep(/^\Q$server\E$/,@okspares)) {
16762:                             push(@okspares,$server);
16763:                         }
16764:                     }
16765:                 }
16766:             }
16767:             my $new = $env{'form.newspare_'.$type.'_'.$lonhost};
16768:             my $newspare;
16769:             if (($new ne '') && (&Apache::lonnet::hostname($new))) {
16770:                 unless (&Apache::lonnet::hostname($new) eq $serverhostname) {
16771:                     $newspare = $new;
16772:                 }
16773:             }
16774:             my @spares;
16775:             if (($newspare ne '') && (!grep(/^\Q$newspare\E$/,@okspares))) {
16776:                 @spares = sort(@okspares,$newspare);
16777:             } else {
16778:                 @spares = sort(@okspares);
16779:             }
16780:             $defaultshash{'usersessions'}{'spares'}{$lonhost}{$type} = \@spares;
16781:             if (ref($spareid{$lonhost}) eq 'HASH') {
16782:                 if (ref($spareid{$lonhost}{$type}) eq 'ARRAY') {
16783:                     my @diffs = &Apache::loncommon::compare_arrays($spareid{$lonhost}{$type},\@spares);
16784:                     if (@diffs > 0) {
16785:                         $spareschg{$type} = 1;
16786:                     }
16787:                 }
16788:             }
16789:         }
16790:         if (keys(%spareschg) > 0) {
16791:             $changes{'spares'}{$lonhost} = \%spareschg;
16792:         }
16793:     }
16794:     $defaultshash{'usersessions'}{'offloadnow'} = {};
16795:     $defaultshash{'usersessions'}{'offloadoth'} = {};
16796:     my @offloadnow = &Apache::loncommon::get_env_multiple('form.offloadnow');
16797:     my @okoffload;
16798:     if (@offloadnow) {
16799:         foreach my $server (@offloadnow) {
16800:             if (&Apache::lonnet::hostname($server) ne '') {
16801:                 unless (grep(/^\Q$server\E$/,@okoffload)) {
16802:                     push(@okoffload,$server);
16803:                 }
16804:             }
16805:         }
16806:         if (@okoffload) {
16807:             foreach my $lonhost (@okoffload) {
16808:                 $defaultshash{'usersessions'}{'offloadnow'}{$lonhost} = 1;
16809:             }
16810:         }
16811:     }
16812:     my @offloadoth = &Apache::loncommon::get_env_multiple('form.offloadoth');
16813:     my @okoffloadoth;
16814:     if (@offloadoth) {
16815:         foreach my $server (@offloadoth) {
16816:             if (&Apache::lonnet::hostname($server) ne '') {
16817:                 unless (grep(/^\Q$server\E$/,@okoffloadoth)) {
16818:                     push(@okoffloadoth,$server);
16819:                 }
16820:             }
16821:         }
16822:         if (@okoffloadoth) {
16823:             foreach my $lonhost (@okoffloadoth) {
16824:                 $defaultshash{'usersessions'}{'offloadoth'}{$lonhost} = 1;
16825:             }
16826:         }
16827:     }
16828:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
16829:         if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
16830:             if (ref($changes{'spares'}) eq 'HASH') {
16831:                 if (keys(%{$changes{'spares'}}) > 0) {
16832:                     $savespares = 1;
16833:                 }
16834:             }
16835:         } else {
16836:             $savespares = 1;
16837:         }
16838:         foreach my $offload ('offloadnow','offloadoth') {
16839:             if (ref($domconfig{'usersessions'}{$offload}) eq 'HASH') {
16840:                 foreach my $lonhost (keys(%{$domconfig{'usersessions'}{$offload}})) {
16841:                     unless ($defaultshash{'usersessions'}{$offload}{$lonhost}) {
16842:                         $changes{$offload} = 1;
16843:                         last;
16844:                     }
16845:                 }
16846:                 unless ($changes{$offload}) {
16847:                     foreach my $lonhost (keys(%{$defaultshash{'usersessions'}{$offload}})) {
16848:                         unless ($domconfig{'usersessions'}{$offload}{$lonhost}) {
16849:                             $changes{$offload} = 1;
16850:                             last;
16851:                         }
16852:                     }
16853:                 }
16854:             } else {
16855:                 if (($offload eq 'offloadnow') && (@okoffload)) {
16856:                      $changes{'offloadnow'} = 1;
16857:                 }
16858:                 if (($offload eq 'offloadoth') && (@okoffloadoth)) {
16859:                     $changes{'offloadoth'} = 1;
16860:                 }
16861:             }
16862:         }
16863:     } else {
16864:         if (@okoffload) {
16865:             $changes{'offloadnow'} = 1;
16866:         }
16867:         if (@okoffloadoth) {
16868:             $changes{'offloadoth'} = 1;
16869:         }
16870:     }
16871:     my $nochgmsg = &mt('No changes made to settings for user session hosting/offloading.');
16872:     if ((keys(%changes) > 0) || ($savespares)) {
16873:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
16874:                                                  $dom);
16875:         if ($putresult eq 'ok') {
16876:             if (ref($defaultshash{'usersessions'}) eq 'HASH') {
16877:                 if (ref($defaultshash{'usersessions'}{'remote'}) eq 'HASH') {
16878:                     $domdefaults{'remotesessions'} = $defaultshash{'usersessions'}{'remote'};
16879:                 }
16880:                 if (ref($defaultshash{'usersessions'}{'hosted'}) eq 'HASH') {
16881:                     $domdefaults{'hostedsessions'} = $defaultshash{'usersessions'}{'hosted'};
16882:                 }
16883:                 if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
16884:                     $domdefaults{'offloadnow'} = $defaultshash{'usersessions'}{'offloadnow'};
16885:                 }
16886:                 if (ref($defaultshash{'usersessions'}{'offloadoth'}) eq 'HASH') {
16887:                     $domdefaults{'offloadoth'} = $defaultshash{'usersessions'}{'offloadoth'};
16888:                 }
16889:             }
16890:             my $cachetime = 24*60*60;
16891:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
16892:             &Apache::lonnet::do_cache_new('usersessions',$dom,$defaultshash{'usersessions'},3600);
16893:             if (ref($lastactref) eq 'HASH') {
16894:                 $lastactref->{'domdefaults'} = 1;
16895:                 $lastactref->{'usersessions'} = 1;
16896:             }
16897:             if (keys(%changes) > 0) {
16898:                 my %lt = &usersession_titles();
16899:                 $resulttext = &mt('Changes made:').'<ul>';
16900:                 foreach my $prefix (@prefixes) {
16901:                     if (ref($changes{$prefix}) eq 'HASH') {
16902:                         $resulttext .= '<li>'.$lt{$prefix}.'<ul>';
16903:                         if ($prefix eq 'spares') {
16904:                             if (ref($changes{$prefix}) eq 'HASH') {
16905:                                 foreach my $lonhost (sort(keys(%{$changes{$prefix}}))) {
16906:                                     $resulttext .= '<li><b>'.$lonhost.'</b> ';
16907:                                     my $lonhostdom = &Apache::lonnet::host_domain($lonhost);
16908:                                     my $cachekey = &escape('spares').':'.&escape($lonhostdom);
16909:                                     &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
16910:                                     if (ref($changes{$prefix}{$lonhost}) eq 'HASH') {
16911:                                         foreach my $type (@{$types{$prefix}}) {
16912:                                             if ($changes{$prefix}{$lonhost}{$type}) {
16913:                                                 my $offloadto = &mt('None');
16914:                                                 if (ref($defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}) eq 'ARRAY') {
16915:                                                     if (@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}} > 0) {   
16916:                                                         $offloadto = join(', ',@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}});
16917:                                                     }
16918:                                                 }
16919:                                                 $resulttext .= &mt('[_1] set to: [_2].','<i>'.$lt{$type}.'</i>',$offloadto).('&nbsp;'x3);
16920:                                             }
16921:                                         }
16922:                                     }
16923:                                     $resulttext .= '</li>';
16924:                                 }
16925:                             }
16926:                         } else {
16927:                             foreach my $type (@{$types{$prefix}}) {
16928:                                 if (defined($changes{$prefix}{$type})) {
16929:                                     my $newvalue;
16930:                                     if (ref($defaultshash{'usersessions'}) eq 'HASH') {
16931:                                         if (ref($defaultshash{'usersessions'}{$prefix})) {
16932:                                             if ($type eq 'version') {
16933:                                                 $newvalue = $defaultshash{'usersessions'}{$prefix}{$type};
16934:                                             } elsif (ref($defaultshash{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
16935:                                                 if (@{$defaultshash{'usersessions'}{$prefix}{$type}} > 0) {
16936:                                                     $newvalue = join(', ',@{$defaultshash{'usersessions'}{$prefix}{$type}});
16937:                                                 }
16938:                                             }
16939:                                         }
16940:                                     }
16941:                                     if ($newvalue eq '') {
16942:                                         if ($type eq 'version') {
16943:                                             $resulttext .= '<li>'.&mt('[_1] set to: off',$lt{$type}).'</li>';
16944:                                         } else {
16945:                                             $resulttext .= '<li>'.&mt('[_1] set to: none',$lt{$type}).'</li>';
16946:                                         }
16947:                                     } else {
16948:                                         if ($type eq 'version') {
16949:                                             $newvalue .= ' '.&mt('(or later)'); 
16950:                                         }
16951:                                         $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$lt{$type},$newvalue).'</li>';
16952:                                     }
16953:                                 }
16954:                             }
16955:                         }
16956:                         $resulttext .= '</ul>';
16957:                     }
16958:                 }
16959:                 if ($changes{'offloadnow'}) {
16960:                     if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
16961:                         if (keys(%{$defaultshash{'usersessions'}{'offloadnow'}}) > 0) {
16962:                             $resulttext .= '<li>'.&mt('Switch any active user on next access, for server(s):').'<ul>';
16963:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadnow'}}))) {
16964:                                 $resulttext .= '<li>'.$lonhost.'</li>';
16965:                             }
16966:                             $resulttext .= '</ul>';
16967:                         } else {
16968:                             $resulttext .= '<li>'.&mt('No servers now set to switch any active user on next access.');
16969:                         }
16970:                     } else {
16971:                         $resulttext .= '<li>'.&mt('No servers now set to switch any active user on next access.').'</li>';
16972:                     }
16973:                 }
16974:                 if ($changes{'offloadoth'}) {
16975:                     if (ref($defaultshash{'usersessions'}{'offloadoth'}) eq 'HASH') {
16976:                         if (keys(%{$defaultshash{'usersessions'}{'offloadoth'}}) > 0) {
16977:                             $resulttext .= '<li>'.&mt('Switch other institutions on next access, for server(s):').'<ul>';
16978:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadoth'}}))) {
16979:                                 $resulttext .= '<li>'.$lonhost.'</li>';
16980:                             }
16981:                             $resulttext .= '</ul>';
16982:                         } else {
16983:                             $resulttext .= '<li>'.&mt('No servers now set to switch other institutions on next access.');
16984:                         }
16985:                     } else {
16986:                         $resulttext .= '<li>'.&mt('No servers now set to switch other institutions on next access.').'</li>';
16987:                     }
16988:                 }
16989:                 $resulttext .= '</ul>';
16990:             } else {
16991:                 $resulttext = $nochgmsg;
16992:             }
16993:         } else {
16994:             $resulttext = '<span class="LC_error">'.
16995:                           &mt('An error occurred: [_1]',$putresult).'</span>';
16996:         }
16997:     } else {
16998:         $resulttext = $nochgmsg;
16999:     }
17000:     return $resulttext;
17001: }
17002: 
17003: sub modify_loadbalancing {
17004:     my ($dom,%domconfig) = @_;
17005:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
17006:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
17007:     my ($othertitle,$usertypes,$types) =
17008:         &Apache::loncommon::sorted_inst_types($dom);
17009:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
17010:     my %libraryservers = &Apache::lonnet::get_servers($dom,'library');
17011:     my @sparestypes = ('primary','default');
17012:     my %typetitles = &sparestype_titles();
17013:     my $resulttext;
17014:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
17015:     if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
17016:         %existing = %{$domconfig{'loadbalancing'}};
17017:     }
17018:     &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
17019:                               \%currtargets,\%currrules,\%currcookies);
17020:     my ($saveloadbalancing,%defaultshash,%changes);
17021:     my ($alltypes,$othertypes,$titles) =
17022:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
17023:     my %ruletitles = &offloadtype_text();
17024:     my @deletions = &Apache::loncommon::get_env_multiple('form.loadbalancing_delete');
17025:     for (my $i=0; $i<$env{'form.loadbalancing_total'}; $i++) {
17026:         my $balancer = $env{'form.loadbalancing_lonhost_'.$i};
17027:         if ($balancer eq '') {
17028:             next;
17029:         }
17030:         if (!exists($servers{$balancer})) {
17031:             if (exists($currbalancer{$balancer})) {
17032:                 push(@{$changes{'delete'}},$balancer);
17033:             }
17034:             next;
17035:         }
17036:         if ((@deletions > 0) && (grep(/^\Q$i\E$/,@deletions))) {
17037:             push(@{$changes{'delete'}},$balancer);
17038:             next;
17039:         }
17040:         if (!exists($currbalancer{$balancer})) {
17041:             push(@{$changes{'add'}},$balancer);
17042:         }
17043:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'} = [];
17044:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'default'} = [];
17045:         $defaultshash{'loadbalancing'}{$balancer}{'rules'} = {};
17046:         unless (ref($domconfig{'loadbalancing'}) eq 'HASH') {
17047:             $saveloadbalancing = 1;
17048:         }
17049:         foreach my $sparetype (@sparestypes) {
17050:             my @targets = &Apache::loncommon::get_env_multiple('form.loadbalancing_target_'.$i.'_'.$sparetype);
17051:             my @offloadto;
17052:             foreach my $target (@targets) {
17053:                 if (($servers{$target}) && ($target ne $balancer)) {
17054:                     if ($sparetype eq 'default') {
17055:                         if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}) eq 'ARRAY') {
17056:                             next if (grep(/^\Q$target\E$/,@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}}));
17057:                         }
17058:                     }
17059:                     unless(grep(/^\Q$target\E$/,@offloadto)) {
17060:                         push(@offloadto,$target);
17061:                     }
17062:                 }
17063:             }
17064:             if ($env{'form.loadbalancing_target_'.$i.'_hosthere'} eq $sparetype) {
17065:                 unless(grep(/^\Q$balancer\E$/,@offloadto)) {
17066:                     push(@offloadto,$balancer);
17067:                 }
17068:             }
17069:             $defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype} = \@offloadto;
17070:         }
17071:         if ($env{'form.loadbalancing_cookie_'.$i}) {
17072:             $defaultshash{'loadbalancing'}{$balancer}{'cookie'} = 1;
17073:             if (exists($currbalancer{$balancer})) {
17074:                 unless ($currcookies{$balancer}) {
17075:                     $changes{'curr'}{$balancer}{'cookie'} = 1;
17076:                 }
17077:             }
17078:         } elsif (exists($currbalancer{$balancer})) {
17079:             if ($currcookies{$balancer}) {
17080:                 $changes{'curr'}{$balancer}{'cookie'} = 1;
17081:             }
17082:         }
17083:         if (ref($currtargets{$balancer}) eq 'HASH') {
17084:             foreach my $sparetype (@sparestypes) {
17085:                 if (ref($currtargets{$balancer}{$sparetype}) eq 'ARRAY') {
17086:                     my @targetdiffs = &Apache::loncommon::compare_arrays($currtargets{$balancer}{$sparetype},$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype});
17087:                     if (@targetdiffs > 0) {
17088:                         $changes{'curr'}{$balancer}{'targets'} = 1;
17089:                     }
17090:                 } elsif (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
17091:                     if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
17092:                         $changes{'curr'}{$balancer}{'targets'} = 1;
17093:                     }
17094:                 }
17095:             }
17096:         } else {
17097:             if (ref($defaultshash{'loadbalancing'}{$balancer}) eq 'HASH') {
17098:                 foreach my $sparetype (@sparestypes) {
17099:                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
17100:                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
17101:                             $changes{'curr'}{$balancer}{'targets'} = 1;
17102:                         }
17103:                     }
17104:                 }
17105:             }
17106:         }
17107:         my $ishomedom;
17108:         if (&Apache::lonnet::host_domain($balancer) eq $dom) {
17109:             $ishomedom = 1;
17110:         }
17111:         if (ref($alltypes) eq 'ARRAY') {
17112:             foreach my $type (@{$alltypes}) {
17113:                 my $rule;
17114:                 unless ((($type eq '_LC_external') || ($type eq '_LC_internetdom')) &&
17115:                          (!$ishomedom)) {
17116:                     $rule = $env{'form.loadbalancing_rules_'.$i.'_'.$type};
17117:                 }
17118:                 if ($rule eq 'specific') {
17119:                     my $specifiedhost = $env{'form.loadbalancing_singleserver_'.$i.'_'.$type};
17120:                     if (exists($servers{$specifiedhost})) {
17121:                         $rule = $specifiedhost;
17122:                     }
17123:                 }
17124:                 $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type} = $rule;
17125:                 if (ref($currrules{$balancer}) eq 'HASH') {
17126:                     if ($rule ne $currrules{$balancer}{$type}) {
17127:                         $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
17128:                     }
17129:                 } elsif ($rule ne '') {
17130:                     $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
17131:                 }
17132:             }
17133:         }
17134:     }
17135:     my $nochgmsg = &mt('No changes made to Load Balancer settings.');
17136:     if ((keys(%changes) > 0) || ($saveloadbalancing)) {
17137:         unless (ref($defaultshash{'loadbalancing'}) eq 'HASH') {
17138:             $defaultshash{'loadbalancing'} = {};
17139:         }
17140:         my $putresult = &Apache::lonnet::put_dom('configuration',
17141:                                                  \%defaultshash,$dom);
17142:         if ($putresult eq 'ok') {
17143:             if (keys(%changes) > 0) {
17144:                 my %toupdate;
17145:                 if (ref($changes{'delete'}) eq 'ARRAY') {
17146:                     foreach my $balancer (sort(@{$changes{'delete'}})) {
17147:                         $resulttext .= '<li>'.&mt('Load Balancing discontinued for: [_1]',$balancer).'</li>';
17148:                         $toupdate{$balancer} = 1;
17149:                     }
17150:                 }
17151:                 if (ref($changes{'add'}) eq 'ARRAY') {
17152:                     foreach my $balancer (sort(@{$changes{'add'}})) {
17153:                         $resulttext .= '<li>'.&mt('Load Balancing enabled for: [_1]',$balancer);
17154:                         $toupdate{$balancer} = 1;
17155:                     }
17156:                 }
17157:                 if (ref($changes{'curr'}) eq 'HASH') {
17158:                     foreach my $balancer (sort(keys(%{$changes{'curr'}}))) {
17159:                         $toupdate{$balancer} = 1;
17160:                         if (ref($changes{'curr'}{$balancer}) eq 'HASH') {
17161:                             if ($changes{'curr'}{$balancer}{'targets'}) {
17162:                                 my %offloadstr;
17163:                                 foreach my $sparetype (@sparestypes) {
17164:                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
17165:                                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
17166:                                             $offloadstr{$sparetype} = join(', ',@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
17167:                                         }
17168:                                     }
17169:                                 }
17170:                                 if (keys(%offloadstr) == 0) {
17171:                                     $resulttext .= '<li>'.&mt("Servers to which Load Balance server offloads set to 'None', by default").'</li>';
17172:                                 } else {
17173:                                     my $showoffload;
17174:                                     foreach my $sparetype (@sparestypes) {
17175:                                         $showoffload .= '<i>'.$typetitles{$sparetype}.'</i>:&nbsp;';
17176:                                         if (defined($offloadstr{$sparetype})) {
17177:                                             $showoffload .= $offloadstr{$sparetype};
17178:                                         } else {
17179:                                             $showoffload .= &mt('None');
17180:                                         }
17181:                                         $showoffload .= ('&nbsp;'x3);
17182:                                     }
17183:                                     $resulttext .= '<li>'.&mt('By default, Load Balancer: [_1] set to offload to - [_2]',$balancer,$showoffload).'</li>';
17184:                                 }
17185:                             }
17186:                         }
17187:                         if (ref($changes{'curr'}{$balancer}{'rules'}) eq 'HASH') {
17188:                             if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH')) {
17189:                                 foreach my $type (@{$alltypes}) {
17190:                                     if ($changes{'curr'}{$balancer}{'rules'}{$type}) {
17191:                                         my $rule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
17192:                                         my $balancetext;
17193:                                         if ($rule eq '') {
17194:                                             $balancetext =  $ruletitles{'default'};
17195:                                         } elsif (($rule eq 'homeserver') || ($rule eq 'externalbalancer') ||
17196:                                                  ($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
17197:                                             if (($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
17198:                                                 foreach my $sparetype (@sparestypes) {
17199:                                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
17200:                                                         map { $toupdate{$_} = 1; } (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
17201:                                                     }
17202:                                                 }
17203:                                                 foreach my $item (@{$alltypes}) {
17204:                                                     next if ($item =~  /^_LC_ipchange/);
17205:                                                     my $hasrule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$item};
17206:                                                     if ($hasrule eq 'homeserver') {
17207:                                                         map { $toupdate{$_} = 1; } (keys(%libraryservers));
17208:                                                     } else {
17209:                                                         unless (($hasrule eq 'default') || ($hasrule eq 'none') || ($hasrule eq 'externalbalancer')) {
17210:                                                             if ($servers{$hasrule}) {
17211:                                                                 $toupdate{$hasrule} = 1;
17212:                                                             }
17213:                                                         }
17214:                                                     }
17215:                                                 }
17216:                                                 if (($rule eq 'balancer') || ($rule eq 'offloadedto')) {
17217:                                                     $balancetext =  $ruletitles{$rule};
17218:                                                 } else {
17219:                                                     my $receiver = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
17220:                                                     $balancetext = $ruletitles{'particular'}.' '.$receiver;
17221:                                                     if ($receiver) {
17222:                                                         $toupdate{$receiver};
17223:                                                     }
17224:                                                 }
17225:                                             } else {
17226:                                                 $balancetext =  $ruletitles{$rule};
17227:                                             }
17228:                                         } else {
17229:                                             $balancetext = &mt('offload to [_1]',$defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type});
17230:                                         }
17231:                                         $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- balancing for [_2] set to - "[_3]"',$balancer,$titles->{$type},$balancetext).'</li>';
17232:                                     }
17233:                                 }
17234:                             }
17235:                         }
17236:                         if ($changes{'curr'}{$balancer}{'cookie'}) {
17237:                             if ($currcookies{$balancer}) {
17238:                                 $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- cookie use disabled',
17239:                                                           $balancer).'</li>';
17240:                             } else {
17241:                                 $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- cookie use enabled',
17242:                                                           $balancer).'</li>';
17243:                             }
17244:                         }
17245:                     }
17246:                 }
17247:                 if (keys(%toupdate)) {
17248:                     my %thismachine;
17249:                     my $updatedhere;
17250:                     my $cachetime = 60*60*24;
17251:                     map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
17252:                     foreach my $lonhost (keys(%toupdate)) {
17253:                         if ($thismachine{$lonhost}) {
17254:                             unless ($updatedhere) {
17255:                                 &Apache::lonnet::do_cache_new('loadbalancing',$dom,
17256:                                                               $defaultshash{'loadbalancing'},
17257:                                                               $cachetime);
17258:                                 $updatedhere = 1;
17259:                             }
17260:                         } else {
17261:                             my $cachekey = &escape('loadbalancing').':'.&escape($dom);
17262:                             &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
17263:                         }
17264:                     }
17265:                 }
17266:                 if ($resulttext ne '') {
17267:                     $resulttext = &mt('Changes made:').'<ul>'.$resulttext.'</ul>';
17268:                 } else {
17269:                     $resulttext = $nochgmsg;
17270:                 }
17271:             } else {
17272:                 $resulttext = $nochgmsg;
17273:             }
17274:         } else {
17275:             $resulttext = '<span class="LC_error">'.
17276:                           &mt('An error occurred: [_1]',$putresult).'</span>';
17277:         }
17278:     } else {
17279:         $resulttext = $nochgmsg;
17280:     }
17281:     return $resulttext;
17282: }
17283: 
17284: sub recurse_check {
17285:     my ($chkcats,$categories,$depth,$name) = @_;
17286:     if (ref($chkcats->[$depth]{$name}) eq 'ARRAY') {
17287:         my $chg = 0;
17288:         for (my $j=0; $j<@{$chkcats->[$depth]{$name}}; $j++) {
17289:             my $category = $chkcats->[$depth]{$name}[$j];
17290:             my $item;
17291:             if ($category eq '') {
17292:                 $chg ++;
17293:             } else {
17294:                 my $deeper = $depth + 1;
17295:                 $item = &escape($category).':'.&escape($name).':'.$depth;
17296:                 if ($chg) {
17297:                     $categories->{$item} -= $chg;
17298:                 }
17299:                 &recurse_check($chkcats,$categories,$deeper,$category);
17300:                 $deeper --;
17301:             }
17302:         }
17303:     }
17304:     return;
17305: }
17306: 
17307: sub recurse_cat_deletes {
17308:     my ($item,$coursecategories,$deletions) = @_;
17309:     my ($deleted,$container,$depth) = map { &unescape($_); } split(/:/,$item);
17310:     my $subdepth = $depth + 1;
17311:     if (ref($coursecategories) eq 'HASH') {
17312:         foreach my $subitem (keys(%{$coursecategories})) {
17313:             my ($child,$parent,$itemdepth) = map { &unescape($_); } split(/:/,$subitem);
17314:             if (($parent eq $deleted) && ($itemdepth == $subdepth)) {
17315:                 delete($coursecategories->{$subitem});
17316:                 $deletions->{$subitem} = 1;
17317:                 &recurse_cat_deletes($subitem,$coursecategories,$deletions);
17318:             }
17319:         }
17320:     }
17321:     return;
17322: }
17323: 
17324: sub active_dc_picker {
17325:     my ($dom,$numinrow,$inputtype,$name,%currhash) = @_;
17326:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
17327:     my @domcoord = keys(%domcoords);
17328:     if (keys(%currhash)) {
17329:         foreach my $dc (keys(%currhash)) {
17330:             unless (exists($domcoords{$dc})) {
17331:                 push(@domcoord,$dc);
17332:             }
17333:         }
17334:     }
17335:     @domcoord = sort(@domcoord);
17336:     my $numdcs = scalar(@domcoord);
17337:     my $rows = 0;
17338:     my $table;
17339:     if ($numdcs > 1) {
17340:         $table = '<table>';
17341:         for (my $i=0; $i<@domcoord; $i++) {
17342:             my $rem = $i%($numinrow);
17343:             if ($rem == 0) {
17344:                 if ($i > 0) {
17345:                     $table .= '</tr>';
17346:                 }
17347:                 $table .= '<tr>';
17348:                 $rows ++;
17349:             }
17350:             my $check = '';
17351:             if ($inputtype eq 'radio') {
17352:                 if (keys(%currhash) == 0) {
17353:                     if (!$i) {
17354:                         $check = ' checked="checked"';
17355:                     }
17356:                 } elsif (exists($currhash{$domcoord[$i]})) {
17357:                     $check = ' checked="checked"';
17358:                 }
17359:             } else {
17360:                 if (exists($currhash{$domcoord[$i]})) {
17361:                     $check = ' checked="checked"';
17362:                 }
17363:             }
17364:             if ($i == @domcoord - 1) {
17365:                 my $colsleft = $numinrow - $rem;
17366:                 if ($colsleft > 1) {
17367:                     $table .= '<td class="LC_left_item" colspan="'.$colsleft.'">';
17368:                 } else {
17369:                     $table .= '<td class="LC_left_item">';
17370:                 }
17371:             } else {
17372:                 $table .= '<td class="LC_left_item">';
17373:             }
17374:             my ($dcname,$dcdom) = split(':',$domcoord[$i]);
17375:             my $user = &Apache::loncommon::plainname($dcname,$dcdom);
17376:             $table .= '<span class="LC_nobreak"><label>'.
17377:                       '<input type="'.$inputtype.'" name="'.$name.'"'.
17378:                       ' value="'.$domcoord[$i].'"'.$check.' />'.$user;
17379:             if ($user ne $dcname.':'.$dcdom) {
17380:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
17381:             }
17382:             $table .= '</label></span></td>';
17383:         }
17384:         $table .= '</tr></table>';
17385:     } elsif ($numdcs == 1) {
17386:         my ($dcname,$dcdom) = split(':',$domcoord[0]);
17387:         my $user = &Apache::loncommon::plainname($dcname,$dcdom);
17388:         if ($inputtype eq 'radio') {
17389:             $table = '<input type="hidden" name="'.$name.'" value="'.$domcoord[0].'" />'.$user;
17390:             if ($user ne $dcname.':'.$dcdom) {
17391:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
17392:             }
17393:         } else {
17394:             my $check;
17395:             if (exists($currhash{$domcoord[0]})) {
17396:                 $check = ' checked="checked"';
17397:             }
17398:             $table = '<span class="LC_nobreak"><label>'.
17399:                      '<input type="checkbox" name="'.$name.'" '.
17400:                      'value="'.$domcoord[0].'"'.$check.' />'.$user;
17401:             if ($user ne $dcname.':'.$dcdom) {
17402:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
17403:             }
17404:             $table .= '</label></span>';
17405:             $rows ++;
17406:         }
17407:     }
17408:     return ($numdcs,$table,$rows);
17409: }
17410: 
17411: sub usersession_titles {
17412:     return &Apache::lonlocal::texthash(
17413:                hosted => 'Hosting of sessions for users from other domains on servers in this domain',
17414:                remote => 'Hosting of sessions for users in this domain on servers in other domains',
17415:                spares => 'Servers offloaded to, when busy',
17416:                version => 'LON-CAPA version requirement',
17417:                excludedomain => 'Allow all, but exclude specific domains',
17418:                includedomain => 'Deny all, but include specific domains',
17419:                primary => 'Primary (checked first)',
17420:                default => 'Default',
17421:            );
17422: }
17423: 
17424: sub id_for_thisdom {
17425:     my (%servers) = @_;
17426:     my %altids;
17427:     foreach my $server (keys(%servers)) {
17428:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
17429:         if ($serverhome ne $server) {
17430:             $altids{$serverhome} = $server;
17431:         }
17432:     }
17433:     return %altids;
17434: }
17435: 
17436: sub count_servers {
17437:     my ($currbalancer,%servers) = @_;
17438:     my (@spares,$numspares);
17439:     foreach my $lonhost (sort(keys(%servers))) {
17440:         next if ($currbalancer eq $lonhost);
17441:         push(@spares,$lonhost);
17442:     }
17443:     if ($currbalancer) {
17444:         $numspares = scalar(@spares);
17445:     } else {
17446:         $numspares = scalar(@spares) - 1;
17447:     }
17448:     return ($numspares,@spares);
17449: }
17450: 
17451: sub lonbalance_targets_js {
17452:     my ($dom,$types,$servers,$settings) = @_;
17453:     my $select = &mt('Select');
17454:     my ($alltargets,$allishome,$allinsttypes,@alltypes);
17455:     if (ref($servers) eq 'HASH') {
17456:         $alltargets = join("','",sort(keys(%{$servers})));
17457:         my @homedoms;
17458:         foreach my $server (sort(keys(%{$servers}))) {
17459:             if (&Apache::lonnet::host_domain($server) eq $dom) {
17460:                 push(@homedoms,'1');
17461:             } else {
17462:                 push(@homedoms,'0');
17463:             }
17464:         }
17465:         $allishome = join("','",@homedoms);
17466:     }
17467:     if (ref($types) eq 'ARRAY') {
17468:         if (@{$types} > 0) {
17469:             @alltypes = @{$types};
17470:         }
17471:     }
17472:     push(@alltypes,'default','_LC_adv','_LC_author','_LC_internetdom','_LC_external');
17473:     $allinsttypes = join("','",@alltypes);
17474:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
17475:     if (ref($settings) eq 'HASH') {
17476:         %existing = %{$settings};
17477:     }
17478:     &get_loadbalancers_config($servers,\%existing,\%currbalancer,
17479:                               \%currtargets,\%currrules,\%currcookies);
17480:     my $balancers = join("','",sort(keys(%currbalancer)));
17481:     return <<"END";
17482: 
17483: <script type="text/javascript">
17484: // <![CDATA[
17485: 
17486: currBalancers = new Array('$balancers');
17487: 
17488: function toggleTargets(balnum) {
17489:     var lonhostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
17490:     var prevhostitem = document.getElementById('loadbalancing_prevlonhost_'+balnum);
17491:     var balancer = lonhostitem.options[lonhostitem.selectedIndex].value;
17492:     var prevbalancer = prevhostitem.value;
17493:     var baltotal = document.getElementById('loadbalancing_total').value;
17494:     prevhostitem.value = balancer;
17495:     if (prevbalancer != '') {
17496:         var prevIdx = currBalancers.indexOf(prevbalancer);
17497:         if (prevIdx != -1) {
17498:             currBalancers.splice(prevIdx,1);
17499:         }
17500:     }
17501:     if (balancer == '') {
17502:         hideSpares(balnum);
17503:     } else {
17504:         var currIdx = currBalancers.indexOf(balancer);
17505:         if (currIdx == -1) {
17506:             currBalancers.push(balancer);
17507:         }
17508:         var homedoms = new Array('$allishome');
17509:         var ishomedom = homedoms[lonhostitem.selectedIndex];
17510:         showSpares(balancer,ishomedom,balnum);
17511:     }
17512:     balancerChange(balnum,baltotal,'change',prevbalancer,balancer);
17513:     return;
17514: }
17515: 
17516: function showSpares(balancer,ishomedom,balnum) {
17517:     var alltargets = new Array('$alltargets');
17518:     var insttypes = new Array('$allinsttypes');
17519:     var offloadtypes = new Array('primary','default');
17520: 
17521:     document.getElementById('loadbalancing_targets_'+balnum).style.display='block';
17522:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='none';
17523:  
17524:     for (var i=0; i<offloadtypes.length; i++) {
17525:         var count = 0;
17526:         for (var j=0; j<alltargets.length; j++) {
17527:             if (alltargets[j] != balancer) {
17528:                 var item = document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+count);
17529:                 item.value = alltargets[j];
17530:                 item.style.textAlign='left';
17531:                 item.style.textFace='normal';
17532:                 document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+count).innerHTML = alltargets[j];
17533:                 if (currBalancers.indexOf(alltargets[j]) == -1) {
17534:                     item.disabled = '';
17535:                 } else {
17536:                     item.disabled = 'disabled';
17537:                     item.checked = false;
17538:                 }
17539:                 count ++;
17540:             }
17541:         }
17542:     }
17543:     for (var k=0; k<insttypes.length; k++) {
17544:         if ((insttypes[k] == '_LC_external') || (insttypes[k] == '_LC_internetdom')) {
17545:             if (ishomedom == 1) {
17546:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
17547:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
17548:             } else {
17549:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
17550:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
17551:             }
17552:         } else {
17553:             document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
17554:             document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
17555:         }
17556:         if ((insttypes[k] != '_LC_external') && 
17557:             ((insttypes[k] != '_LC_internetdom') ||
17558:              ((insttypes[k] == '_LC_internetdom') && (ishomedom == 1)))) {
17559:             var item = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]);
17560:             item.options.length = 0;
17561:             item.options[0] = new Option("","",true,true);
17562:             var idx = 0;
17563:             for (var m=0; m<alltargets.length; m++) {
17564:                 if ((currBalancers.indexOf(alltargets[m]) == -1) && (alltargets[m] != balancer)) {
17565:                     idx ++;
17566:                     item.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
17567:                 }
17568:             }
17569:         }
17570:     }
17571:     return;
17572: }
17573: 
17574: function hideSpares(balnum) {
17575:     var alltargets = new Array('$alltargets');
17576:     var insttypes = new Array('$allinsttypes');
17577:     var offloadtypes = new Array('primary','default');
17578: 
17579:     document.getElementById('loadbalancing_targets_'+balnum).style.display='none';
17580:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='block';
17581: 
17582:     var total = alltargets.length - 1;
17583:     for (var i=0; i<offloadtypes; i++) {
17584:         for (var j=0; j<total; j++) {
17585:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).checked = false;
17586:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).value = '';
17587:            document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+j).innerHTML = '';
17588:         }
17589:     }
17590:     for (var k=0; k<insttypes.length; k++) {
17591:         document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
17592:         document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
17593:         if (insttypes[k] != '_LC_external') {
17594:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).length = 0;
17595:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).options[0] = new Option("","",true,true);
17596:         }
17597:     }
17598:     return;
17599: }
17600: 
17601: function checkOffloads(item,balnum,type) {
17602:     var alltargets = new Array('$alltargets');
17603:     var offloadtypes = new Array('primary','default');
17604:     if (item.checked) {
17605:         var total = alltargets.length - 1;
17606:         var other;
17607:         if (type == offloadtypes[0]) {
17608:             other = offloadtypes[1];
17609:         } else {
17610:             other = offloadtypes[0];
17611:         }
17612:         for (var i=0; i<total; i++) {
17613:             var server = document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).value;
17614:             if (server == item.value) {
17615:                 if (document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked) {
17616:                     document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked = false;
17617:                 }
17618:             }
17619:         }
17620:     }
17621:     return;
17622: }
17623: 
17624: function singleServerToggle(balnum,type) {
17625:     var offloadtoSelIdx = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex;
17626:     if (offloadtoSelIdx == 0) {
17627:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_0').checked = true;
17628:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
17629: 
17630:     } else {
17631:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_2').checked = true;
17632:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
17633:     }
17634:     return;
17635: }
17636: 
17637: function balanceruleChange(formname,balnum,type) {
17638:     if (type == '_LC_external') {
17639:         return;
17640:     }
17641:     var typesRules = getIndicesByName(formname,'loadbalancing_rules_'+balnum+'_'+type);
17642:     for (var i=0; i<typesRules.length; i++) {
17643:         if (formname.elements[typesRules[i]].checked) {
17644:             if (formname.elements[typesRules[i]].value != 'specific') {
17645:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex = 0;
17646:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
17647:             } else {
17648:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
17649:             }
17650:         }
17651:     }
17652:     return;
17653: }
17654: 
17655: function balancerDeleteChange(balnum) {
17656:     var hostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
17657:     var baltotal = document.getElementById('loadbalancing_total').value;
17658:     var addtarget;
17659:     var removetarget;
17660:     var action = 'delete';
17661:     if (document.getElementById('loadbalancing_delete_'+balnum)) {
17662:         var lonhost = hostitem.value;
17663:         var currIdx = currBalancers.indexOf(lonhost);
17664:         if (document.getElementById('loadbalancing_delete_'+balnum).checked) {
17665:             if (currIdx != -1) {
17666:                 currBalancers.splice(currIdx,1);
17667:             }
17668:             addtarget = lonhost;
17669:         } else {
17670:             if (currIdx == -1) {
17671:                 currBalancers.push(lonhost);
17672:             }
17673:             removetarget = lonhost;
17674:             action = 'undelete';
17675:         }
17676:         balancerChange(balnum,baltotal,action,addtarget,removetarget);
17677:     }
17678:     return;
17679: }
17680: 
17681: function balancerChange(balnum,baltotal,action,addtarget,removetarget) {
17682:     if (baltotal > 1) {
17683:         var offloadtypes = new Array('primary','default');
17684:         var alltargets = new Array('$alltargets');
17685:         var insttypes = new Array('$allinsttypes');
17686:         for (var i=0; i<baltotal; i++) {
17687:             if (i != balnum) {
17688:                 for (var j=0; j<offloadtypes.length; j++) {
17689:                     var total = alltargets.length - 1;
17690:                     for (var k=0; k<total; k++) {
17691:                         var serveritem = document.getElementById('loadbalancing_target_'+i+'_'+offloadtypes[j]+'_'+k);
17692:                         var server = serveritem.value;
17693:                         if ((action == 'delete') || (action == 'change' && addtarget != ''))  {
17694:                             if (server == addtarget) {
17695:                                 serveritem.disabled = '';
17696:                             }
17697:                         }
17698:                         if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
17699:                             if (server == removetarget) {
17700:                                 serveritem.disabled = 'disabled';
17701:                                 serveritem.checked = false;
17702:                             }
17703:                         }
17704:                     }
17705:                 }
17706:                 for (var j=0; j<insttypes.length; j++) {
17707:                     if (insttypes[j] != '_LC_external') {
17708:                         if (document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j])) {
17709:                             var singleserver = document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j]);
17710:                             var currSel = singleserver.selectedIndex;
17711:                             var currVal = singleserver.options[currSel].value;
17712:                             if ((action == 'delete') || (action == 'change' && addtarget != '')) {
17713:                                 var numoptions = singleserver.options.length;
17714:                                 var needsnew = 1;
17715:                                 for (var k=0; k<numoptions; k++) {
17716:                                     if (singleserver.options[k] == addtarget) {
17717:                                         needsnew = 0;
17718:                                         break;
17719:                                     }
17720:                                 }
17721:                                 if (needsnew == 1) {
17722:                                     singleserver.options[numoptions] = new Option(addtarget,addtarget,false,false);
17723:                                 }
17724:                             }
17725:                             if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
17726:                                 singleserver.options.length = 0;
17727:                                 if ((currVal) && (currVal != removetarget)) {
17728:                                     singleserver.options[0] = new Option("","",false,false);
17729:                                 } else {
17730:                                     singleserver.options[0] = new Option("","",true,true);
17731:                                 }
17732:                                 var idx = 0;
17733:                                 for (var m=0; m<alltargets.length; m++) {
17734:                                     if (currBalancers.indexOf(alltargets[m]) == -1) {
17735:                                         idx ++;
17736:                                         if (currVal == alltargets[m]) {
17737:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],true,true);
17738:                                         } else {
17739:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
17740:                                         }
17741:                                     }
17742:                                 }
17743:                             }
17744:                         }
17745:                     }
17746:                 }
17747:             }
17748:         }
17749:     }
17750:     return;
17751: }
17752: 
17753: // ]]>
17754: </script>
17755: 
17756: END
17757: }
17758: 
17759: sub new_spares_js {
17760:     my @sparestypes = ('primary','default');
17761:     my $types = join("','",@sparestypes);
17762:     my $select = &mt('Select');
17763:     return <<"END";
17764: 
17765: <script type="text/javascript">
17766: // <![CDATA[
17767: 
17768: function updateNewSpares(formname,lonhost) {
17769:     var types = new Array('$types');
17770:     var include = new Array();
17771:     var exclude = new Array();
17772:     for (var i=0; i<types.length; i++) {
17773:         var spareboxes = getIndicesByName(formname,'spare_'+types[i]+'_'+lonhost);
17774:         for (var j=0; j<spareboxes.length; j++) {
17775:             if (formname.elements[spareboxes[j]].checked) {
17776:                 exclude.push(formname.elements[spareboxes[j]].value);
17777:             } else {
17778:                 include.push(formname.elements[spareboxes[j]].value);
17779:             }
17780:         }
17781:     }
17782:     for (var i=0; i<types.length; i++) {
17783:         var newSpare = document.getElementById('newspare_'+types[i]+'_'+lonhost);
17784:         var selIdx = newSpare.selectedIndex;
17785:         var currnew = newSpare.options[selIdx].value;
17786:         var okSpares = new Array();
17787:         for (var j=0; j<newSpare.options.length; j++) {
17788:             var possible = newSpare.options[j].value;
17789:             if (possible != '') {
17790:                 if (exclude.indexOf(possible) == -1) {
17791:                     okSpares.push(possible);
17792:                 } else {
17793:                     if (currnew == possible) {
17794:                         selIdx = 0;
17795:                     }
17796:                 }
17797:             }
17798:         }
17799:         for (var k=0; k<include.length; k++) {
17800:             if (okSpares.indexOf(include[k]) == -1) {
17801:                 okSpares.push(include[k]);
17802:             }
17803:         }
17804:         okSpares.sort();
17805:         newSpare.options.length = 0;
17806:         if (selIdx == 0) {
17807:             newSpare.options[0] = new Option("$select","",true,true);
17808:         } else {
17809:             newSpare.options[0] = new Option("$select","",false,false);
17810:         }
17811:         for (var m=0; m<okSpares.length; m++) {
17812:             var idx = m+1;
17813:             var selThis = 0;
17814:             if (selIdx != 0) {
17815:                 if (okSpares[m] == currnew) {
17816:                     selThis = 1;
17817:                 }
17818:             }
17819:             if (selThis == 1) {
17820:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],true,true);
17821:             } else {
17822:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],false,false);
17823:             }
17824:         }
17825:     }
17826:     return;
17827: }
17828: 
17829: function checkNewSpares(lonhost,type) {
17830:     var newSpare = document.getElementById('newspare_'+type+'_'+lonhost);
17831:     var chosen =  newSpare.options[newSpare.selectedIndex].value;
17832:     if (chosen != '') { 
17833:         var othertype;
17834:         var othernewSpare;
17835:         if (type == 'primary') {
17836:             othernewSpare = document.getElementById('newspare_default_'+lonhost);
17837:         }
17838:         if (type == 'default') {
17839:             othernewSpare = document.getElementById('newspare_primary_'+lonhost);
17840:         }
17841:         if (othernewSpare.options[othernewSpare.selectedIndex].value == chosen) {
17842:             othernewSpare.selectedIndex = 0;
17843:         }
17844:     }
17845:     return;
17846: }
17847: 
17848: // ]]>
17849: </script>
17850: 
17851: END
17852: 
17853: }
17854: 
17855: sub common_domprefs_js {
17856:     return <<"END";
17857: 
17858: <script type="text/javascript">
17859: // <![CDATA[
17860: 
17861: function getIndicesByName(formname,item) {
17862:     var group = new Array();
17863:     for (var i=0;i<formname.elements.length;i++) {
17864:         if (formname.elements[i].name == item) {
17865:             group.push(formname.elements[i].id);
17866:         }
17867:     }
17868:     return group;
17869: }
17870: 
17871: // ]]>
17872: </script>
17873: 
17874: END
17875: 
17876: }
17877: 
17878: sub recaptcha_js {
17879:     my %lt = &captcha_phrases();
17880:     return <<"END";
17881: 
17882: <script type="text/javascript">
17883: // <![CDATA[
17884: 
17885: function updateCaptcha(caller,context) {
17886:     var privitem;
17887:     var pubitem;
17888:     var privtext;
17889:     var pubtext;
17890:     var versionitem;
17891:     var versiontext;
17892:     if (document.getElementById(context+'_recaptchapub')) {
17893:         pubitem = document.getElementById(context+'_recaptchapub');
17894:     } else {
17895:         return;
17896:     }
17897:     if (document.getElementById(context+'_recaptchapriv')) {
17898:         privitem = document.getElementById(context+'_recaptchapriv');
17899:     } else {
17900:         return;
17901:     }
17902:     if (document.getElementById(context+'_recaptchapubtxt')) {
17903:         pubtext = document.getElementById(context+'_recaptchapubtxt');
17904:     } else {
17905:         return;
17906:     }
17907:     if (document.getElementById(context+'_recaptchaprivtxt')) {
17908:         privtext = document.getElementById(context+'_recaptchaprivtxt');
17909:     } else {
17910:         return;
17911:     }
17912:     if (document.getElementById(context+'_recaptchaversion')) {
17913:         versionitem = document.getElementById(context+'_recaptchaversion');
17914:     } else {
17915:         return;
17916:     }
17917:     if (document.getElementById(context+'_recaptchavertxt')) {
17918:         versiontext = document.getElementById(context+'_recaptchavertxt');
17919:     } else {
17920:         return;
17921:     }
17922:     if (caller.checked) {
17923:         if (caller.value == 'recaptcha') {
17924:             pubitem.type = 'text';
17925:             privitem.type = 'text';
17926:             pubitem.size = '40';
17927:             privitem.size = '40';
17928:             pubtext.innerHTML = "$lt{'pub'}";
17929:             privtext.innerHTML = "$lt{'priv'}";
17930:             versionitem.type = 'text';
17931:             versionitem.size = '3';
17932:             versiontext.innerHTML = "$lt{'ver'}";
17933:         } else {
17934:             pubitem.type = 'hidden';
17935:             privitem.type = 'hidden';
17936:             versionitem.type = 'hidden';
17937:             pubtext.innerHTML = '';
17938:             privtext.innerHTML = '';
17939:             versiontext.innerHTML = '';
17940:         }
17941:     }
17942:     return;
17943: }
17944: 
17945: // ]]>
17946: </script>
17947: 
17948: END
17949: 
17950: }
17951: 
17952: sub toggle_display_js {
17953:     return <<"END";
17954: 
17955: <script type="text/javascript">
17956: // <![CDATA[
17957: 
17958: function toggleDisplay(domForm,caller) {
17959:     if (document.getElementById(caller)) {
17960:         var divitem = document.getElementById(caller);
17961:         var optionsElement = domForm.coursecredits;
17962:         var checkval = 1;
17963:         var dispval = 'block';
17964:         var selfcreateRegExp = /^cancreate_emailverified/;
17965:         if (caller == 'emailoptions') {
17966:             optionsElement = domForm.cancreate_email; 
17967:         }
17968:         if (caller == 'studentsubmission') {
17969:             optionsElement = domForm.postsubmit;
17970:         }
17971:         if (caller == 'cloneinstcode') {
17972:             optionsElement = domForm.canclone;
17973:             checkval = 'instcode';
17974:         }
17975:         if (selfcreateRegExp.test(caller)) {
17976:             optionsElement = domForm.elements[caller];
17977:             checkval = 'other';
17978:             dispval = 'inline'
17979:         }
17980:         if (optionsElement.length) {
17981:             var currval;
17982:             for (var i=0; i<optionsElement.length; i++) {
17983:                 if (optionsElement[i].checked) {
17984:                    currval = optionsElement[i].value;
17985:                 }
17986:             }
17987:             if (currval == checkval) {
17988:                 divitem.style.display = dispval;
17989:             } else {
17990:                 divitem.style.display = 'none';
17991:             }
17992:         }
17993:     }
17994:     return;
17995: }
17996: 
17997: // ]]>
17998: </script>
17999: 
18000: END
18001: 
18002: }
18003: 
18004: sub captcha_phrases {
18005:     return &Apache::lonlocal::texthash (
18006:                  priv => 'Private key',
18007:                  pub  => 'Public key',
18008:                  original  => 'original (CAPTCHA)',
18009:                  recaptcha => 'successor (ReCAPTCHA)',
18010:                  notused   => 'unused',
18011:                  ver => 'ReCAPTCHA version (1 or 2)',
18012:     );
18013: }
18014: 
18015: sub devalidate_remote_domconfs {
18016:     my ($dom,$cachekeys) = @_;
18017:     return unless (ref($cachekeys) eq 'HASH');
18018:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
18019:     my %thismachine;
18020:     map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
18021:     my @posscached = ('domainconfig','domdefaults','usersessions',
18022:                       'directorysrch','passwdconf','cats','proxyalias','proxysaml',
18023:                       'ipaccess');
18024:     my %cache_by_lonhost;
18025:     if (exists($cachekeys->{'samllanding'})) {
18026:         if (ref($cachekeys->{'samllanding'}) eq 'HASH') {
18027:             my %landing = %{$cachekeys->{'samllanding'}};
18028:             my %domservers = &Apache::lonnet::get_servers($dom);
18029:             if (keys(%domservers)) {
18030:                 foreach my $server (keys(%domservers)) {
18031:                     my @cached;
18032:                     next if ($thismachine{$server});
18033:                     if ($landing{$server}) {
18034:                         push(@cached,&escape('samllanding').':'.&escape($server));
18035:                     }
18036:                     if (@cached) {
18037:                         $cache_by_lonhost{$server} = \@cached;
18038:                     }
18039:                 }
18040:             }
18041:         }
18042:     }
18043:     if (keys(%servers)) {
18044:         foreach my $server (keys(%servers)) {
18045:             next if ($thismachine{$server});
18046:             my @cached;
18047:             foreach my $name (@posscached) {
18048:                 if ($cachekeys->{$name}) {
18049:                     if (($name eq 'proxyalias') || ($name eq 'proxysaml')) {
18050:                         if (ref($cachekeys->{$name}) eq 'HASH') {
18051:                             foreach my $key (keys(%{$cachekeys->{$name}})) {
18052:                                 push(@cached,&escape($name).':'.&escape($key));
18053:                             }
18054:                         }
18055:                     } else {
18056:                         push(@cached,&escape($name).':'.&escape($dom));
18057:                     }
18058:                 }
18059:             }
18060:             if ((exists($cache_by_lonhost{$server})) &&
18061:                 (ref($cache_by_lonhost{$server}) eq 'ARRAY')) {
18062:                 push(@cached,@{$cache_by_lonhost{$server}});
18063:             }
18064:             if (@cached) {
18065:                 &Apache::lonnet::remote_devalidate_cache($server,\@cached);
18066:             }
18067:         }
18068:     }
18069:     return;
18070: }
18071: 
18072: 1;

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