File:  [LON-CAPA] / loncom / interface / domainprefs.pm
Revision 1.160.6.118.2.6: download - view: text, annotated - select for diffs
Mon Feb 21 13:56:22 2022 UTC (2 years, 3 months ago) by raeburn
Branches: version_2_11_4_msu
- For 2.11.4 (modified)
  - Add some scope changes and a line omitted in changes in 1.160.6.118.2.5

    1: # The LearningOnline Network with CAPA
    2: # Handler to set domain-wide configuration settings
    3: #
    4: # $Id: domainprefs.pm,v 1.160.6.118.2.6 2022/02/21 13:56:22 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','ltitools','ltisec','wafproxy','ipaccess'],$dom);
  222:     my %encconfig =
  223:         &Apache::lonnet::get_dom('encconfig',['ltitools','linkprot'],$dom,undef,1);
  224:     if (ref($domconfig{'ltitools'}) eq 'HASH') {
  225:         if (ref($encconfig{'ltitools'}) eq 'HASH') {
  226:             foreach my $id (keys(%{$domconfig{'ltitools'}})) {
  227:                 if (ref($domconfig{'ltitools'}{$id}) eq 'HASH') {
  228:                     foreach my $item ('key','secret') {
  229:                         $domconfig{'ltitools'}{$id}{$item} = $encconfig{'ltitools'}{$id}{$item};
  230:                     }
  231:                 }
  232:             }
  233:         }
  234:     }
  235:     if (ref($domconfig{'ltisec'}) eq 'HASH') {
  236:         if (ref($domconfig{'ltisec'}{'linkprot'}) eq 'HASH') {
  237:             if (ref($encconfig{'linkprot'}) eq 'HASH') {
  238:                 foreach my $id (keys(%{$domconfig{'ltisec'}{'linkprot'}})) {
  239:                     unless ($id =~ /^\d+$/) {
  240:                         delete($domconfig{'ltisec'}{'linkprot'}{$id});
  241:                     }
  242:                     if ((ref($domconfig{'ltisec'}{'linkprot'}{$id}) eq 'HASH') &&
  243:                         (ref($encconfig{'linkprot'}{$id}) eq 'HASH')) {
  244:                         foreach my $item ('key','secret') {
  245:                             $domconfig{'ltisec'}{'linkprot'}{$id}{$item} = $encconfig{'linkprot'}{$id}{$item};
  246:                         }
  247:                     }
  248:                 }
  249:             }
  250:         }
  251:     }
  252:     my @prefs_order = ('rolecolors','login','ipaccess','defaults','wafproxy','passwords',
  253:                        'quotas','autoenroll','autoupdate','autocreate','directorysrch',
  254:                        'contacts','usercreation','selfcreation','usermodification',
  255:                        'scantron','requestcourses','requestauthor','coursecategories',
  256:                        'serverstatuses','helpsettings','coursedefaults',
  257:                        'ltitools','selfenrollment','usersessions','lti');
  258:     my %existing;
  259:     if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
  260:         %existing = %{$domconfig{'loadbalancing'}};
  261:     }
  262:     if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
  263:         push(@prefs_order,'loadbalancing');
  264:     }
  265:     my %prefs = (
  266:         'rolecolors' =>
  267:                    { text => 'Default color schemes',
  268:                      help => 'Domain_Configuration_Color_Schemes',
  269:                      header => [{col1 => 'Student Settings',
  270:                                  col2 => '',},
  271:                                 {col1 => 'Coordinator Settings',
  272:                                  col2 => '',},
  273:                                 {col1 => 'Author Settings',
  274:                                  col2 => '',},
  275:                                 {col1 => 'Administrator Settings',
  276:                                  col2 => '',}],
  277:                       print => \&print_rolecolors,
  278:                       modify => \&modify_rolecolors,
  279:                     },
  280:         'login' =>
  281:                     { text => 'Log-in page options',
  282:                       help => 'Domain_Configuration_Login_Page',
  283:                       header => [{col1 => 'Log-in Page Items',
  284:                                   col2 => '',},
  285:                                  {col1 => 'Log-in Help',
  286:                                   col2 => 'Value'},
  287:                                  {col1 => 'Custom HTML in document head',
  288:                                   col2 => 'Value'},
  289:                                  {col1 => 'SSO',
  290:                                   col2 => 'Dual login: SSO and non-SSO options'},
  291:                                 ],
  292:                       print => \&print_login,
  293:                       modify => \&modify_login,
  294:                     },
  295:         'defaults' => 
  296:                     { text => 'Default authentication/language/timezone/portal/types',
  297:                       help => 'Domain_Configuration_LangTZAuth',
  298:                       header => [{col1 => 'Setting',
  299:                                   col2 => 'Value'},
  300:                                  {col1 => 'Institutional user types',
  301:                                   col2 => 'Name displayed'}],
  302:                       print => \&print_defaults,
  303:                       modify => \&modify_defaults,
  304:                     },
  305:         'wafproxy' =>
  306:                     { text => 'Web Application Firewall/Reverse Proxy',
  307:                       help => 'Domain_Configuration_WAF_Proxy',
  308:                       header => [{col1 => 'Domain(s)',
  309:                                   col2 => 'Servers and WAF/Reverse Proxy alias(es)',
  310:                                  },
  311:                                  {col1 => 'Domain(s)',
  312:                                   col2 => 'WAF Configuration',}],
  313:                       print => \&print_wafproxy,
  314:                       modify => \&modify_wafproxy,
  315:                     },
  316:         'passwords' =>
  317:                     { text => 'Passwords (Internal authentication)',
  318:                       help => 'Domain_Configuration_Passwords',
  319:                       header => [{col1 => 'Resetting Forgotten Password',
  320:                                   col2 => 'Settings'},
  321:                                  {col1 => 'Encryption of Stored Passwords (Internal Auth)',
  322:                                   col2 => 'Settings'},
  323:                                  {col1 => 'Rules for LON-CAPA Passwords',
  324:                                   col2 => 'Settings'},
  325:                                  {col1 => 'Course Owner Changing Student Passwords',
  326:                                   col2 => 'Settings'}],
  327:                       print => \&print_passwords,
  328:                       modify => \&modify_passwords,
  329:                     },
  330:         'quotas' => 
  331:                     { text => 'Blogs, personal web pages, webDAV/quotas, portfolios',
  332:                       help => 'Domain_Configuration_Quotas',
  333:                       header => [{col1 => 'User affiliation',
  334:                                   col2 => 'Available tools',
  335:                                   col3 => 'Quotas, MB; (Authoring requires role)',}],
  336:                       print => \&print_quotas,
  337:                       modify => \&modify_quotas,
  338:                     },
  339:         'autoenroll' =>
  340:                    { text => 'Auto-enrollment settings',
  341:                      help => 'Domain_Configuration_Auto_Enrollment',
  342:                      header => [{col1 => 'Configuration setting',
  343:                                  col2 => 'Value(s)'}],
  344:                      print => \&print_autoenroll,
  345:                      modify => \&modify_autoenroll,
  346:                    },
  347:         'autoupdate' => 
  348:                    { text => 'Auto-update settings',
  349:                      help => 'Domain_Configuration_Auto_Updates',
  350:                      header => [{col1 => 'Setting',
  351:                                  col2 => 'Value',},
  352:                                 {col1 => 'Setting',
  353:                                  col2 => 'Affiliation'},
  354:                                 {col1 => 'User population',
  355:                                  col2 => 'Updatable user data'}],
  356:                      print => \&print_autoupdate,
  357:                      modify => \&modify_autoupdate,
  358:                   },
  359:         'autocreate' => 
  360:                   { text => 'Auto-course creation settings',
  361:                      help => 'Domain_Configuration_Auto_Creation',
  362:                      header => [{col1 => 'Configuration Setting',
  363:                                  col2 => 'Value',}],
  364:                      print => \&print_autocreate,
  365:                      modify => \&modify_autocreate,
  366:                   },
  367:         'directorysrch' => 
  368:                   { text => 'Directory searches',
  369:                     help => 'Domain_Configuration_InstDirectory_Search',
  370:                     header => [{col1 => 'Institutional Directory Setting',
  371:                                 col2 => 'Value',},
  372:                                {col1 => 'LON-CAPA Directory Setting',
  373:                                 col2 => 'Value',}],
  374:                     print => \&print_directorysrch,
  375:                     modify => \&modify_directorysrch,
  376:                   },
  377:         'contacts' =>
  378:                   { text => 'E-mail addresses and helpform',
  379:                     help => 'Domain_Configuration_Contact_Info',
  380:                     header => [{col1 => 'Default e-mail addresses',
  381:                                 col2 => 'Value',},
  382:                                {col1 => 'Recipient(s) for notifications',
  383:                                 col2 => 'Value',},
  384:                                {col1 => 'Nightly status check e-mail',
  385:                                 col2 => 'Settings',},
  386:                                {col1 => 'Ask helpdesk form settings',
  387:                                 col2 => 'Value',},],
  388:                     print => \&print_contacts,
  389:                     modify => \&modify_contacts,
  390:                   },
  391:         'usercreation' => 
  392:                   { text => 'User creation',
  393:                     help => 'Domain_Configuration_User_Creation',
  394:                     header => [{col1 => 'Format rule type',
  395:                                 col2 => 'Format rules in force'},
  396:                                {col1 => 'User account creation',
  397:                                 col2 => 'Usernames which may be created',},
  398:                                {col1 => 'Context',
  399:                                 col2 => 'Assignable authentication types'}],
  400:                     print => \&print_usercreation,
  401:                     modify => \&modify_usercreation,
  402:                   },
  403:         'selfcreation' => 
  404:                   { text => 'Users self-creating accounts',
  405:                     help => 'Domain_Configuration_Self_Creation', 
  406:                     header => [{col1 => 'Self-creation with institutional username',
  407:                                 col2 => 'Enabled?'},
  408:                                {col1 => 'Institutional user type (login/SSO self-creation)',
  409:                                 col2 => 'Information user can enter'},
  410:                                {col1 => 'Self-creation with e-mail verification',
  411:                                 col2 => 'Settings'}],
  412:                     print => \&print_selfcreation,
  413:                     modify => \&modify_selfcreation,
  414:                   },
  415:         'usermodification' =>
  416:                   { text => 'User modification',
  417:                     help => 'Domain_Configuration_User_Modification',
  418:                     header => [{col1 => 'Target user has role',
  419:                                 col2 => 'User information updatable in author context'},
  420:                                {col1 => 'Target user has role',
  421:                                 col2 => 'User information updatable in course context'}],
  422:                     print => \&print_usermodification,
  423:                     modify => \&modify_usermodification,
  424:                   },
  425:         'scantron' =>
  426:                   { text => 'Bubblesheet format',
  427:                     help => 'Domain_Configuration_Scantron_Format',
  428:                     header => [ {col1 => 'Bubblesheet format file',
  429:                                  col2 => ''},
  430:                                 {col1 => 'Bubblesheet data upload formats',
  431:                                  col2 => 'Settings'}],
  432:                     print => \&print_scantron,
  433:                     modify => \&modify_scantron,
  434:                   },
  435:         'requestcourses' => 
  436:                  {text => 'Request creation of courses',
  437:                   help => 'Domain_Configuration_Request_Courses',
  438:                   header => [{col1 => 'User affiliation',
  439:                               col2 => 'Availability/Processing of requests',},
  440:                              {col1 => 'Setting',
  441:                               col2 => 'Value'},
  442:                              {col1 => 'Available textbooks',
  443:                               col2 => ''},
  444:                              {col1 => 'Available templates',
  445:                               col2 => ''},
  446:                              {col1 => 'Validation (not official courses)',
  447:                               col2 => 'Value'},],
  448:                   print => \&print_quotas,
  449:                   modify => \&modify_quotas,
  450:                  },
  451:         'requestauthor' =>
  452:                  {text => 'Request Authoring Space',
  453:                   help => 'Domain_Configuration_Request_Author',
  454:                   header => [{col1 => 'User affiliation',
  455:                               col2 => 'Availability/Processing of requests',},
  456:                              {col1 => 'Setting',
  457:                               col2 => 'Value'}],
  458:                   print => \&print_quotas,
  459:                   modify => \&modify_quotas,
  460:                  },
  461:         'coursecategories' =>
  462:                   { text => 'Cataloging of courses/communities',
  463:                     help => 'Domain_Configuration_Cataloging_Courses',
  464:                     header => [{col1 => 'Catalog type/availability',
  465:                                 col2 => '',},
  466:                                {col1 => 'Category settings for standard catalog',
  467:                                 col2 => '',},
  468:                                {col1 => 'Categories',
  469:                                 col2 => '',
  470:                                }],
  471:                     print => \&print_coursecategories,
  472:                     modify => \&modify_coursecategories,
  473:                   },
  474:         'serverstatuses' =>
  475:                  {text   => 'Access to server status pages',
  476:                   help   => 'Domain_Configuration_Server_Status',
  477:                   header => [{col1 => 'Status Page',
  478:                               col2 => 'Other named users',
  479:                               col3 => 'Specific IPs',
  480:                             }],
  481:                   print => \&print_serverstatuses,
  482:                   modify => \&modify_serverstatuses,
  483:                  },
  484:         'helpsettings' =>
  485:                  {text   => 'Support settings',
  486:                   help   => 'Domain_Configuration_Help_Settings',
  487:                   header => [{col1 => 'Help Page Settings (logged-in users)',
  488:                               col2 => 'Value'},
  489:                              {col1 => 'Helpdesk Roles',
  490:                               col2 => 'Settings'},],
  491:                   print  => \&print_helpsettings,
  492:                   modify => \&modify_helpsettings,
  493:                  },
  494:         'coursedefaults' => 
  495:                  {text => 'Course/Community defaults',
  496:                   help => 'Domain_Configuration_Course_Defaults',
  497:                   header => [{col1 => 'Defaults which can be overridden in each course by a CC',
  498:                               col2 => 'Value',},
  499:                              {col1 => 'Defaults which can be overridden for each course by a DC',
  500:                               col2 => 'Value',},],
  501:                   print => \&print_coursedefaults,
  502:                   modify => \&modify_coursedefaults,
  503:                  },
  504:         'selfenrollment' => 
  505:                  {text   => 'Self-enrollment in Course/Community',
  506:                   help   => 'Domain_Configuration_Selfenrollment',
  507:                   header => [{col1 => 'Configuration Rights',
  508:                               col2 => 'Configured by Course Personnel or Domain Coordinator?'},
  509:                              {col1 => 'Defaults',
  510:                               col2 => 'Value'},
  511:                              {col1 => 'Self-enrollment validation (optional)',
  512:                               col2 => 'Value'},],
  513:                   print => \&print_selfenrollment,
  514:                   modify => \&modify_selfenrollment,
  515:                  },
  516:         'usersessions' =>
  517:                  {text  => 'User session hosting/offloading',
  518:                   help  => 'Domain_Configuration_User_Sessions',
  519:                   header => [{col1 => 'Domain server',
  520:                               col2 => 'Servers to offload sessions to when busy'},
  521:                              {col1 => 'Hosting of users from other domains',
  522:                               col2 => 'Rules'},
  523:                              {col1 => "Hosting domain's own users elsewhere",
  524:                               col2 => 'Rules'}],
  525:                   print => \&print_usersessions,
  526:                   modify => \&modify_usersessions,
  527:                  },
  528:         'loadbalancing' =>
  529:                  {text  => 'Dedicated Load Balancer(s)',
  530:                   help  => 'Domain_Configuration_Load_Balancing',
  531:                   header => [{col1 => 'Balancers',
  532:                               col2 => 'Default destinations',
  533:                               col3 => 'User affiliation',
  534:                               col4 => 'Overrides'},
  535:                             ],
  536:                   print => \&print_loadbalancing,
  537:                   modify => \&modify_loadbalancing,
  538:                  },
  539:         'ltitools' =>
  540:                  {text => 'External Tools (LTI)',
  541:                   help => 'Domain_Configuration_LTI_Tools',
  542:                   header => [{col1 => 'Setting',
  543:                               col2 => 'Value',}],
  544:                   print => \&print_ltitools,
  545:                   modify => \&modify_ltitools,
  546:                  },
  547:           'lti' =>
  548:                  {text => 'LTI Link Protection and LTI Consumers',
  549:                   help => 'Domain_Configuration_LTI_Provider',
  550:                   header => [{col1 => 'Encryption of shared secrets',
  551:                               col2 => 'Settings'},
  552:                              {col1 => 'Rules for shared secrets',
  553:                               col2 => 'Settings'},
  554:                              {col1 => 'Link Protectors',
  555:                               col2 => 'Settings'},],
  556:                   print => \&print_lti,
  557:                   modify => \&modify_lti,
  558:                  },
  559:          'ipaccess' =>
  560:                        {text => 'IP-based access control',
  561:                         help => 'Domain_Configuration_IP_Access',
  562:                         header => [{col1 => 'Setting',
  563:                                     col2 => 'Value'},],
  564:                         print  => \&print_ipaccess,
  565:                         modify => \&modify_ipaccess,
  566:                        },
  567:     );
  568:     if (keys(%servers) > 1) {
  569:         $prefs{'login'}  = { text   => 'Log-in page options',
  570:                              help   => 'Domain_Configuration_Login_Page',
  571:                             header => [{col1 => 'Log-in Service',
  572:                                         col2 => 'Server Setting',},
  573:                                        {col1 => 'Log-in Page Items',
  574:                                         col2 => 'Settings'},
  575:                                        {col1 => 'Log-in Help',
  576:                                         col2 => 'Value'},
  577:                                        {col1 => 'Custom HTML in document head',
  578:                                         col2 => 'Value'},
  579:                                        {col1 => 'SSO',
  580:                                         col2 => 'Dual login: SSO and non-SSO options'},
  581:                                       ],
  582:                             print => \&print_login,
  583:                             modify => \&modify_login,
  584:                            };
  585:     }
  586: 
  587:     my @roles = ('student','coordinator','author','admin');
  588:     my @actions = &Apache::loncommon::get_env_multiple('form.actions');
  589:     &Apache::lonhtmlcommon::add_breadcrumb
  590:     ({href=>"javascript:changePage(document.$phase,'pickactions')",
  591:       text=>"Settings to display/modify"});
  592:     my $confname = $dom.'-domainconfig';
  593: 
  594:     if ($phase eq 'process') {
  595:         my $result = &Apache::lonconfigsettings::make_changes($r,$dom,$phase,$context,\@prefs_order,
  596:                                                               \%prefs,\%domconfig,$confname,\@roles);
  597:         if ((ref($result) eq 'HASH') && (keys(%{$result}))) {
  598:             $r->rflush();
  599:             &devalidate_remote_domconfs($dom,$result);
  600:         }
  601:     } elsif ($phase eq 'display') {
  602:         my $js = &recaptcha_js().
  603:                  &toggle_display_js();
  604:         if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
  605:             my ($othertitle,$usertypes,$types) =
  606:                 &Apache::loncommon::sorted_inst_types($dom);
  607:             $js .= &lonbalance_targets_js($dom,$types,\%servers,
  608:                                           $domconfig{'loadbalancing'}).
  609:                    &new_spares_js().
  610:                    &common_domprefs_js().
  611:                    &Apache::loncommon::javascript_array_indexof();
  612:         }
  613:         if (grep(/^requestcourses$/,@actions)) {
  614:             my $javascript_validations;
  615:             my $coursebrowserjs=&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}); 
  616:             $js .= <<END;
  617: <script type="text/javascript">
  618: $javascript_validations
  619: </script>
  620: $coursebrowserjs
  621: END
  622:         } elsif (grep(/^ipaccess$/,@actions)) {
  623:             $js .= &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
  624:         }
  625:         if (grep(/^selfcreation$/,@actions)) {
  626:             $js .= &selfcreate_javascript();
  627:         }
  628:         if (grep(/^contacts$/,@actions)) {
  629:             $js .= &contacts_javascript();
  630:         }
  631:         if (grep(/^scantron$/,@actions)) {
  632:             $js .= &scantron_javascript();
  633:         }
  634:         &Apache::lonconfigsettings::display_settings($r,$dom,$phase,$context,\@prefs_order,\%prefs,\%domconfig,$confname,$js);
  635:     } else {
  636: # check if domconfig user exists for the domain.
  637:         my $servadm = $r->dir_config('lonAdmEMail');
  638:         my ($configuserok,$author_ok,$switchserver) =
  639:             &config_check($dom,$confname,$servadm);
  640:         unless ($configuserok eq 'ok') {
  641:             &Apache::lonconfigsettings::print_header($r,$phase,$context);
  642:             $r->print(&mt('The domain configuration user "[_1]" has yet to be created.',
  643:                           $confname).
  644:                       '<br />'
  645:             );
  646:             if ($switchserver) {
  647:                 $r->print(&mt('Ordinarily, that domain configuration user is created when the ./UPDATE script is run to install LON-CAPA for the first time.').
  648:                           '<br />'.
  649:                           &mt('However, that does not apply when new domains are added to a multi-domain server, and ./UPDATE has not been run recently.').
  650:                           '<br />'.
  651:                           &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).
  652:                           '<br />'.
  653:                           &mt('To do that now, use the following link: [_1]',$switchserver)
  654:                 );
  655:             } else {
  656:                 $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.').
  657:                           '<br />'.
  658:                           &mt('Once that is done, you will be able to use the web-based "Set domain configuration" to configure the domain')
  659:                 );
  660:             }
  661:             $r->print(&Apache::loncommon::end_page());
  662:             return OK;
  663:         }
  664:         if (keys(%domconfig) == 0) {
  665:             my $primarylibserv = &Apache::lonnet::domain($dom,'primary');
  666:             my @ids=&Apache::lonnet::current_machine_ids();
  667:             if (!grep(/^\Q$primarylibserv\E$/,@ids)) {
  668:                 my %designhash = &Apache::loncommon::get_domainconf($dom);
  669:                 my @loginimages = ('img','logo','domlogo','login');
  670:                 my $custom_img_count = 0;
  671:                 foreach my $img (@loginimages) {
  672:                     if ($designhash{$dom.'.login.'.$img} ne '') {
  673:                         $custom_img_count ++;
  674:                     }
  675:                 }
  676:                 foreach my $role (@roles) {
  677:                     if ($designhash{$dom.'.'.$role.'.img'} ne '') {
  678:                         $custom_img_count ++;
  679:                     }
  680:                 }
  681:                 if ($custom_img_count > 0) {
  682:                     &Apache::lonconfigsettings::print_header($r,$phase,$context);
  683:                     my $switch_server = &check_switchserver($dom,$confname);
  684:                     $r->print(
  685:     &mt('Domain configuration settings have yet to be saved for this domain via the web-based domain preferences interface.').'<br />'.
  686:     &mt("While this remains so, you must switch to the domain's primary library server in order to update settings.").'<br /><br />'.
  687:     &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 />'.
  688:     &mt("However, you will still need to switch to the domain's primary library server to upload new images or logos.").'<br /><br />');
  689:                     if ($switch_server) {
  690:                         $r->print($switch_server.' '.&mt('to primary library server for domain: [_1]',$dom));
  691:                     }
  692:                     $r->print(&Apache::loncommon::end_page());
  693:                     return OK;
  694:                 }
  695:             }
  696:         }
  697:         &Apache::lonconfigsettings::display_choices($r,$phase,$context,\@prefs_order,\%prefs);
  698:     }
  699:     return OK;
  700: }
  701: 
  702: sub process_changes {
  703:     my ($r,$dom,$confname,$action,$roles,$values,$lastactref) = @_;
  704:     my %domconfig;
  705:     if (ref($values) eq 'HASH') {
  706:         %domconfig = %{$values};
  707:     }
  708:     my $output;
  709:     if ($action eq 'login') {
  710:         $output = &modify_login($r,$dom,$confname,$lastactref,%domconfig);
  711:     } elsif ($action eq 'rolecolors') {
  712:         $output = &modify_rolecolors($r,$dom,$confname,$roles,
  713:                                      $lastactref,%domconfig);
  714:     } elsif ($action eq 'quotas') {
  715:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  716:     } elsif ($action eq 'autoenroll') {
  717:         $output = &modify_autoenroll($dom,$lastactref,%domconfig);
  718:     } elsif ($action eq 'autoupdate') {
  719:         $output = &modify_autoupdate($dom,%domconfig);
  720:     } elsif ($action eq 'autocreate') {
  721:         $output = &modify_autocreate($dom,%domconfig);
  722:     } elsif ($action eq 'directorysrch') {
  723:         $output = &modify_directorysrch($dom,$lastactref,%domconfig);
  724:     } elsif ($action eq 'usercreation') {
  725:         $output = &modify_usercreation($dom,%domconfig);
  726:     } elsif ($action eq 'selfcreation') {
  727:         $output = &modify_selfcreation($dom,$lastactref,%domconfig);
  728:     } elsif ($action eq 'usermodification') {
  729:         $output = &modify_usermodification($dom,%domconfig);
  730:     } elsif ($action eq 'contacts') {
  731:         $output = &modify_contacts($dom,$lastactref,%domconfig);
  732:     } elsif ($action eq 'defaults') {
  733:         $output = &modify_defaults($dom,$lastactref,%domconfig);
  734:     } elsif ($action eq 'scantron') {
  735:         $output = &modify_scantron($r,$dom,$confname,$lastactref,%domconfig);
  736:     } elsif ($action eq 'coursecategories') {
  737:         $output = &modify_coursecategories($dom,$lastactref,%domconfig);
  738:     } elsif ($action eq 'serverstatuses') {
  739:         $output = &modify_serverstatuses($dom,%domconfig);
  740:     } elsif ($action eq 'requestcourses') {
  741:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  742:     } elsif ($action eq 'requestauthor') {
  743:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  744:     } elsif ($action eq 'helpsettings') {
  745:         $output = &modify_helpsettings($r,$dom,$confname,$lastactref,%domconfig);
  746:     } elsif ($action eq 'coursedefaults') {
  747:         $output = &modify_coursedefaults($dom,$lastactref,%domconfig);
  748:     } elsif ($action eq 'selfenrollment') {
  749:         $output = &modify_selfenrollment($dom,$lastactref,%domconfig)
  750:     } elsif ($action eq 'usersessions') {
  751:         $output = &modify_usersessions($dom,$lastactref,%domconfig);
  752:     } elsif ($action eq 'loadbalancing') {
  753:         $output = &modify_loadbalancing($dom,%domconfig);
  754:     } elsif ($action eq 'lti') {
  755:         $output = &modify_lti($r,$dom,$action,$lastactref,%domconfig);
  756:     } elsif ($action eq 'passwords') {
  757:         $output = &modify_passwords($r,$dom,$confname,$lastactref,%domconfig);
  758:     } elsif ($action eq 'ltitools') {
  759:         $output = &modify_ltitools($r,$dom,$action,$lastactref,%domconfig);
  760:     } elsif ($action eq 'wafproxy') {
  761:         $output = &modify_wafproxy($dom,$action,$lastactref,%domconfig);
  762:     } elsif ($action eq 'ipaccess') {
  763:         $output = &modify_ipaccess($dom,$lastactref,%domconfig);
  764:     }
  765:     return $output;
  766: }
  767: 
  768: sub print_config_box {
  769:     my ($r,$dom,$confname,$phase,$action,$item,$settings) = @_;
  770:     my $rowtotal = 0;
  771:     my $output;
  772:     if ($action eq 'coursecategories') {
  773:         $output = &coursecategories_javascript($settings);
  774:     } elsif ($action eq 'defaults') {
  775:         $output = &defaults_javascript($settings); 
  776:     } elsif ($action eq 'passwords') {
  777:         $output = &passwords_javascript($action);
  778:     } elsif ($action eq 'helpsettings') {
  779:         my (%privs,%levelscurrent);
  780:         my %full=();
  781:         my %levels=(
  782:                      course => {},
  783:                      domain => {},
  784:                      system => {},
  785:                    );
  786:         my $context = 'domain';
  787:         my $crstype = 'Course';
  788:         my $formname = 'display';
  789:         &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
  790:         my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
  791:         $output =
  792:             &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,\%full,
  793:                                                       \@templateroles);
  794:     } elsif ($action eq 'ltitools') {
  795:         $output .= &ltitools_javascript($settings);
  796:     } elsif ($action eq 'lti') {
  797:         $output .= &passwords_javascript('secrets')."\n".
  798:                    &lti_javascript($dom,$settings);
  799:     } elsif ($action eq 'wafproxy') {
  800:         $output .= &wafproxy_javascript($dom);
  801:     } elsif ($action eq 'autoupdate') {
  802:         $output .= &autoupdate_javascript();
  803:     } elsif ($action eq 'autoenroll') {
  804:         $output .= &autoenroll_javascript();
  805:     } elsif ($action eq 'login') {
  806:         $output .= &saml_javascript();
  807:     } elsif ($action eq 'ipaccess') {
  808:         $output .= &ipaccess_javascript($settings);
  809:     }
  810:     $output .=
  811:          '<table class="LC_nested_outer">
  812:           <tr>
  813:            <th class="LC_left_item LC_middle"><span class="LC_nobreak">'.
  814:            &mt($item->{text}).'&nbsp;'.
  815:            &Apache::loncommon::help_open_topic($item->{'help'}).'</span></th>'."\n".
  816:           '</tr>';
  817:     $rowtotal ++;
  818:     my $numheaders = 1;
  819:     if (ref($item->{'header'}) eq 'ARRAY') {
  820:         $numheaders = scalar(@{$item->{'header'}});
  821:     }
  822:     if ($numheaders > 1) {
  823:         my $colspan = '';
  824:         my $rightcolspan = '';
  825:         my $leftnobr = '';  
  826:         if (($action eq 'rolecolors') || ($action eq 'defaults') ||
  827:             ($action eq 'directorysrch') ||
  828:             (($action eq 'login') && ($numheaders < 5))) {
  829:             $colspan = ' colspan="2"';
  830:         }
  831:         if ($action eq 'usersessions') {
  832:             $rightcolspan = ' colspan="3"'; 
  833:         }
  834:         if ($action eq 'passwords') {
  835:             $leftnobr = ' LC_nobreak';
  836:         }
  837:         $output .= '
  838:           <tr>
  839:            <td>
  840:             <table class="LC_nested">
  841:              <tr class="LC_info_row">
  842:               <td class="LC_left_item'.$leftnobr.'"'.$colspan.'>'.&mt($item->{'header'}->[0]->{'col1'}).'</td>
  843:               <td class="LC_right_item"'.$rightcolspan.'>'.&mt($item->{'header'}->[0]->{'col2'}).'</td>
  844:              </tr>';
  845:         $rowtotal ++;
  846:         if (($action eq 'autoupdate') || ($action eq 'usercreation') || ($action eq 'selfcreation') ||
  847:             ($action eq 'usermodification') || ($action eq 'defaults') || ($action eq 'coursedefaults') ||
  848:             ($action eq 'selfenrollment') || ($action eq 'usersessions') || ($action eq 'directorysrch') ||
  849:             ($action eq 'helpsettings') || ($action eq 'contacts') || ($action eq 'wafproxy') || ($action eq 'lti')) {
  850:             $output .= $item->{'print'}->('top',$dom,$settings,\$rowtotal);
  851:         } elsif ($action eq 'passwords') {
  852:             $output .= $item->{'print'}->('top',$dom,$confname,$settings,\$rowtotal);
  853:         } elsif ($action eq 'coursecategories') {
  854:             $output .= $item->{'print'}->('top',$dom,$item,$settings,\$rowtotal);
  855:         } elsif ($action eq 'scantron') {
  856:             $output .= $item->{'print'}->($r,'top',$dom,$confname,$settings,\$rowtotal);
  857:         } elsif ($action eq 'login') {
  858:             if ($numheaders == 5) {
  859:                 $colspan = ' colspan="2"';
  860:                 $output .= &print_login('service',$dom,$confname,$phase,$settings,\$rowtotal);
  861:             } else {
  862:                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal);
  863:             }
  864:         } elsif (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
  865:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
  866:         } elsif ($action eq 'rolecolors') {
  867:             $output .= &print_rolecolors($phase,'student',$dom,$confname,$settings,\$rowtotal);
  868:         }
  869:         $output .= '
  870:            </table>
  871:           </td>
  872:          </tr>
  873:          <tr>
  874:            <td>
  875:             <table class="LC_nested">
  876:              <tr class="LC_info_row">
  877:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col1'}).'</td>
  878:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col2'}).'</td>
  879:              </tr>';
  880:             $rowtotal ++;
  881:         if (($action eq 'autoupdate') || ($action eq 'usercreation') ||
  882:             ($action eq 'selfcreation') || ($action eq 'selfenrollment') ||
  883:             ($action eq 'usersessions') || ($action eq 'coursecategories') ||
  884:             ($action eq 'contacts') || ($action eq 'passwords') || ($action eq 'lti')) {
  885:             if ($action eq 'coursecategories') {
  886:                 $output .= &print_coursecategories('middle',$dom,$item,$settings,\$rowtotal);
  887:                 $colspan = ' colspan="2"';
  888:             } elsif ($action eq 'passwords') {
  889:                 $output .= $item->{'print'}->('middle',$dom,$confname,$settings,\$rowtotal);
  890:             } else {
  891:                 $output .= $item->{'print'}->('middle',$dom,$settings,\$rowtotal);
  892:             }
  893:             $output .= '
  894:            </table>
  895:           </td>
  896:          </tr>
  897:          <tr>
  898:            <td>
  899:             <table class="LC_nested">
  900:              <tr class="LC_info_row">
  901:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
  902:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
  903:              </tr>'."\n";
  904:             if ($action eq 'coursecategories') {
  905:                 $output .= &print_coursecategories('bottom',$dom,$item,$settings,\$rowtotal);
  906:             } elsif (($action eq 'contacts') || ($action eq 'passwords')) {
  907:                 if ($action eq 'passwords') {
  908:                     $output .= $item->{'print'}->('lower',$dom,$confname,$settings,\$rowtotal);
  909:                 } else {
  910:                     $output .= $item->{'print'}->('lower',$dom,$settings,\$rowtotal);
  911:                 }
  912:                 $output .= '
  913:              </tr>
  914:             </table>
  915:            </td>
  916:           </tr>
  917:           <tr>
  918:            <td>
  919:             <table class="LC_nested">
  920:              <tr class="LC_info_row">
  921:               <td class="LC_left_item'.$leftnobr.'"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
  922:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td></tr>'."\n";
  923:                 if ($action eq 'passwords') {
  924:                     $output .= $item->{'print'}->('bottom',$dom,$confname,$settings,\$rowtotal);
  925:                 } else {
  926:                     $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
  927:                 }
  928:                 $output .= '
  929:             </table>
  930:           </td>
  931:          </tr>
  932:          <tr>';
  933:             } else {
  934:                 $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
  935:             }
  936:             $rowtotal ++;
  937:         } elsif (($action eq 'usermodification') || ($action eq 'coursedefaults') ||
  938:                  ($action eq 'defaults') || ($action eq 'directorysrch') ||
  939:                  ($action eq 'helpsettings') || ($action eq 'wafproxy')) {
  940:             $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
  941:         } elsif ($action eq 'scantron') {
  942:             $output .= $item->{'print'}->($r,'bottom',$dom,$confname,$settings,\$rowtotal);
  943:         } elsif ($action eq 'login') {
  944:             if ($numheaders == 5) {
  945:                 $output .= &print_login('page',$dom,$confname,$phase,$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"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td></tr>'.
  955:                        &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
  956:                 $rowtotal ++;
  957:             } else {
  958:                 $output .= &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
  959:             }
  960:             $output .= '
  961:            </table>
  962:           </td>
  963:          </tr>
  964:          <tr>
  965:            <td>
  966:             <table class="LC_nested">
  967:              <tr class="LC_info_row">';
  968:             if ($numheaders == 5) {
  969:                 $output .= '
  970:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
  971:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
  972:              </tr>';
  973:             } else {
  974:                 $output .= '
  975:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
  976:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
  977:              </tr>';
  978:             }
  979:             $rowtotal ++;
  980:             $output .= &print_login('headtag',$dom,$confname,$phase,$settings,\$rowtotal).'
  981:            </table>
  982:           </td>
  983:          </tr>
  984:          <tr>
  985:            <td>
  986:             <table class="LC_nested">
  987:              <tr class="LC_info_row">';
  988:             if ($numheaders == 5) {
  989:                 $output .= '
  990:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[4]->{'col1'}).'</td>
  991:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[4]->{'col2'}).'</td>
  992:              </tr>';
  993:             } else {
  994:                 $output .= '
  995:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
  996:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
  997:              </tr>';
  998:             }
  999:             $rowtotal ++;
 1000:             $output .= &print_login('saml',$dom,$confname,$phase,$settings,\$rowtotal);
 1001:         } elsif ($action eq 'requestcourses') {
 1002:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
 1003:             $rowtotal ++;
 1004:             $output .= &print_studentcode($settings,\$rowtotal).'
 1005:            </table>
 1006:           </td>
 1007:          </tr>
 1008:          <tr>
 1009:            <td>
 1010:             <table class="LC_nested">
 1011:              <tr class="LC_info_row">
 1012:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1013:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td> </tr>'.
 1014:                        &textbookcourses_javascript($settings).
 1015:                        &print_textbookcourses($dom,'textbooks',$settings,\$rowtotal).'
 1016:             </table>
 1017:            </td>
 1018:           </tr>
 1019:          <tr>
 1020:            <td>
 1021:             <table class="LC_nested">
 1022:              <tr class="LC_info_row">
 1023:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1024:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td> </tr>'.
 1025:                        &print_textbookcourses($dom,'templates',$settings,\$rowtotal).'
 1026:             </table>
 1027:            </td>
 1028:           </tr>
 1029:           <tr>
 1030:            <td>
 1031:             <table class="LC_nested">
 1032:              <tr class="LC_info_row">
 1033:               <td class="LC_left_item"'.$colspan.' valign="top">'.&mt($item->{'header'}->[4]->{'col1'}).'</td>
 1034:               <td class="LC_right_item" valign="top">'.&mt($item->{'header'}->[4]->{'col2'}).'</td>
 1035:              </tr>'.
 1036:             &print_validation_rows('requestcourses',$dom,$settings,\$rowtotal);
 1037:         } elsif ($action eq 'requestauthor') {
 1038:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
 1039:             $rowtotal ++;
 1040:         } elsif ($action eq 'rolecolors') {
 1041:             $output .= &print_rolecolors($phase,'coordinator',$dom,$confname,$settings,\$rowtotal).'
 1042:            </table>
 1043:           </td>
 1044:          </tr>
 1045:          <tr>
 1046:            <td>
 1047:             <table class="LC_nested">
 1048:              <tr class="LC_info_row">
 1049:               <td class="LC_left_item"'.$colspan.' valign="top">'.
 1050:                &mt($item->{'header'}->[2]->{'col1'}).'</td>
 1051:               <td class="LC_right_item" valign="top">'.
 1052:                &mt($item->{'header'}->[2]->{'col2'}).'</td>
 1053:              </tr>'.
 1054:             &print_rolecolors($phase,'author',$dom,$confname,$settings,\$rowtotal).'
 1055:            </table>
 1056:           </td>
 1057:          </tr>
 1058:          <tr>
 1059:            <td>
 1060:             <table class="LC_nested">
 1061:              <tr class="LC_info_row">
 1062:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1063:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
 1064:              </tr>'.
 1065:             &print_rolecolors($phase,'admin',$dom,$confname,$settings,\$rowtotal);
 1066:             $rowtotal += 2;
 1067:         }
 1068:     } else {
 1069:         $output .= '
 1070:           <tr>
 1071:            <td>
 1072:             <table class="LC_nested">
 1073:              <tr class="LC_info_row">';
 1074:         if ($action eq 'login') {
 1075:             $output .= '  
 1076:               <td class="LC_left_item" colspan="2">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
 1077:         } elsif ($action eq 'serverstatuses') {
 1078:             $output .= '
 1079:               <td class="LC_left_item" valign="top">'.&mt($item->{'header'}->[0]->{'col1'}).
 1080:               '<br />('.&mt('Automatic access for Dom. Coords.').')</td>';
 1081: 
 1082:         } else {
 1083:             $output .= '
 1084:               <td class="LC_left_item" valign="top">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
 1085:         }
 1086:         if (defined($item->{'header'}->[0]->{'col3'})) {
 1087:             $output .= '<td class="LC_left_item" valign="top">'.
 1088:                        &mt($item->{'header'}->[0]->{'col2'});
 1089:             if ($action eq 'serverstatuses') {
 1090:                 $output .= '<br />(<tt>'.&mt('user1:domain1,user2:domain2 etc.').'</tt>)';
 1091:             } 
 1092:         } else {
 1093:             $output .= '<td class="LC_right_item" valign="top">'.
 1094:                        &mt($item->{'header'}->[0]->{'col2'});
 1095:         }
 1096:         $output .= '</td>';
 1097:         if ($item->{'header'}->[0]->{'col3'}) {
 1098:             if (defined($item->{'header'}->[0]->{'col4'})) {
 1099:                 $output .= '<td class="LC_left_item" valign="top">'.
 1100:                             &mt($item->{'header'}->[0]->{'col3'});
 1101:             } else {
 1102:                 $output .= '<td class="LC_right_item" valign="top">'.
 1103:                            &mt($item->{'header'}->[0]->{'col3'});
 1104:             }
 1105:             if ($action eq 'serverstatuses') {
 1106:                 $output .= '<br />(<tt>'.&mt('IP1,IP2 etc.').'</tt>)';
 1107:             }
 1108:             $output .= '</td>';
 1109:         }
 1110:         if ($item->{'header'}->[0]->{'col4'}) {
 1111:             $output .= '<td class="LC_right_item" valign="top">'.
 1112:                        &mt($item->{'header'}->[0]->{'col4'});
 1113:         }
 1114:         $output .= '</tr>';
 1115:         $rowtotal ++;
 1116:         if ($action eq 'quotas') {
 1117:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
 1118:         } elsif (($action eq 'autoenroll') || ($action eq 'autocreate') || 
 1119:                  ($action eq 'serverstatuses') || ($action eq 'loadbalancing') ||
 1120:                  ($action eq 'ltitools') || ($action eq 'ipaccess')) {
 1121:             $output .= $item->{'print'}->($dom,$settings,\$rowtotal);
 1122:         }
 1123:     }
 1124:     $output .= '
 1125:    </table>
 1126:   </td>
 1127:  </tr>
 1128: </table><br />';
 1129:     return ($output,$rowtotal);
 1130: }
 1131: 
 1132: sub print_login {
 1133:     my ($caller,$dom,$confname,$phase,$settings,$rowtotal) = @_;
 1134:     my ($css_class,$datatable,$switchserver,%lt);
 1135:     my %choices = &login_choices();
 1136:     if (($caller eq 'help') || ($caller eq 'headtag') || ($caller eq 'saml')) {
 1137:         %lt = &login_file_options();
 1138:         $switchserver = &check_switchserver($dom,$confname);
 1139:     }
 1140: 
 1141:     if ($caller eq 'service') {
 1142:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 1143:         my $choice = $choices{'disallowlogin'};
 1144:         $css_class = ' class="LC_odd_row"';
 1145:         $datatable .= '<tr'.$css_class.'><td>'.$choice.'</td>'.
 1146:                       '<td align="right"><table><tr><th>'.$choices{'hostid'}.'</th>'.
 1147:                       '<th>'.$choices{'server'}.'</th>'.
 1148:                       '<th>'.$choices{'serverpath'}.'</th>'.
 1149:                       '<th>'.$choices{'custompath'}.'</th>'.
 1150:                       '<th><span class="LC_nobreak">'.$choices{'exempt'}.'</span></th></tr>'."\n";
 1151:         my %disallowed;
 1152:         if (ref($settings) eq 'HASH') {
 1153:             if (ref($settings->{'loginvia'}) eq 'HASH') {
 1154:                %disallowed = %{$settings->{'loginvia'}};
 1155:             }
 1156:         }
 1157:         foreach my $lonhost (sort(keys(%servers))) {
 1158:             my $direct = 'selected="selected"';
 1159:             if (ref($disallowed{$lonhost}) eq 'HASH') {
 1160:                 if ($disallowed{$lonhost}{'server'} ne '') {
 1161:                     $direct = '';
 1162:                 }
 1163:             }
 1164:             $datatable .= '<tr><td>'.$servers{$lonhost}.'</td>'.
 1165:                           '<td><select name="'.$lonhost.'_server">'.
 1166:                           '<option value=""'.$direct.'>'.$choices{'directlogin'}.
 1167:                           '</option>';
 1168:             foreach my $hostid (sort(keys(%servers))) {
 1169:                 next if ($servers{$hostid} eq $servers{$lonhost});
 1170:                 my $selected = '';
 1171:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
 1172:                     if ($hostid eq $disallowed{$lonhost}{'server'}) {
 1173:                         $selected = 'selected="selected"';
 1174:                     }
 1175:                 }
 1176:                 $datatable .= '<option value="'.$hostid.'"'.$selected.'>'.
 1177:                               $servers{$hostid}.'</option>';
 1178:             }
 1179:             $datatable .= '</select></td>'.
 1180:                           '<td><select name="'.$lonhost.'_serverpath">';
 1181:             foreach my $path ('','/','/adm/login','/adm/roles','custom') {
 1182:                 my $pathname = $path;
 1183:                 if ($path eq 'custom') {
 1184:                     $pathname = &mt('Custom Path').' ->';
 1185:                 }
 1186:                 my $selected = '';
 1187:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
 1188:                     if ($path eq $disallowed{$lonhost}{'serverpath'}) {
 1189:                         $selected = 'selected="selected"';
 1190:                     }
 1191:                 } elsif ($path eq '') {
 1192:                     $selected = 'selected="selected"';
 1193:                 }
 1194:                 $datatable .= '<option value="'.$path.'"'.$selected.'>'.$pathname.'</option>';
 1195:             }
 1196:             $datatable .= '</select></td>';
 1197:             my ($custom,$exempt);
 1198:             if (ref($disallowed{$lonhost}) eq 'HASH') {
 1199:                 $custom = $disallowed{$lonhost}{'custompath'};
 1200:                 $exempt = $disallowed{$lonhost}{'exempt'};
 1201:             }
 1202:             $datatable .= '<td><input type="text" name="'.$lonhost.'_custompath" size="6" value="'.$custom.'" /></td>'.
 1203:                           '<td><input type="text" name="'.$lonhost.'_exempt" size="8" value="'.$exempt.'" /></td>'.
 1204:                           '</tr>';
 1205:         }
 1206:         $datatable .= '</table></td></tr>';
 1207:         return $datatable;
 1208:     } elsif ($caller eq 'page') {
 1209:         my %defaultchecked = ( 
 1210:                                'coursecatalog' => 'on',
 1211:                                'helpdesk'      => 'on',
 1212:                                'adminmail'     => 'off',
 1213:                                'newuser'       => 'off',
 1214:                              );
 1215:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
 1216:         my (%checkedon,%checkedoff);
 1217:         foreach my $item (@toggles) {
 1218:             if ($defaultchecked{$item} eq 'on') { 
 1219:                 $checkedon{$item} = ' checked="checked" ';
 1220:                 $checkedoff{$item} = ' ';
 1221:             } elsif ($defaultchecked{$item} eq 'off') {
 1222:                 $checkedoff{$item} = ' checked="checked" ';
 1223:                 $checkedon{$item} = ' ';
 1224:             }
 1225:         }
 1226:         my @images = ('img','logo','domlogo','login');
 1227:         my @alttext = ('img','logo','domlogo');
 1228:         my @logintext = ('textcol','bgcol');
 1229:         my @bgs = ('pgbg','mainbg','sidebg');
 1230:         my @links = ('link','alink','vlink');
 1231:         my %designhash = &Apache::loncommon::get_domainconf($dom);
 1232:         my %defaultdesign = %Apache::loncommon::defaultdesign;
 1233:         my (%is_custom,%designs);
 1234:         my %defaults = (
 1235:                        font => $defaultdesign{'login.font'},
 1236:                        );
 1237:         foreach my $item (@images) {
 1238:             $defaults{$item} = $defaultdesign{'login.'.$item};
 1239:             $defaults{'showlogo'}{$item} = 1;
 1240:         }
 1241:         foreach my $item (@bgs) {
 1242:             $defaults{'bgs'}{$item} = $defaultdesign{'login.'.$item};
 1243:         }
 1244:         foreach my $item (@logintext) {
 1245:             $defaults{'logintext'}{$item} = $defaultdesign{'login.'.$item};
 1246:         }
 1247:         foreach my $item (@links) {
 1248:             $defaults{'links'}{$item} = $defaultdesign{'login.'.$item};
 1249:         }
 1250:         if (ref($settings) eq 'HASH') {
 1251:             foreach my $item (@toggles) {
 1252:                 if ($settings->{$item} eq '1') {
 1253:                     $checkedon{$item} =  ' checked="checked" ';
 1254:                     $checkedoff{$item} = ' ';
 1255:                 } elsif ($settings->{$item} eq '0') {
 1256:                     $checkedoff{$item} =  ' checked="checked" ';
 1257:                     $checkedon{$item} = ' ';
 1258:                 }
 1259:             }
 1260:             foreach my $item (@images) {
 1261:                 if (defined($settings->{$item})) {
 1262:                     $designs{$item} = $settings->{$item};
 1263:                     $is_custom{$item} = 1;
 1264:                 }
 1265:                 if (defined($settings->{'showlogo'}{$item})) {
 1266:                     $designs{'showlogo'}{$item} = $settings->{'showlogo'}{$item};
 1267:                 }
 1268:             }
 1269:             foreach my $item (@alttext) {
 1270:                 if (ref($settings->{'alttext'}) eq 'HASH') {
 1271:                     if ($settings->{'alttext'}->{$item} ne '') {
 1272:                         $designs{'alttext'}{$item} = $settings->{'alttext'}{$item};
 1273:                     }
 1274:                 }
 1275:             }
 1276:             foreach my $item (@logintext) {
 1277:                 if ($settings->{$item} ne '') {
 1278:                     $designs{'logintext'}{$item} = $settings->{$item};
 1279:                     $is_custom{$item} = 1;
 1280:                 }
 1281:             }
 1282:             if ($settings->{'font'} ne '') {
 1283:                 $designs{'font'} = $settings->{'font'};
 1284:                 $is_custom{'font'} = 1;
 1285:             }
 1286:             foreach my $item (@bgs) {
 1287:                 if ($settings->{$item} ne '') {
 1288:                     $designs{'bgs'}{$item} = $settings->{$item};
 1289:                     $is_custom{$item} = 1;
 1290:                 }
 1291:             }
 1292:             foreach my $item (@links) {
 1293:                 if ($settings->{$item} ne '') {
 1294:                     $designs{'links'}{$item} = $settings->{$item};
 1295:                     $is_custom{$item} = 1;
 1296:                 }
 1297:             }
 1298:         } else {
 1299:             if ($designhash{$dom.'.login.font'} ne '') {
 1300:                 $designs{'font'} = $designhash{$dom.'.login.font'};
 1301:                 $is_custom{'font'} = 1;
 1302:             }
 1303:             foreach my $item (@images) {
 1304:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1305:                     $designs{$item} = $designhash{$dom.'.login.'.$item};
 1306:                     $is_custom{$item} = 1;
 1307:                 }
 1308:             }
 1309:             foreach my $item (@bgs) {
 1310:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1311:                     $designs{'bgs'}{$item} = $designhash{$dom.'.login.'.$item};
 1312:                     $is_custom{$item} = 1;
 1313:                 }
 1314:             }
 1315:             foreach my $item (@links) {
 1316:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1317:                     $designs{'links'}{$item} = $designhash{$dom.'.login.'.$item};
 1318:                     $is_custom{$item} = 1;
 1319:                 }
 1320:             }
 1321:         }
 1322:         my %alt_text = &Apache::lonlocal::texthash  ( img => 'Log-in banner',
 1323:                                                       logo => 'Institution Logo',
 1324:                                                       domlogo => 'Domain Logo',
 1325:                                                       login => 'Login box');
 1326:         my $itemcount = 1;
 1327:         foreach my $item (@toggles) {
 1328:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1329:             $datatable .=  
 1330:                 '<tr'.$css_class.'><td colspan="2">'.$choices{$item}.
 1331:                 '</td><td>'.
 1332:                 '<span class="LC_nobreak"><label><input type="radio" name="'.
 1333:                 $item.'"'.$checkedon{$item}.' value="1" />'.&mt('Yes').
 1334:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'"'.
 1335:                 $checkedoff{$item}.' value="0" />'.&mt('No').'</label></span></td>'.
 1336:                 '</tr>';
 1337:             $itemcount ++;
 1338:         }
 1339:         $datatable .= &display_color_options($dom,$confname,$phase,'login',$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal,\@logintext);
 1340:         $datatable .= '</tr></table></td></tr>';
 1341:     } elsif ($caller eq 'help') {
 1342:         my ($defaulturl,$defaulttype,%url,%type,%langchoices);
 1343:         my $itemcount = 1;
 1344:         $defaulturl = '/adm/loginproblems.html';
 1345:         $defaulttype = 'default';
 1346:         %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
 1347:         my @currlangs;
 1348:         if (ref($settings) eq 'HASH') {
 1349:             if (ref($settings->{'helpurl'}) eq 'HASH') {
 1350:                 foreach my $key (sort(keys(%{$settings->{'helpurl'}}))) {
 1351:                     next if ($settings->{'helpurl'}{$key} eq '');
 1352:                     $url{$key} = $settings->{'helpurl'}{$key}.'?inhibitmenu=yes';
 1353:                     $type{$key} = 'custom';
 1354:                     unless ($key eq 'nolang') {
 1355:                         push(@currlangs,$key);
 1356:                     }
 1357:                 }
 1358:             } elsif ($settings->{'helpurl'} ne '') {
 1359:                 $type{'nolang'} = 'custom';
 1360:                 $url{'nolang'} = $settings->{'helpurl'}.'?inhibitmenu=yes';
 1361:             }
 1362:         }
 1363:         foreach my $lang ('nolang',sort(@currlangs)) {
 1364:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1365:             $datatable .= '<tr'.$css_class.'>';
 1366:             if ($url{$lang} eq '') {
 1367:                 $url{$lang} = $defaulturl;
 1368:             }
 1369:             if ($type{$lang} eq '') {
 1370:                 $type{$lang} = $defaulttype;
 1371:             }
 1372:             $datatable .= '<td colspan="2"><span class="LC_nobreak">';
 1373:             if ($lang eq 'nolang') {
 1374:                 $datatable .= &mt('Log-in help page if no specific language file: [_1]',
 1375:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1376:             } else {
 1377:                 $datatable .= &mt('Log-in help page for language: [_1] is [_2]',
 1378:                                   $langchoices{$lang},
 1379:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1380:             }
 1381:             $datatable .= '</span></td>'."\n".
 1382:                           '<td class="LC_left_item">';
 1383:             if ($type{$lang} eq 'custom') {
 1384:                 $datatable .= '<span class="LC_nobreak"><label>'.
 1385:                               '<input type="checkbox" name="loginhelpurl_del" value="'.$lang.'" />'.
 1386:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1387:             } else {
 1388:                 $datatable .= $lt{'upl'};
 1389:             }
 1390:             $datatable .='<br />';
 1391:             if ($switchserver) {
 1392:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1393:             } else {
 1394:                 $datatable .= '<input type="file" name="loginhelpurl_'.$lang.'" />';
 1395:             }
 1396:             $datatable .= '</td></tr>';
 1397:             $itemcount ++;
 1398:         }
 1399:         my @addlangs;
 1400:         foreach my $lang (sort(keys(%langchoices))) {
 1401:             next if ((grep(/^\Q$lang\E$/,@currlangs)) || ($lang eq 'x_chef'));
 1402:             push(@addlangs,$lang);
 1403:         }
 1404:         if (@addlangs > 0) {
 1405:             my %toadd;
 1406:             map { $toadd{$_} = $langchoices{$_} ; } @addlangs;
 1407:             $toadd{''} = &mt('Select');
 1408:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1409:             $datatable .= '<tr'.$css_class.'><td class="LC_left_item" colspan="2">'.
 1410:                           &mt('Add log-in help page for a specific language:').'&nbsp;'.
 1411:                           &Apache::loncommon::select_form('','loginhelpurl_add_lang',\%toadd).
 1412:                           '</td><td class="LC_left_item">'.$lt{'upl'}.'<br />';
 1413:             if ($switchserver) {
 1414:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1415:             } else {
 1416:                 $datatable .= '<input type="file" name="loginhelpurl_add_file" />';
 1417:             }
 1418:             $datatable .= '</td></tr>';
 1419:             $itemcount ++;
 1420:         }
 1421:         $datatable .= &captcha_choice('login',$settings,$itemcount);
 1422:     } elsif ($caller eq 'headtag') {
 1423:         my %domservers = &Apache::lonnet::get_servers($dom);
 1424:         my $choice = $choices{'headtag'};
 1425:         $css_class = ' class="LC_odd_row"';
 1426:         $datatable .= '<tr'.$css_class.'><td colspan="2">'.$choice.'</td>'.
 1427:                       '<td align="left"><table><tr><th>'.$choices{'hostid'}.'</th>'.
 1428:                       '<th>'.$choices{'current'}.'</th>'.
 1429:                       '<th>'.$choices{'action'}.'</th>'.
 1430:                       '<th>'.$choices{'exempt'}.'</th></tr>'."\n";
 1431:         my (%currurls,%currexempt);
 1432:         if (ref($settings) eq 'HASH') {
 1433:             if (ref($settings->{'headtag'}) eq 'HASH') {
 1434:                 foreach my $lonhost (keys(%{$settings->{'headtag'}})) {
 1435:                     if (ref($settings->{'headtag'}{$lonhost}) eq 'HASH') {
 1436:                         $currurls{$lonhost} = $settings->{'headtag'}{$lonhost}{'url'};
 1437:                         $currexempt{$lonhost} = $settings->{'headtag'}{$lonhost}{'exempt'};
 1438:                     }
 1439:                 }
 1440:             }
 1441:         }
 1442:         foreach my $lonhost (sort(keys(%domservers))) {
 1443:             my $exempt = &check_exempt_addresses($currexempt{$lonhost});
 1444:             $datatable .= '<tr><td>'.$domservers{$lonhost}.'</td>';
 1445:             if ($currurls{$lonhost}) {
 1446:                 $datatable .= '<td class="LC_right_item"><a href="'.
 1447:                               "javascript:void(open('$currurls{$lonhost}?inhibitmenu=yes','Custom_HeadTag',
 1448:                               'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
 1449:                               '">'.$lt{'curr'}.'</a></td>'.
 1450:                               '<td><span class="LC_nobreak"><label>'.
 1451:                               '<input type="checkbox" name="loginheadtag_del" value="'.$lonhost.'" />'.
 1452:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1453:             } else {
 1454:                 $datatable .= '<td class="LC_right_item">'.$lt{'none'}.'</td><td>'.$lt{'upl'};
 1455:             }
 1456:             $datatable .='<br />';
 1457:             if ($switchserver) {
 1458:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1459:             } else {
 1460:                 $datatable .= '<input type="file" name="loginheadtag_'.$lonhost.'" />';
 1461:             }
 1462:             $datatable .= '</td><td><input type="text" name="loginheadtagexempt_'.$lonhost.'" value="'.$exempt.'" /></td></tr>';
 1463:         }
 1464:         $datatable .= '</table></td></tr>';
 1465:     } elsif ($caller eq 'saml') {
 1466:         my %domservers = &Apache::lonnet::get_servers($dom);
 1467:         $datatable .= '<tr><td colspan="3" style="text-align: left">'.
 1468:                       '<table><tr><th>'.$choices{'hostid'}.'</th>'.
 1469:                       '<th>'.$choices{'samllanding'}.'</th>'.
 1470:                       '<th>'.$choices{'samloptions'}.'</th></tr>'."\n";
 1471:         my (%saml,%samltext,%samlimg,%samlalt,%samlurl,%samltitle,%samlnotsso,%styleon,%styleoff);
 1472:         foreach my $lonhost (keys(%domservers)) {
 1473:             $samlurl{$lonhost} = '/adm/sso';
 1474:             $styleon{$lonhost} = 'display:none';
 1475:             $styleoff{$lonhost} = '';
 1476:         }
 1477:         if (ref($settings->{'saml'}) eq 'HASH') {
 1478:             foreach my $lonhost (keys(%{$settings->{'saml'}})) {
 1479:                 if (ref($settings->{'saml'}{$lonhost}) eq 'HASH') {
 1480:                     $saml{$lonhost} = 1;
 1481:                     $samltext{$lonhost} = $settings->{'saml'}{$lonhost}{'text'};
 1482:                     $samlimg{$lonhost} = $settings->{'saml'}{$lonhost}{'img'};
 1483:                     $samlalt{$lonhost} = $settings->{'saml'}{$lonhost}{'alt'};
 1484:                     $samlurl{$lonhost} = $settings->{'saml'}{$lonhost}{'url'};
 1485:                     $samltitle{$lonhost} = $settings->{'saml'}{$lonhost}{'title'};
 1486:                     $samlnotsso{$lonhost} = $settings->{'saml'}{$lonhost}{'notsso'};
 1487:                     $styleon{$lonhost} = '';
 1488:                     $styleoff{$lonhost} = 'display:none';
 1489:                 } else {
 1490:                     $styleon{$lonhost} = 'display:none';
 1491:                     $styleoff{$lonhost} = '';
 1492:                 }
 1493:             }
 1494:         }
 1495:         my $itemcount = 1;
 1496:         foreach my $lonhost (sort(keys(%domservers))) {
 1497:             my $samlon = ' ';
 1498:             my $samloff = ' checked="checked" ';
 1499:             if ($saml{$lonhost}) {
 1500:                 $samlon = $samloff;
 1501:                 $samloff = ' ';
 1502:             }
 1503:             my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1504:             $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.$domservers{$lonhost}.'</span></td>'.
 1505:                           '<td><span class="LC_nobreak"><label><input type="radio" name="saml_'.$lonhost.'"'.$samloff.
 1506:                           'onclick="toggleSamlOptions(this.form,'."'$lonhost'".');" value="0" />'.
 1507:                           &mt('No').'</label>'.('&nbsp;'x2).
 1508:                           '<label><input type="radio" name="saml_'.$lonhost.'"'.$samlon.
 1509:                           'onclick="toggleSamlOptions(this.form,'."'$lonhost'".');" value="1" />'.
 1510:                           &mt('Yes').'</label></span></td>'.
 1511:                           '<td id="samloptionson_'.$lonhost.'" style="'.$styleon{$lonhost}.'" width="100%">'.
 1512:                           '<table><tr><th colspan="5" align="center">'.&mt('SSO').'</th><th align="center">'.
 1513:                           '<span class="LC_nobreak">'.&mt('Non-SSO').'</span></th></tr>'.
 1514:                           '<tr><th>'.&mt('Text').'</th><th>'.&mt('Image').'</th>'.
 1515:                           '<th>'.&mt('Alt Text').'</th><th>'.&mt('URL').'</th>'.
 1516:                           '<th>'.&mt('Tool Tip').'</th><th>'.&mt('Text').'</th></tr>'.
 1517:                           '<tr'.$css_class.'><td><input type="text" name="saml_text_'.$lonhost.'" size="8" value="'.
 1518:                           $samltext{$lonhost}.'" /></td><td>';
 1519:             if ($samlimg{$lonhost}) {
 1520:                 $datatable .= '<img src="'.$samlimg{$lonhost}.'" /><br />'.
 1521:                               '<span class="LC_nobreak"><label>'.
 1522:                               '<input type="checkbox" name="saml_img_del" value="'.$lonhost.'" />'.
 1523:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1524:             } else {
 1525:                 $datatable .= $lt{'upl'};
 1526:             }
 1527:             $datatable .='<br />';
 1528:             if ($switchserver) {
 1529:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1530:             } else {
 1531:                 $datatable .= '<input type="file" name="saml_img_'.$lonhost.'" />';
 1532:             }
 1533:             $datatable .= '</td>'.
 1534:                           '<td><input type="text" name="saml_alt_'.$lonhost.'" size="20" '.
 1535:                           'value="'.$samlalt{$lonhost}.'" /></td>'.
 1536:                           '<td><input type="text" name="saml_url_'.$lonhost.'" size="8" '.
 1537:                           'value="'.$samlurl{$lonhost}.'" /></td>'.
 1538:                           '<td><textarea name="saml_title_'.$lonhost.'" rows="3" cols="15">'.
 1539:                           $samltitle{$lonhost}.'</textarea></td>'.
 1540:                           '<td><input type="text" name="saml_notsso_'.$lonhost.'" size="8" '.
 1541:                           'value="'.$samlnotsso{$lonhost}.'" /></td></tr>'.
 1542:                           '</table></td>'.
 1543:                           '<td id="samloptionsoff_'.$lonhost.'" style="'.$styleoff{$lonhost}.'" width="100%">&nbsp;</td></tr>';
 1544:            $itemcount ++;
 1545:         }
 1546:         $datatable .= '</table></td></tr>';
 1547:     }
 1548:     return $datatable;
 1549: }
 1550: 
 1551: sub login_choices {
 1552:     my %choices =
 1553:         &Apache::lonlocal::texthash (
 1554:             coursecatalog => 'Display Course/Community Catalog link?',
 1555:             adminmail     => "Display Administrator's E-mail Address?",
 1556:             helpdesk      => 'Display "Contact Helpdesk" link',
 1557:             disallowlogin => "Login page requests redirected",
 1558:             hostid        => "Server",
 1559:             server        => "Redirect to:",
 1560:             serverpath    => "Path",
 1561:             custompath    => "Custom", 
 1562:             exempt        => "Exempt IP(s)",
 1563:             directlogin   => "No redirect",
 1564:             newuser       => "Link to create a user account",
 1565:             img           => "Header",
 1566:             logo          => "Main Logo",
 1567:             domlogo       => "Domain Logo",
 1568:             login         => "Log-in Header", 
 1569:             textcol       => "Text color",
 1570:             bgcol         => "Box color",
 1571:             bgs           => "Background colors",
 1572:             links         => "Link colors",
 1573:             font          => "Font color",
 1574:             pgbg          => "Header",
 1575:             mainbg        => "Page",
 1576:             sidebg        => "Login box",
 1577:             link          => "Link",
 1578:             alink         => "Active link",
 1579:             vlink         => "Visited link",
 1580:             headtag       => "Custom markup",
 1581:             action        => "Action",
 1582:             current       => "Current",
 1583:             samllanding   => "Dual login?",
 1584:             samloptions   => "Options",
 1585:             alttext       => "Alt text",
 1586:         );
 1587:     return %choices;
 1588: }
 1589: 
 1590: sub login_file_options {
 1591:       return &Apache::lonlocal::texthash(
 1592:                                            del     => 'Delete?',
 1593:                                            rep     => 'Replace:',
 1594:                                            upl     => 'Upload:',
 1595:                                            curr    => 'View contents',
 1596:                                            default => 'Default',
 1597:                                            custom  => 'Custom',
 1598:                                            none    => 'None',
 1599:       );
 1600: }
 1601: 
 1602: sub print_ipaccess {
 1603:     my ($dom,$settings,$rowtotal) = @_;
 1604:     my $css_class;
 1605:     my $itemcount = 0;
 1606:     my $datatable;
 1607:     my %ordered;
 1608:     if (ref($settings) eq 'HASH') {
 1609:         foreach my $item (keys(%{$settings})) {
 1610:             if (ref($settings->{$item}) eq 'HASH') {
 1611:                 my $num = $settings->{$item}{'order'};
 1612:                 if ($num eq '') {
 1613:                     $num = scalar(keys(%{$settings}));
 1614:                 }
 1615:                 $ordered{$num} = $item;
 1616:             }
 1617:         }
 1618:     }
 1619:     my $maxnum = scalar(keys(%ordered));
 1620:     if (keys(%ordered)) {
 1621:         my @items = sort { $a <=> $b } keys(%ordered);
 1622:         for (my $i=0; $i<@items; $i++) {
 1623:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1624:             my $item = $ordered{$items[$i]};
 1625:             my ($name,$ipranges,%commblocks,%courses);
 1626:             if (ref($settings->{$item}) eq 'HASH') {
 1627:                 $name = $settings->{$item}->{'name'};
 1628:                 $ipranges = $settings->{$item}->{'ip'};
 1629:                 if (ref($settings->{$item}->{'commblocks'}) eq 'HASH') {
 1630:                     %commblocks = %{$settings->{$item}->{'commblocks'}};
 1631:                 }
 1632:                 if (ref($settings->{$item}->{'courses'}) eq 'HASH') {
 1633:                     %courses = %{$settings->{$item}->{'courses'}};
 1634:                 }
 1635:             }
 1636:             my $chgstr = ' onchange="javascript:reorderIPaccess(this.form,'."'ipaccess_pos_".$item."'".');"';
 1637:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 1638:                          .'<select name="ipaccess_pos_'.$item.'"'.$chgstr.'>';
 1639:             for (my $k=0; $k<=$maxnum; $k++) {
 1640:                 my $vpos = $k+1;
 1641:                 my $selstr;
 1642:                 if ($k == $i) {
 1643:                     $selstr = ' selected="selected" ';
 1644:                 }
 1645:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 1646:             }
 1647:             $datatable .= '</select>'.('&nbsp;'x2).
 1648:                 '<label><input type="checkbox" name="ipaccess_del" value="'.$item.'" />'.
 1649:                 &mt('Delete?').'</label></span></td>'.
 1650:                 '<td colspan="2"><input type="hidden" name="ipaccess_id_'.$i.'" value="'.$item.'" />'.
 1651:                 &ipaccess_options($i,$itemcount,$dom,$name,$ipranges,\%commblocks,\%courses).
 1652:                 '</td></tr>';
 1653:             $itemcount ++;
 1654:         }
 1655:     }
 1656:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1657:     my $chgstr = ' onchange="javascript:reorderIPaccess(this.form,'."'ipaccess_pos_add'".');"';
 1658:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 1659:                   '<input type="hidden" name="ipaccess_maxnum" value="'.$maxnum.'" />'."\n".
 1660:                   '<select name="ipaccess_pos_add"'.$chgstr.'>';
 1661:     for (my $k=0; $k<$maxnum+1; $k++) {
 1662:         my $vpos = $k+1;
 1663:         my $selstr;
 1664:         if ($k == $maxnum) {
 1665:             $selstr = ' selected="selected" ';
 1666:         }
 1667:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 1668:     }
 1669:     $datatable .= '</select>&nbsp;'."\n".
 1670:                   '<input type="checkbox" name="ipaccess_add" value="1" />'.&mt('Add').'</span></td>'."\n".
 1671:                   '<td colspan="2">'.
 1672:                   &ipaccess_options('add',$itemcount,$dom).
 1673:                   '</td>'."\n".
 1674:                   '</tr>'."\n";
 1675:     $$rowtotal ++;
 1676:     return $datatable;
 1677: }
 1678: 
 1679: sub ipaccess_options {
 1680:     my ($num,$itemcount,$dom,$name,$ipranges,$blocksref,$coursesref) = @_;
 1681:     my (%currblocks,%currcourses,$output);
 1682:     if (ref($blocksref) eq 'HASH') {
 1683:         %currblocks = %{$blocksref};
 1684:     }
 1685:     if (ref($coursesref) eq 'HASH') {
 1686:         %currcourses = %{$coursesref};
 1687:     }
 1688:     $output = '<fieldset><legend>'.&mt('Location(s)').'</legend>'.
 1689:               '<span class="LC_nobreak">'.&mt('Name').':&nbsp;'.
 1690:               '<input type="text" name="ipaccess_name_'.$num.'" value="'.$name.'" />'.
 1691:               '</span></fieldset>'.
 1692:               '<fieldset><legend>'.&mt('IP Range(s)').'</legend>'.
 1693:               &mt('Format for each IP range').': '.&mt('A.B.C.D/N or A.B.C.D-E.F.G.H').'<br />'.
 1694:               &mt('Range(s) will be stored as IP netblock(s) in CIDR notation (comma separated)').'<br />'.
 1695:               '<textarea name="ipaccess_range_'.$num.'" rows="3" cols="80">'.
 1696:               $ipranges.'</textarea></fieldset>'.
 1697:               '<fieldset><legend>'.&mt('Functionality Blocked?').'</legend>'.
 1698:               &blocker_checkboxes($num,$blocksref).'</fieldset>'.
 1699:               '<fieldset><legend>'.&mt('Courses/Communities allowed').'</legend>'.
 1700:               '<table>';
 1701:     foreach my $cid (sort(keys(%currcourses))) {
 1702:         my %courseinfo = &Apache::lonnet::coursedescription($cid,{'one_time' => 1});
 1703:         $output .= '<tr><td><span class="LC_nobreak">'.
 1704:                    '<label><input type="checkbox" name="ipaccess_course_delete_'.$num.'" value="'.$cid.'" />'.
 1705:                    &mt('Delete?').'&nbsp;<span class="LC_cusr_emph">'.$courseinfo{'description'}.'</span></label></span>'.
 1706:                    ' <span class="LC_fontsize_medium">('.$cid.')</span></td></tr>';
 1707:     }
 1708:     $output .= '<tr><td><span class="LC_nobreak">'.&mt('Add').':&nbsp;'.
 1709:                '<input type="text" name="ipaccess_cdesc_'.$num.'" value="" onfocus="this.blur();opencrsbrowser('."'display','ipaccess_cnum_$num','ipaccess_cdom_$num','ipaccess_cdesc_$num'".');" />'.
 1710:                 &Apache::loncommon::selectcourse_link('display','ipaccess_cnum_'.$num,'ipaccess_cdom_'.$num,'ipaccess_cdesc_'.$num,$dom,undef,'Course/Community').
 1711:                '<input type="hidden" name="ipaccess_cnum_'.$num.'" value="" />'.
 1712:                '<input type="hidden" name="ipaccess_cdom_'.$num.'" value="" />'.
 1713:                '</span></td></tr></table>'."\n".
 1714:                '</fieldset>';
 1715:     return $output;
 1716: }
 1717: 
 1718: sub blocker_checkboxes {
 1719:     my ($num,$blocks) = @_;
 1720:     my ($typeorder,$types) = &commblocktype_text();
 1721:     my $numinrow = 6;
 1722:     my $output = '<table>';
 1723:     for (my $i=0; $i<@{$typeorder}; $i++) {
 1724:         my $block = $typeorder->[$i];
 1725:         my $blockstatus;
 1726:         if (ref($blocks) eq 'HASH') {
 1727:             if ($blocks->{$block} eq 'on') {
 1728:                 $blockstatus = 'checked="checked"';
 1729:             }
 1730:         }
 1731:         my $rem = $i%($numinrow);
 1732:         if ($rem == 0) {
 1733:             if ($i > 0) {
 1734:                 $output .= '</tr>';
 1735:             }
 1736:             $output .= '<tr>';
 1737:         }
 1738:         if ($i == scalar(@{$typeorder})-1) {
 1739:             my $colsleft = $numinrow-$rem;
 1740:             if ($colsleft > 1) {
 1741:                 $output .= '<td colspan="'.$colsleft.'">';
 1742:             } else {
 1743:                 $output .= '<td>';
 1744:             }
 1745:         } else {
 1746:             $output .= '<td>';
 1747:         }
 1748:         my $item = 'ipaccess_block_'.$num;
 1749:         if ($blockstatus) {
 1750:             $blockstatus = ' '.$blockstatus;
 1751:         }
 1752:         $output .= '<span class="LC_nobreak"><label>'."\n".
 1753:                    '<input type="checkbox" name="'.$item.'"'.
 1754:                    $blockstatus.' value="'.$block.'"'.' />'.
 1755:                    $types->{$block}.'</label></span>'."\n".
 1756:                    '<br /></td>';
 1757:     }
 1758:     $output .= '</tr></table>';
 1759:     return $output;
 1760: }
 1761: 
 1762: sub commblocktype_text {
 1763:     my %types = &Apache::lonlocal::texthash(
 1764:         'com' => 'Messaging',
 1765:         'chat' => 'Chat Room',
 1766:         'boards' => 'Discussion',
 1767:         'port' => 'Portfolio',
 1768:         'groups' => 'Groups',
 1769:         'blogs' => 'Blogs',
 1770:         'about' => 'User Information',
 1771:         'printout' => 'Printouts',
 1772:         'passwd' => 'Change Password',
 1773:         'grades' => 'Gradebook',
 1774:         'search' => 'Course search',
 1775:         'wishlist' => 'Stored links',
 1776:         'annotate' => 'Annotations',
 1777:     );
 1778:     my $typeorder = ['com','chat','boards','port','groups','blogs','about','wishlist','printout','grades','search','annotate','passwd'];
 1779:     return ($typeorder,\%types);
 1780: }
 1781: 
 1782: sub print_rolecolors {
 1783:     my ($phase,$role,$dom,$confname,$settings,$rowtotal) = @_;
 1784:     my %choices = &color_font_choices();
 1785:     my @bgs = ('pgbg','tabbg','sidebg');
 1786:     my @links = ('link','alink','vlink');
 1787:     my @images = ('img');
 1788:     my %alt_text = &Apache::lonlocal::texthash(img => "Banner for $role role");
 1789:     my %designhash = &Apache::loncommon::get_domainconf($dom);
 1790:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 1791:     my (%is_custom,%designs);
 1792:     my %defaults = &role_defaults($role,\@bgs,\@links,\@images);
 1793:     if (ref($settings) eq 'HASH') {
 1794:         if (ref($settings->{$role}) eq 'HASH') {
 1795:             if ($settings->{$role}->{'img'} ne '') {
 1796:                 $designs{'img'} = $settings->{$role}->{'img'};
 1797:                 $is_custom{'img'} = 1;
 1798:             }
 1799:             if ($settings->{$role}->{'font'} ne '') {
 1800:                 $designs{'font'} = $settings->{$role}->{'font'};
 1801:                 $is_custom{'font'} = 1;
 1802:             }
 1803:             if ($settings->{$role}->{'fontmenu'} ne '') {
 1804:                 $designs{'fontmenu'} = $settings->{$role}->{'fontmenu'};
 1805:                 $is_custom{'fontmenu'} = 1;
 1806:             }
 1807:             foreach my $item (@bgs) {
 1808:                 if ($settings->{$role}->{$item} ne '') {
 1809:                     $designs{'bgs'}{$item} = $settings->{$role}->{$item};
 1810:                     $is_custom{$item} = 1;
 1811:                 }
 1812:             }
 1813:             foreach my $item (@links) {
 1814:                 if ($settings->{$role}->{$item} ne '') {
 1815:                     $designs{'links'}{$item} = $settings->{$role}->{$item};
 1816:                     $is_custom{$item} = 1;
 1817:                 }
 1818:             }
 1819:         }
 1820:     } else {
 1821:         if ($designhash{$dom.'.'.$role.'.img'} ne '') {
 1822:             $designs{img} = $designhash{$dom.'.'.$role.'.img'};
 1823:             $is_custom{'img'} = 1;
 1824:         }
 1825:         if ($designhash{$dom.'.'.$role.'.fontmenu'} ne '') {
 1826:             $designs{fontmenu} = $designhash{$dom.'.'.$role.'.fontmenu'};
 1827:             $is_custom{'fontmenu'} = 1; 
 1828:         }
 1829:         if ($designhash{$dom.'.'.$role.'.font'} ne '') {
 1830:             $designs{font} = $designhash{$dom.'.'.$role.'.font'};
 1831:             $is_custom{'font'} = 1;
 1832:         }
 1833:         foreach my $item (@bgs) {
 1834:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 1835:                 $designs{'bgs'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 1836:                 $is_custom{$item} = 1;
 1837:             
 1838:             }
 1839:         }
 1840:         foreach my $item (@links) {
 1841:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 1842:                 $designs{'links'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 1843:                 $is_custom{$item} = 1;
 1844:             }
 1845:         }
 1846:     }
 1847:     my $itemcount = 1;
 1848:     my $datatable = &display_color_options($dom,$confname,$phase,$role,$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal);
 1849:     $datatable .= '</tr></table></td></tr>';
 1850:     return $datatable;
 1851: }
 1852: 
 1853: sub role_defaults {
 1854:     my ($role,$bgs,$links,$images,$logintext) = @_;
 1855:     my %defaults;
 1856:     unless ((ref($bgs) eq 'ARRAY') && (ref($links) eq 'ARRAY') && (ref($images) eq 'ARRAY')) {
 1857:         return %defaults;
 1858:     }
 1859:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 1860:     if ($role eq 'login') {
 1861:         %defaults = (
 1862:                        font => $defaultdesign{$role.'.font'},
 1863:                     );
 1864:         if (ref($logintext) eq 'ARRAY') {
 1865:             foreach my $item (@{$logintext}) {
 1866:                 $defaults{'logintext'}{$item} = $defaultdesign{$role.'.'.$item};
 1867:             }
 1868:         }
 1869:         foreach my $item (@{$images}) {
 1870:             $defaults{'showlogo'}{$item} = 1;
 1871:         }
 1872:     } else {
 1873:         %defaults = (
 1874:                        img => $defaultdesign{$role.'.img'},
 1875:                        font => $defaultdesign{$role.'.font'},
 1876:                        fontmenu => $defaultdesign{$role.'.fontmenu'},
 1877:                     );
 1878:     }
 1879:     foreach my $item (@{$bgs}) {
 1880:         $defaults{'bgs'}{$item} = $defaultdesign{$role.'.'.$item};
 1881:     }
 1882:     foreach my $item (@{$links}) {
 1883:         $defaults{'links'}{$item} = $defaultdesign{$role.'.'.$item};
 1884:     }
 1885:     foreach my $item (@{$images}) {
 1886:         $defaults{$item} = $defaultdesign{$role.'.'.$item};
 1887:     }
 1888:     return %defaults;
 1889: }
 1890: 
 1891: sub display_color_options {
 1892:     my ($dom,$confname,$phase,$role,$itemcount,$choices,$is_custom,$defaults,$designs,
 1893:         $images,$bgs,$links,$alt_text,$rowtotal,$logintext) = @_;
 1894:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 1895:     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1896:     my $datatable = '<tr'.$css_class.'>'.
 1897:         '<td>'.$choices->{'font'}.'</td>';
 1898:     if (!$is_custom->{'font'}) {
 1899:         $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span class="css_default_'.$role.'_font" style="color: '.$defaults->{'font'}.';">'.$defaults->{'font'}.'</span></td>';
 1900:     } else {
 1901:         $datatable .= '<td>&nbsp;</td>';
 1902:     }
 1903:     my $current_color = $designs->{'font'} ? $designs->{'font'} : $defaults->{'font'};
 1904: 
 1905:     $datatable .= '<td><span class="LC_nobreak">'.
 1906:                   '<input type="text" class="colorchooser" size="10" name="'.$role.'_font"'.
 1907:                   ' value="'.$current_color.'" />&nbsp;'.
 1908:                   '&nbsp;</span></td></tr>';
 1909:     unless ($role eq 'login') { 
 1910:         $datatable .= '<tr'.$css_class.'>'.
 1911:                       '<td>'.$choices->{'fontmenu'}.'</td>';
 1912:         if (!$is_custom->{'fontmenu'}) {
 1913:             $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span class="css_default_'.$role.'_font" style="color: '.$defaults->{'fontmenu'}.';">'.$defaults->{'fontmenu'}.'</span></td>';
 1914:         } else {
 1915:             $datatable .= '<td>&nbsp;</td>';
 1916:         }
 1917: 	$current_color = $designs->{'fontmenu'} ?
 1918: 	    $designs->{'fontmenu'} : $defaults->{'fontmenu'};
 1919:         $datatable .= '<td><span class="LC_nobreak">'.
 1920:                       '<input class="colorchooser" type="text" size="10" name="'
 1921: 		      .$role.'_fontmenu"'.
 1922:                       ' value="'.$current_color.'" />&nbsp;'.
 1923:                       '&nbsp;</span></td></tr>';
 1924:     }
 1925:     my $switchserver = &check_switchserver($dom,$confname);
 1926:     foreach my $img (@{$images}) {
 1927: 	$itemcount ++;
 1928:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1929:         $datatable .= '<tr'.$css_class.'>'.
 1930:                       '<td>'.$choices->{$img};
 1931:         my ($imgfile,$img_import,$login_hdr_pick,$logincolors,$alttext);
 1932:         if ($role eq 'login') {
 1933:             if ($img eq 'login') {
 1934:                 $login_hdr_pick =
 1935:                     &login_header_options($img,$role,$defaults,$is_custom,$choices);
 1936:                 $logincolors =
 1937:                     &login_text_colors($img,$role,$logintext,$phase,$choices,
 1938:                                        $designs,$defaults);
 1939:             } else {
 1940:                 if ($img ne 'domlogo') {
 1941:                     $datatable.= &logo_display_options($img,$defaults,$designs);
 1942:                 }
 1943:                 if (ref($designs->{'alttext'}) eq 'HASH') {
 1944:                     $alttext = $designs->{'alttext'}{$img};
 1945:                 }
 1946:             }
 1947:         }
 1948:         $datatable .= '</td>';
 1949:         if ($designs->{$img} ne '') {
 1950:             $imgfile = $designs->{$img};
 1951: 	    $img_import = ($imgfile =~ m{^/adm/});
 1952:         } else {
 1953:             $imgfile = $defaults->{$img};
 1954:         }
 1955:         if ($imgfile) {
 1956:             my ($showfile,$fullsize);
 1957:             if ($imgfile =~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
 1958:                 my $urldir = $1;
 1959:                 my $filename = $2;
 1960:                 my @info = &Apache::lonnet::stat_file($designs->{$img});
 1961:                 if (@info) {
 1962:                     my $thumbfile = 'tn-'.$filename;
 1963:                     my @thumb=&Apache::lonnet::stat_file($urldir.'/'.$thumbfile);
 1964:                     if (@thumb) {
 1965:                         $showfile = $urldir.'/'.$thumbfile;
 1966:                     } else {
 1967:                         $showfile = $imgfile;
 1968:                     }
 1969:                 } else {
 1970:                     $showfile = '';
 1971:                 }
 1972:             } elsif ($imgfile =~ m-^/(adm/[^/]+)/([^/]+)$-) {
 1973:                 $showfile = $imgfile;
 1974:                 my $imgdir = $1;
 1975:                 my $filename = $2;
 1976:                 if (-e "$londocroot/$imgdir/tn-".$filename) {
 1977:                     $showfile = "/$imgdir/tn-".$filename;
 1978:                 } else {
 1979:                     my $input = $londocroot.$imgfile;
 1980:                     my $output = "$londocroot/$imgdir/tn-".$filename;
 1981:                     if (!-e $output) {
 1982:                         my ($width,$height) = &thumb_dimensions();
 1983:                         my ($fullwidth,$fullheight) = &check_dimensions($input);
 1984:                         if ($fullwidth ne '' && $fullheight ne '') {
 1985:                             if ($fullwidth > $width && $fullheight > $height) { 
 1986:                                 my $size = $width.'x'.$height;
 1987:                                 my @args = ('convert','-sample',$size,$input,$output);
 1988:                                 system({$args[0]} @args);
 1989:                                 $showfile = "/$imgdir/tn-".$filename;
 1990:                             }
 1991:                         }
 1992:                     }
 1993:                 }
 1994:             }
 1995:             if ($showfile) {
 1996:                 if ($showfile =~ m{^/(adm|res)/}) {
 1997:                     if ($showfile =~ m{^/res/}) {
 1998:                         my $local_showfile =
 1999:                             &Apache::lonnet::filelocation('',$showfile);
 2000:                         &Apache::lonnet::repcopy($local_showfile);
 2001:                     }
 2002:                     $showfile = &Apache::loncommon::lonhttpdurl($showfile);
 2003:                 }
 2004:                 if ($imgfile) {
 2005:                     if ($imgfile  =~ m{^/(adm|res)/}) {
 2006:                         if ($imgfile =~ m{^/res/}) {
 2007:                             my $local_imgfile =
 2008:                                 &Apache::lonnet::filelocation('',$imgfile);
 2009:                             &Apache::lonnet::repcopy($local_imgfile);
 2010:                         }
 2011:                         $fullsize = &Apache::loncommon::lonhttpdurl($imgfile);
 2012:                     } else {
 2013:                         $fullsize = $imgfile;
 2014:                     }
 2015:                 }
 2016:                 $datatable .= '<td>';
 2017:                 if ($img eq 'login') {
 2018:                     $datatable .= $login_hdr_pick;
 2019:                 } 
 2020:                 $datatable .= &image_changes($is_custom->{$img},$alt_text->{$img},$img_import,
 2021:                                              $showfile,$fullsize,$role,$img,$imgfile,$logincolors);
 2022:             } else {
 2023:                 $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 2024:                               &mt('Upload:').'<br />';
 2025:             }
 2026:         } else {
 2027:             $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 2028:                           &mt('Upload:').'<br />';
 2029:         }
 2030:         if ($switchserver) {
 2031:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2032:         } else {
 2033:             if ($img ne 'login') { # suppress file selection for Log-in header
 2034:                 $datatable .='&nbsp;<input type="file" name="'.$role.'_'.$img.'" />';
 2035:             }
 2036:         }
 2037:         if (($role eq 'login') && ($img ne 'login')) {
 2038:             $datatable .= ('&nbsp;' x2).' <span class="LC_nobreak"><label>'.$choices->{'alttext'}.':'.
 2039:                           '<input type="text" name="'.$role.'_alt_'.$img.'" size="10" value="'.$alttext.'" />'.
 2040:                           '</label></span>';
 2041:         }
 2042:         $datatable .= '</td></tr>';
 2043:     }
 2044:     $itemcount ++;
 2045:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2046:     $datatable .= '<tr'.$css_class.'>'.
 2047:                   '<td>'.$choices->{'bgs'}.'</td>';
 2048:     my $bgs_def;
 2049:     foreach my $item (@{$bgs}) {
 2050:         if (!$is_custom->{$item}) {
 2051:             $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>';
 2052:         }
 2053:     }
 2054:     if ($bgs_def) {
 2055:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$bgs_def.'</tr></table></td>';
 2056:     } else {
 2057:         $datatable .= '<td>&nbsp;</td>';
 2058:     }
 2059:     $datatable .= '<td class="LC_right_item">'.
 2060:                   '<table border="0"><tr>';
 2061: 
 2062:     foreach my $item (@{$bgs}) {
 2063:         $datatable .= '<td align="center">'.$choices->{$item};
 2064: 	my $color = $designs->{'bgs'}{$item} ? $designs->{'bgs'}{$item} : $defaults->{'bgs'}{$item};
 2065:         if ($designs->{'bgs'}{$item}) {
 2066:             $datatable .= '&nbsp;';
 2067:         }
 2068:         $datatable .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 2069:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 2070:     }
 2071:     $datatable .= '</tr></table></td></tr>';
 2072:     $itemcount ++;
 2073:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2074:     $datatable .= '<tr'.$css_class.'>'.
 2075:                   '<td>'.$choices->{'links'}.'</td>';
 2076:     my $links_def;
 2077:     foreach my $item (@{$links}) {
 2078:         if (!$is_custom->{$item}) {
 2079:             $links_def .= '<td>'.$choices->{$item}.'<br /><span class="css_default_'.$role.'_'.$item.'" style="color: '.$defaults->{'links'}{$item}.';">'.$defaults->{'links'}{$item}.'</span></td>';
 2080:         }
 2081:     }
 2082:     if ($links_def) {
 2083:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$links_def.'</tr></table></td>';
 2084:     } else {
 2085:         $datatable .= '<td>&nbsp;</td>';
 2086:     }
 2087:     $datatable .= '<td class="LC_right_item">'.
 2088:                   '<table border="0"><tr>';
 2089:     foreach my $item (@{$links}) {
 2090: 	my $color = $designs->{'links'}{$item} ? $designs->{'links'}{$item} : $defaults->{'links'}{$item};
 2091:         $datatable .= '<td align="center">'.$choices->{$item}."\n";
 2092:         if ($designs->{'links'}{$item}) {
 2093:             $datatable.='&nbsp;';
 2094:         }
 2095:         $datatable .= '<br /><input type="text" size="8" class="colorchooser" name="'.$role.'_'.$item.'" value="'.$color.
 2096:                       '" /></td>';
 2097:     }
 2098:     $$rowtotal += $itemcount;
 2099:     return $datatable;
 2100: }
 2101: 
 2102: sub logo_display_options {
 2103:     my ($img,$defaults,$designs) = @_;
 2104:     my $checkedon;
 2105:     if (ref($defaults) eq 'HASH') {
 2106:         if (ref($defaults->{'showlogo'}) eq 'HASH') {
 2107:             if ($defaults->{'showlogo'}{$img}) {
 2108:                 $checkedon = 'checked="checked" ';     
 2109:             }
 2110:         } 
 2111:     }
 2112:     if (ref($designs) eq 'HASH') {
 2113:         if (ref($designs->{'showlogo'}) eq 'HASH') {
 2114:             if (defined($designs->{'showlogo'}{$img})) {
 2115:                 if ($designs->{'showlogo'}{$img} == 0) {
 2116:                     $checkedon = '';
 2117:                 } elsif ($designs->{'showlogo'}{$img} == 1) {
 2118:                     $checkedon = 'checked="checked" ';
 2119:                 }
 2120:             }
 2121:         }
 2122:     }
 2123:     return '<br /><label>&nbsp;&nbsp;<input type="checkbox" name="'.
 2124:            'login_showlogo_'.$img.'" value="1" '.$checkedon.'/>'.
 2125:            &mt('show').'</label>'."\n";
 2126: }
 2127: 
 2128: sub login_header_options  {
 2129:     my ($img,$role,$defaults,$is_custom,$choices) = @_;
 2130:     my $output = '';
 2131:     if ((!$is_custom->{'textcol'}) || (!$is_custom->{'bgcol'})) {
 2132:         $output .= &mt('Text default(s):').'<br />';
 2133:         if (!$is_custom->{'textcol'}) {
 2134:             $output .= $choices->{'textcol'}.':&nbsp;'.$defaults->{'logintext'}{'textcol'}.
 2135:                        '&nbsp;&nbsp;&nbsp;';
 2136:         }
 2137:         if (!$is_custom->{'bgcol'}) {
 2138:             $output .= $choices->{'bgcol'}.':&nbsp;'.
 2139:                        '<span id="css_'.$role.'_font" style="background-color: '.
 2140:                        $defaults->{'logintext'}{'bgcol'}.';">&nbsp;&nbsp;&nbsp;</span>';
 2141:         }
 2142:         $output .= '<br />';
 2143:     }
 2144:     $output .='<br />';
 2145:     return $output;
 2146: }
 2147: 
 2148: sub login_text_colors {
 2149:     my ($img,$role,$logintext,$phase,$choices,$designs,$defaults) = @_;
 2150:     my $color_menu = '<table border="0"><tr>';
 2151:     foreach my $item (@{$logintext}) {
 2152:         $color_menu .= '<td align="center">'.$choices->{$item};
 2153:         my $color = $designs->{'logintext'}{$item} ? $designs->{'logintext'}{$item} : $defaults->{'logintext'}{$item};
 2154:         $color_menu .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 2155:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 2156:     }
 2157:     $color_menu .= '</tr></table><br />';
 2158:     return $color_menu;
 2159: }
 2160: 
 2161: sub image_changes {
 2162:     my ($is_custom,$alt_text,$img_import,$showfile,$fullsize,$role,$img,$imgfile,$logincolors) = @_;
 2163:     my $output;
 2164:     if ($img eq 'login') {
 2165:         $output = '</td><td>'.$logincolors; # suppress image for Log-in header
 2166:     } elsif (!$is_custom) {
 2167:         if ($img ne 'domlogo') {
 2168:             $output = &mt('Default image:').'<br />';
 2169:         } else {
 2170:             $output = &mt('Default in use:').'<br />';
 2171:         }
 2172:     }
 2173:     if ($img ne 'login') {
 2174:         if ($img_import) {
 2175:             $output .= '<input type="hidden" name="'.$role.'_import_'.$img.'" value="'.$imgfile.'" />';
 2176:         }
 2177:         $output .= '<a href="'.$fullsize.'" target="_blank"><img src="'.
 2178:                    $showfile.'" alt="'.$alt_text.'" border="0" /></a></td>';
 2179:         if ($is_custom) {
 2180:             $output .= '<td>'.$logincolors.'<span class="LC_nobreak"><label>'.
 2181:                        '<input type="checkbox" name="'.
 2182:                        $role.'_del_'.$img.'" value="1" />'.&mt('Delete?').
 2183:                        '</label>&nbsp;'.&mt('Replace:').'</span><br />';
 2184:         } else {
 2185:             $output .= '<td valign="middle">'.$logincolors.&mt('Upload:').'<br />';
 2186:         }
 2187:     }
 2188:     return $output;
 2189: }
 2190: 
 2191: sub print_quotas {
 2192:     my ($dom,$settings,$rowtotal,$action) = @_;
 2193:     my $context;
 2194:     if ($action eq 'quotas') {
 2195:         $context = 'tools';
 2196:     } else {
 2197:         $context = $action;
 2198:     }
 2199:     my ($datatable,$defaultquota,$authorquota,@usertools,@options,%validations);
 2200:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 2201:     my $typecount = 0;
 2202:     my ($css_class,%titles);
 2203:     if ($context eq 'requestcourses') {
 2204:         @usertools = ('official','unofficial','community','textbook');
 2205:         @options =('norequest','approval','validate','autolimit');
 2206:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
 2207:         %titles = &courserequest_titles();
 2208:     } elsif ($context eq 'requestauthor') {
 2209:         @usertools = ('author');
 2210:         @options = ('norequest','approval','automatic');
 2211:         %titles = &authorrequest_titles();
 2212:     } else {
 2213:         @usertools = ('aboutme','blog','webdav','portfolio');
 2214:         %titles = &tool_titles();
 2215:     }
 2216:     if (ref($types) eq 'ARRAY') {
 2217:         foreach my $type (@{$types}) {
 2218:             my ($currdefquota,$currauthorquota);
 2219:             unless (($context eq 'requestcourses') ||
 2220:                     ($context eq 'requestauthor')) {
 2221:                 if (ref($settings) eq 'HASH') {
 2222:                     if (ref($settings->{defaultquota}) eq 'HASH') {
 2223:                         $currdefquota = $settings->{defaultquota}->{$type};
 2224:                     } else {
 2225:                         $currdefquota = $settings->{$type};
 2226:                     }
 2227:                     if (ref($settings->{authorquota}) eq 'HASH') {
 2228:                         $currauthorquota = $settings->{authorquota}->{$type};
 2229:                     }
 2230:                 }
 2231:             }
 2232:             if (defined($usertypes->{$type})) {
 2233:                 $typecount ++;
 2234:                 $css_class = $typecount%2?' class="LC_odd_row"':'';
 2235:                 $datatable .= '<tr'.$css_class.'>'.
 2236:                               '<td>'.$usertypes->{$type}.'</td>'.
 2237:                               '<td class="LC_left_item">';
 2238:                 if ($context eq 'requestcourses') {
 2239:                     $datatable .= '<table><tr>';
 2240:                 }
 2241:                 my %cell;  
 2242:                 foreach my $item (@usertools) {
 2243:                     if ($context eq 'requestcourses') {
 2244:                         my ($curroption,$currlimit);
 2245:                         if (ref($settings) eq 'HASH') {
 2246:                             if (ref($settings->{$item}) eq 'HASH') {
 2247:                                 $curroption = $settings->{$item}->{$type};
 2248:                                 if ($curroption =~ /^autolimit=(\d*)$/) {
 2249:                                     $currlimit = $1; 
 2250:                                 }
 2251:                             }
 2252:                         }
 2253:                         if (!$curroption) {
 2254:                             $curroption = 'norequest';
 2255:                         }
 2256:                         $datatable .= '<th>'.$titles{$item}.'</th>';
 2257:                         foreach my $option (@options) {
 2258:                             my $val = $option;
 2259:                             if ($option eq 'norequest') {
 2260:                                 $val = 0;  
 2261:                             }
 2262:                             if ($option eq 'validate') {
 2263:                                 my $canvalidate = 0;
 2264:                                 if (ref($validations{$item}) eq 'HASH') { 
 2265:                                     if ($validations{$item}{$type}) {
 2266:                                         $canvalidate = 1;
 2267:                                     }
 2268:                                 }
 2269:                                 next if (!$canvalidate);
 2270:                             }
 2271:                             my $checked = '';
 2272:                             if ($option eq $curroption) {
 2273:                                 $checked = ' checked="checked"';
 2274:                             } elsif ($option eq 'autolimit') {
 2275:                                 if ($curroption =~ /^autolimit/) {
 2276:                                     $checked = ' checked="checked"';
 2277:                                 }                       
 2278:                             } 
 2279:                             $cell{$item} .= '<span class="LC_nobreak"><label>'.
 2280:                                   '<input type="radio" name="crsreq_'.$item.
 2281:                                   '_'.$type.'" value="'.$val.'"'.$checked.' />'.
 2282:                                   $titles{$option}.'</label>';
 2283:                             if ($option eq 'autolimit') {
 2284:                                 $cell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2285:                                                 $item.'_limit_'.$type.'" size="1" '.
 2286:                                                 'value="'.$currlimit.'" />';
 2287:                             }
 2288:                             $cell{$item} .= '</span> ';
 2289:                             if ($option eq 'autolimit') {
 2290:                                 $cell{$item} .= $titles{'unlimited'};
 2291:                             }
 2292:                         }
 2293:                     } elsif ($context eq 'requestauthor') {
 2294:                         my $curroption;
 2295:                         if (ref($settings) eq 'HASH') {
 2296:                             $curroption = $settings->{$type};
 2297:                         }
 2298:                         if (!$curroption) {
 2299:                             $curroption = 'norequest';
 2300:                         }
 2301:                         foreach my $option (@options) {
 2302:                             my $val = $option;
 2303:                             if ($option eq 'norequest') {
 2304:                                 $val = 0;
 2305:                             }
 2306:                             my $checked = '';
 2307:                             if ($option eq $curroption) {
 2308:                                 $checked = ' checked="checked"';
 2309:                             }
 2310:                             $datatable .= '<span class="LC_nobreak"><label>'.
 2311:                                   '<input type="radio" name="authorreq_'.$type.
 2312:                                   '" value="'.$val.'"'.$checked.' />'.
 2313:                                   $titles{$option}.'</label></span>&nbsp; ';
 2314:                         }
 2315:                     } else {
 2316:                         my $checked = 'checked="checked" ';
 2317:                         if (ref($settings) eq 'HASH') {
 2318:                             if (ref($settings->{$item}) eq 'HASH') {
 2319:                                 if ($settings->{$item}->{$type} == 0) {
 2320:                                     $checked = '';
 2321:                                 } elsif ($settings->{$item}->{$type} == 1) {
 2322:                                     $checked =  'checked="checked" ';
 2323:                                 }
 2324:                             }
 2325:                         }
 2326:                         $datatable .= '<span class="LC_nobreak"><label>'.
 2327:                                       '<input type="checkbox" name="'.$context.'_'.$item.
 2328:                                       '" value="'.$type.'" '.$checked.'/>'.$titles{$item}.
 2329:                                       '</label></span>&nbsp; ';
 2330:                     }
 2331:                 }
 2332:                 if ($context eq 'requestcourses') {
 2333:                     $datatable .= '</tr><tr>';
 2334:                     foreach my $item (@usertools) {
 2335:                         $datatable .= '<td style="vertical-align: top">'.$cell{$item}.'</td>';  
 2336:                     }
 2337:                     $datatable .= '</tr></table>';
 2338:                 }
 2339:                 $datatable .= '</td>';
 2340:                 unless (($context eq 'requestcourses') ||
 2341:                         ($context eq 'requestauthor')) {
 2342:                     $datatable .= 
 2343:                               '<td class="LC_right_item">'.
 2344:                               '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 2345:                               '<input type="text" name="quota_'.$type.
 2346:                               '" value="'.$currdefquota.
 2347:                               '" size="5" /></span>'.('&nbsp;' x 2).
 2348:                               '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 2349:                               '<input type="text" name="authorquota_'.$type.
 2350:                               '" value="'.$currauthorquota.
 2351:                               '" size="5" /></span></td>';
 2352:                 }
 2353:                 $datatable .= '</tr>';
 2354:             }
 2355:         }
 2356:     }
 2357:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 2358:         $defaultquota = '20';
 2359:         $authorquota = '500';
 2360:         if (ref($settings) eq 'HASH') {
 2361:             if (ref($settings->{'defaultquota'}) eq 'HASH') {
 2362:                 $defaultquota = $settings->{'defaultquota'}->{'default'};
 2363:             } elsif (defined($settings->{'default'})) {
 2364:                 $defaultquota = $settings->{'default'};
 2365:             }
 2366:             if (ref($settings->{'authorquota'}) eq 'HASH') {
 2367:                 $authorquota = $settings->{'authorquota'}->{'default'};
 2368:             }
 2369:         }
 2370:     }
 2371:     $typecount ++;
 2372:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 2373:     $datatable .= '<tr'.$css_class.'>'.
 2374:                   '<td>'.$othertitle.'</td>'.
 2375:                   '<td class="LC_left_item">';
 2376:     if ($context eq 'requestcourses') {
 2377:         $datatable .= '<table><tr>';
 2378:     }
 2379:     my %defcell;
 2380:     foreach my $item (@usertools) {
 2381:         if ($context eq 'requestcourses') {
 2382:             my ($curroption,$currlimit);
 2383:             if (ref($settings) eq 'HASH') {
 2384:                 if (ref($settings->{$item}) eq 'HASH') {
 2385:                     $curroption = $settings->{$item}->{'default'};
 2386:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 2387:                         $currlimit = $1;
 2388:                     }
 2389:                 }
 2390:             }
 2391:             if (!$curroption) {
 2392:                 $curroption = 'norequest';
 2393:             }
 2394:             $datatable .= '<th>'.$titles{$item}.'</th>';
 2395:             foreach my $option (@options) {
 2396:                 my $val = $option;
 2397:                 if ($option eq 'norequest') {
 2398:                     $val = 0;
 2399:                 }
 2400:                 if ($option eq 'validate') {
 2401:                     my $canvalidate = 0;
 2402:                     if (ref($validations{$item}) eq 'HASH') {
 2403:                         if ($validations{$item}{'default'}) {
 2404:                             $canvalidate = 1;
 2405:                         }
 2406:                     }
 2407:                     next if (!$canvalidate);
 2408:                 }
 2409:                 my $checked = '';
 2410:                 if ($option eq $curroption) {
 2411:                     $checked = ' checked="checked"';
 2412:                 } elsif ($option eq 'autolimit') {
 2413:                     if ($curroption =~ /^autolimit/) {
 2414:                         $checked = ' checked="checked"';
 2415:                     }
 2416:                 }
 2417:                 $defcell{$item} .= '<span class="LC_nobreak"><label>'.
 2418:                                   '<input type="radio" name="crsreq_'.$item.
 2419:                                   '_default" value="'.$val.'"'.$checked.' />'.
 2420:                                   $titles{$option}.'</label>';
 2421:                 if ($option eq 'autolimit') {
 2422:                     $defcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2423:                                        $item.'_limit_default" size="1" '.
 2424:                                        'value="'.$currlimit.'" />';
 2425:                 }
 2426:                 $defcell{$item} .= '</span> ';
 2427:                 if ($option eq 'autolimit') {
 2428:                     $defcell{$item} .= $titles{'unlimited'};
 2429:                 }
 2430:             }
 2431:         } elsif ($context eq 'requestauthor') {
 2432:             my $curroption;
 2433:             if (ref($settings) eq 'HASH') {
 2434:                 $curroption = $settings->{'default'};
 2435:             }
 2436:             if (!$curroption) {
 2437:                 $curroption = 'norequest';
 2438:             }
 2439:             foreach my $option (@options) {
 2440:                 my $val = $option;
 2441:                 if ($option eq 'norequest') {
 2442:                     $val = 0;
 2443:                 }
 2444:                 my $checked = '';
 2445:                 if ($option eq $curroption) {
 2446:                     $checked = ' checked="checked"';
 2447:                 }
 2448:                 $datatable .= '<span class="LC_nobreak"><label>'.
 2449:                               '<input type="radio" name="authorreq_default"'.
 2450:                               ' value="'.$val.'"'.$checked.' />'.
 2451:                               $titles{$option}.'</label></span>&nbsp; ';
 2452:             }
 2453:         } else {
 2454:             my $checked = 'checked="checked" ';
 2455:             if (ref($settings) eq 'HASH') {
 2456:                 if (ref($settings->{$item}) eq 'HASH') {
 2457:                     if ($settings->{$item}->{'default'} == 0) {
 2458:                         $checked = '';
 2459:                     } elsif ($settings->{$item}->{'default'} == 1) {
 2460:                         $checked = 'checked="checked" ';
 2461:                     }
 2462:                 }
 2463:             }
 2464:             $datatable .= '<span class="LC_nobreak"><label>'.
 2465:                           '<input type="checkbox" name="'.$context.'_'.$item.
 2466:                           '" value="default" '.$checked.'/>'.$titles{$item}.
 2467:                           '</label></span>&nbsp; ';
 2468:         }
 2469:     }
 2470:     if ($context eq 'requestcourses') {
 2471:         $datatable .= '</tr><tr>';
 2472:         foreach my $item (@usertools) {
 2473:             $datatable .= '<td style="vertical-align: top">'.$defcell{$item}.'</td>';
 2474:         }
 2475:         $datatable .= '</tr></table>';
 2476:     }
 2477:     $datatable .= '</td>';
 2478:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 2479:         $datatable .= '<td class="LC_right_item">'.
 2480:                       '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 2481:                       '<input type="text" name="defaultquota" value="'.
 2482:                       $defaultquota.'" size="5" /></span>'.('&nbsp;' x2).
 2483:                       '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 2484:                       '<input type="text" name="authorquota" value="'.
 2485:                       $authorquota.'" size="5" /></span></td>';
 2486:     }
 2487:     $datatable .= '</tr>';
 2488:     $typecount ++;
 2489:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 2490:     $datatable .= '<tr'.$css_class.'>'.
 2491:                   '<td>'.&mt('LON-CAPA Advanced Users').'<br />';
 2492:     if ($context eq 'requestcourses') {
 2493:         $datatable .= &mt('(overrides affiliation, if set)').
 2494:                       '</td>'.
 2495:                       '<td class="LC_left_item">'.
 2496:                       '<table><tr>';
 2497:     } else {
 2498:         $datatable .= &mt('(overrides affiliation, if checked)').
 2499:                       '</td>'.
 2500:                       '<td class="LC_left_item" colspan="2">'.
 2501:                       '<br />';
 2502:     }
 2503:     my %advcell;
 2504:     foreach my $item (@usertools) {
 2505:         if ($context eq 'requestcourses') {
 2506:             my ($curroption,$currlimit);
 2507:             if (ref($settings) eq 'HASH') {
 2508:                 if (ref($settings->{$item}) eq 'HASH') {
 2509:                     $curroption = $settings->{$item}->{'_LC_adv'};
 2510:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 2511:                         $currlimit = $1;
 2512:                     }
 2513:                 }
 2514:             }
 2515:             $datatable .= '<th>'.$titles{$item}.'</th>';
 2516:             my $checked = '';
 2517:             if ($curroption eq '') {
 2518:                 $checked = ' checked="checked"';
 2519:             }
 2520:             $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2521:                                '<input type="radio" name="crsreq_'.$item.
 2522:                                '__LC_adv" value=""'.$checked.' />'.
 2523:                                &mt('No override set').'</label></span>&nbsp; ';
 2524:             foreach my $option (@options) {
 2525:                 my $val = $option;
 2526:                 if ($option eq 'norequest') {
 2527:                     $val = 0;
 2528:                 }
 2529:                 if ($option eq 'validate') {
 2530:                     my $canvalidate = 0;
 2531:                     if (ref($validations{$item}) eq 'HASH') {
 2532:                         if ($validations{$item}{'_LC_adv'}) {
 2533:                             $canvalidate = 1;
 2534:                         }
 2535:                     }
 2536:                     next if (!$canvalidate);
 2537:                 }
 2538:                 my $checked = '';
 2539:                 if ($val eq $curroption) {
 2540:                     $checked = ' checked="checked"';
 2541:                 } elsif ($option eq 'autolimit') {
 2542:                     if ($curroption =~ /^autolimit/) {
 2543:                         $checked = ' checked="checked"';
 2544:                     }
 2545:                 }
 2546:                 $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2547:                                   '<input type="radio" name="crsreq_'.$item.
 2548:                                   '__LC_adv" value="'.$val.'"'.$checked.' />'.
 2549:                                   $titles{$option}.'</label>';
 2550:                 if ($option eq 'autolimit') {
 2551:                     $advcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2552:                                        $item.'_limit__LC_adv" size="1" '.
 2553:                                        'value="'.$currlimit.'" />';
 2554:                 }
 2555:                 $advcell{$item} .= '</span> ';
 2556:                 if ($option eq 'autolimit') {
 2557:                     $advcell{$item} .= $titles{'unlimited'};
 2558:                 }
 2559:             }
 2560:         } elsif ($context eq 'requestauthor') {
 2561:             my $curroption;
 2562:             if (ref($settings) eq 'HASH') {
 2563:                 $curroption = $settings->{'_LC_adv'};
 2564:             }
 2565:             my $checked = '';
 2566:             if ($curroption eq '') {
 2567:                 $checked = ' checked="checked"';
 2568:             }
 2569:             $datatable .= '<span class="LC_nobreak"><label>'.
 2570:                           '<input type="radio" name="authorreq__LC_adv"'.
 2571:                           ' value=""'.$checked.' />'.
 2572:                           &mt('No override set').'</label></span>&nbsp; ';
 2573:             foreach my $option (@options) {
 2574:                 my $val = $option;
 2575:                 if ($option eq 'norequest') {
 2576:                     $val = 0;
 2577:                 }
 2578:                 my $checked = '';
 2579:                 if ($val eq $curroption) {
 2580:                     $checked = ' checked="checked"';
 2581:                 }
 2582:                 $datatable .= '<span class="LC_nobreak"><label>'.
 2583:                               '<input type="radio" name="authorreq__LC_adv"'.
 2584:                               ' value="'.$val.'"'.$checked.' />'.
 2585:                               $titles{$option}.'</label></span>&nbsp; ';
 2586:             }
 2587:         } else {
 2588:             my $checked = 'checked="checked" ';
 2589:             if (ref($settings) eq 'HASH') {
 2590:                 if (ref($settings->{$item}) eq 'HASH') {
 2591:                     if ($settings->{$item}->{'_LC_adv'} == 0) {
 2592:                         $checked = '';
 2593:                     } elsif ($settings->{$item}->{'_LC_adv'} == 1) {
 2594:                         $checked = 'checked="checked" ';
 2595:                     }
 2596:                 }
 2597:             }
 2598:             $datatable .= '<span class="LC_nobreak"><label>'.
 2599:                           '<input type="checkbox" name="'.$context.'_'.$item.
 2600:                           '" value="_LC_adv" '.$checked.'/>'.$titles{$item}.
 2601:                           '</label></span>&nbsp; ';
 2602:         }
 2603:     }
 2604:     if ($context eq 'requestcourses') {
 2605:         $datatable .= '</tr><tr>';
 2606:         foreach my $item (@usertools) {
 2607:             $datatable .= '<td style="vertical-align: top">'.$advcell{$item}.'</td>';
 2608:         }
 2609:         $datatable .= '</tr></table>';
 2610:     }
 2611:     $datatable .= '</td></tr>';
 2612:     $$rowtotal += $typecount;
 2613:     return $datatable;
 2614: }
 2615: 
 2616: sub print_requestmail {
 2617:     my ($dom,$action,$settings,$rowtotal,$customcss,$rowstyle) = @_;
 2618:     my ($now,$datatable,%currapp);
 2619:     $now = time;
 2620:     if (ref($settings) eq 'HASH') {
 2621:         if (ref($settings->{'notify'}) eq 'HASH') {
 2622:             if ($settings->{'notify'}{'approval'} ne '') {
 2623:                 map {$currapp{$_}=1;} split(/,/,$settings->{'notify'}{'approval'});
 2624:             }
 2625:         }
 2626:     }
 2627:     my $numinrow = 2;
 2628:     my $css_class;
 2629:     if ($$rowtotal%2) {
 2630:         $css_class = 'LC_odd_row';
 2631:     }
 2632:     if ($customcss) {
 2633:         $css_class .= " $customcss";
 2634:     }
 2635:     $css_class =~ s/^\s+//;
 2636:     if ($css_class) {
 2637:         $css_class = ' class="'.$css_class.'"';
 2638:     }
 2639:     if ($rowstyle) {
 2640:         $css_class .= ' style="'.$rowstyle.'"';
 2641:     }
 2642:     my $text;
 2643:     if ($action eq 'requestcourses') {
 2644:         $text = &mt('Receive notification of course requests requiring approval');
 2645:     } elsif ($action eq 'requestauthor') {
 2646:         $text = &mt('Receive notification of Authoring Space requests requiring approval');
 2647:     } else {
 2648:        $text = &mt('Receive notification of queued requests for self-created user accounts requiring approval');
 2649:     }
 2650:     $datatable = '<tr'.$css_class.'>'.
 2651:                  ' <td>'.$text.'</td>'.
 2652:                  ' <td class="LC_left_item">';
 2653:     my ($numdc,$table,$rows) = &active_dc_picker($dom,$numinrow,'checkbox',
 2654:                                                  $action.'notifyapproval',%currapp);
 2655:     if ($numdc > 0) {
 2656:         $datatable .= $table;
 2657:     } else {
 2658:         $datatable .= &mt('There are no active Domain Coordinators');
 2659:     }
 2660:     $datatable .='</td></tr>';
 2661:     return $datatable;
 2662: }
 2663: 
 2664: sub print_studentcode {
 2665:     my ($settings,$rowtotal) = @_;
 2666:     my $rownum = 0; 
 2667:     my ($output,%current);
 2668:     my @crstypes = ('official','unofficial','community','textbook');
 2669:     if (ref($settings) eq 'HASH') {
 2670:         if (ref($settings->{'uniquecode'}) eq 'HASH') {
 2671:             foreach my $type (@crstypes) {
 2672:                 $current{$type} = $settings->{'uniquecode'}{$type};
 2673:             }
 2674:         }
 2675:     }
 2676:     $output .= '<tr>'.
 2677:                '<td class="LC_left_item">'.&mt('Generate unique six character code as course identifier?').'</td>'.
 2678:                '<td class="LC_left_item">';
 2679:     foreach my $type (@crstypes) {
 2680:         my $check = ' ';
 2681:         if ($current{$type}) {
 2682:             $check = ' checked="checked" ';
 2683:         }
 2684:         $output .= '<span class="LC_nobreak"><label>'.
 2685:                    '<input type="checkbox" name="uniquecode" value="'.$type.'"'.$check.'/>'.
 2686:                    &mt($type).'</label></span>'.('&nbsp;'x2).' ';
 2687:     }
 2688:     $output .= '</td></tr>';
 2689:     $$rowtotal ++;
 2690:     return $output;
 2691: }
 2692: 
 2693: sub print_textbookcourses {
 2694:     my ($dom,$type,$settings,$rowtotal) = @_;
 2695:     my $rownum = 0;
 2696:     my $css_class;
 2697:     my $itemcount = 1;
 2698:     my $maxnum = 0;
 2699:     my $bookshash;
 2700:     if (ref($settings) eq 'HASH') {
 2701:         $bookshash = $settings->{$type};
 2702:     }
 2703:     my %ordered;
 2704:     if (ref($bookshash) eq 'HASH') {
 2705:         foreach my $item (keys(%{$bookshash})) {
 2706:             if (ref($bookshash->{$item}) eq 'HASH') {
 2707:                 my $num = $bookshash->{$item}{'order'};
 2708:                 $ordered{$num} = $item;
 2709:             }
 2710:         }
 2711:     }
 2712:     my $confname = $dom.'-domainconfig';
 2713:     my $switchserver = &check_switchserver($dom,$confname);
 2714:     my $maxnum = scalar(keys(%ordered));
 2715:     my $datatable;
 2716:     if (keys(%ordered)) {
 2717:         my @items = sort { $a <=> $b } keys(%ordered);
 2718:         for (my $i=0; $i<@items; $i++) {
 2719:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2720:             my $key = $ordered{$items[$i]};
 2721:             my %coursehash=&Apache::lonnet::coursedescription($key);
 2722:             my $coursetitle = $coursehash{'description'};
 2723:             my ($subject,$title,$author,$publisher,$image,$imgsrc,$cdom,$cnum);
 2724:             if (ref($bookshash->{$key}) eq 'HASH') {
 2725:                 $subject = $bookshash->{$key}->{'subject'};
 2726:                 $title = $bookshash->{$key}->{'title'};
 2727:                 if ($type eq 'textbooks') {
 2728:                     $publisher = $bookshash->{$key}->{'publisher'};
 2729:                     $author = $bookshash->{$key}->{'author'};
 2730:                     $image = $bookshash->{$key}->{'image'};
 2731:                     if ($image ne '') {
 2732:                         my ($path,$imagefile) = ($image =~ m{^(.+)/([^/]+)$});
 2733:                         my $imagethumb = "$path/tn-".$imagefile;
 2734:                         $imgsrc = '<img src="'.$imagethumb.'" alt="'.&mt('Textbook image').'" />';
 2735:                     }
 2736:                 }
 2737:             }
 2738:             my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type".'_'."$key','$type'".');"';
 2739:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 2740:                          .'<select name="'.$type.'_'.$key.'"'.$chgstr.'>';
 2741:             for (my $k=0; $k<=$maxnum; $k++) {
 2742:                 my $vpos = $k+1;
 2743:                 my $selstr;
 2744:                 if ($k == $i) {
 2745:                     $selstr = ' selected="selected" ';
 2746:                 }
 2747:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2748:             }
 2749:             $datatable .= '</select>'.('&nbsp;'x2).
 2750:                 '<label><input type="checkbox" name="'.$type.'_del" value="'.$key.'" />'.
 2751:                 &mt('Delete?').'</label></span></td>'.
 2752:                 '<td colspan="2">'.
 2753:                 '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_subject_'.$i.'" value="'.$subject.'" /></span> '.
 2754:                 ('&nbsp;'x2).
 2755:                 '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_title_'.$i.'" value="'.$title.'" /></span> ';
 2756:             if ($type eq 'textbooks') {
 2757:                 $datatable .= ('&nbsp;'x2).
 2758:                               '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_publisher_'.$i.'" value="'.$publisher.'" /></span> '.
 2759:                               ('&nbsp;'x2).
 2760:                               '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_author_'.$i.'" value="'.$author.'" /></span> '.
 2761:                               ('&nbsp;'x2).
 2762:                               '<span class="LC_nobreak">'.&mt('Thumbnail:');
 2763:                 if ($image) {
 2764:                     $datatable .= $imgsrc.
 2765:                                   '<label><input type="checkbox" name="'.$type.'_image_del"'.
 2766:                                   ' value="'.$key.'" />'.&mt('Delete?').'</label></span> '.
 2767:                                   '<span class="LC_nobreak">&nbsp;'.&mt('Replace:').'&nbsp;';
 2768:                 }
 2769:                 if ($switchserver) {
 2770:                     $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2771:                 } else {
 2772:                     $datatable .= '<input type="file" name="'.$type.'_image_'.$i.'" value="" />';
 2773:                 }
 2774:             }
 2775:             $datatable .= '<input type="hidden" name="'.$type.'_id_'.$i.'" value="'.$type.'_'.$key.'" /></span> '.
 2776:                           '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 2777:                           $coursetitle.'</span></td></tr>'."\n";
 2778:             $itemcount ++;
 2779:         }
 2780:     }
 2781:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2782:     my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type"."_addbook_pos','$type'".');"';
 2783:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 2784:                   '<input type="hidden" name="'.$type.'_maxnum" value="'.$maxnum.'" />'."\n".
 2785:                   '<select name="'.$type.'_addbook_pos"'.$chgstr.'>';
 2786:     for (my $k=0; $k<$maxnum+1; $k++) {
 2787:         my $vpos = $k+1;
 2788:         my $selstr;
 2789:         if ($k == $maxnum) {
 2790:             $selstr = ' selected="selected" ';
 2791:         }
 2792:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2793:     }
 2794:     $datatable .= '</select>&nbsp;'."\n".
 2795:                   '<input type="checkbox" name="'.$type.'_addbook" value="1" />'.&mt('Add').'</span></td>'."\n".
 2796:                   '<td colspan="2">'.
 2797:                   '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_addbook_subject" value="" /></span> '."\n".
 2798:                   ('&nbsp;'x2).
 2799:                   '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_addbook_title" value="" /></span> '."\n".
 2800:                   ('&nbsp;'x2);
 2801:     if ($type eq 'textbooks') {
 2802:         $datatable .= '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_addbook_publisher" value="" /></span> '."\n".
 2803:                       ('&nbsp;'x2).
 2804:                       '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_addbook_author" value="" /></span> '."\n".
 2805:                       ('&nbsp;'x2).
 2806:                       '<span class="LC_nobreak">'.&mt('Image:').'&nbsp;';
 2807:         if ($switchserver) {
 2808:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2809:         } else {
 2810:             $datatable .= '<input type="file" name="'.$type.'_addbook_image" value="" />';
 2811:         }
 2812:         $datatable .= '</span>'."\n";
 2813:     }
 2814:     $datatable .= '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 2815:                   &Apache::loncommon::select_dom_form($env{'request.role.domain'},$type.'_addbook_cdom').
 2816:                   '<input type="text" size="25" name="'.$type.'_addbook_cnum" value="" />'.
 2817:                   &Apache::loncommon::selectcourse_link
 2818:                       ('display',$type.'_addbook_cnum',$type.'_addbook_cdom',undef,undef,undef,'Course').
 2819:                   '</span></td>'."\n".
 2820:                   '</tr>'."\n";
 2821:     $itemcount ++;
 2822:     return $datatable;
 2823: }
 2824: 
 2825: sub textbookcourses_javascript {
 2826:     my ($settings) = @_;
 2827:     return unless(ref($settings) eq 'HASH');
 2828:     my (%ordered,%total,%jstext);
 2829:     foreach my $type ('textbooks','templates') {
 2830:         $total{$type} = 0;
 2831:         if (ref($settings->{$type}) eq 'HASH') {
 2832:             foreach my $item (keys(%{$settings->{$type}})) {
 2833:                 if (ref($settings->{$type}->{$item}) eq 'HASH') {
 2834:                     my $num = $settings->{$type}->{$item}{'order'};
 2835:                     $ordered{$type}{$num} = $item;
 2836:                 }
 2837:             }
 2838:             $total{$type} = scalar(keys(%{$settings->{$type}}));
 2839:         }
 2840:         my @jsarray = ();
 2841:         foreach my $item (sort {$a <=> $b } (keys(%{$ordered{$type}}))) {
 2842:             push(@jsarray,$ordered{$type}{$item});
 2843:         }
 2844:         $jstext{$type} = '    var '.$type.' = Array('."'".join("','",@jsarray)."'".');'."\n";
 2845:     }
 2846:     return <<"ENDSCRIPT";
 2847: <script type="text/javascript">
 2848: // <![CDATA[
 2849: function reorderBooks(form,item,caller) {
 2850:     var changedVal;
 2851: $jstext{'textbooks'};
 2852: $jstext{'templates'};
 2853:     var newpos;
 2854:     var maxh;
 2855:     if (caller == 'textbooks') {  
 2856:         newpos = 'textbooks_addbook_pos';
 2857:         maxh = 1 + $total{'textbooks'};
 2858:     } else {
 2859:         newpos = 'templates_addbook_pos';
 2860:         maxh = 1 + $total{'templates'};
 2861:     }
 2862:     var current = new Array;
 2863:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 2864:     if (item == newpos) {
 2865:         changedVal = newitemVal;
 2866:     } else {
 2867:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 2868:         current[newitemVal] = newpos;
 2869:     }
 2870:     if (caller == 'textbooks') {
 2871:         for (var i=0; i<textbooks.length; i++) {
 2872:             var elementName = 'textbooks_'+textbooks[i];
 2873:             if (elementName != item) {
 2874:                 if (form.elements[elementName]) {
 2875:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 2876:                     current[currVal] = elementName;
 2877:                 }
 2878:             }
 2879:         }
 2880:     }
 2881:     if (caller == 'templates') {
 2882:         for (var i=0; i<templates.length; i++) {
 2883:             var elementName = 'templates_'+templates[i];
 2884:             if (elementName != item) {
 2885:                 if (form.elements[elementName]) {
 2886:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 2887:                     current[currVal] = elementName;
 2888:                 }
 2889:             }
 2890:         }
 2891:     }
 2892:     var oldVal;
 2893:     for (var j=0; j<maxh; j++) {
 2894:         if (current[j] == undefined) {
 2895:             oldVal = j;
 2896:         }
 2897:     }
 2898:     if (oldVal < changedVal) {
 2899:         for (var k=oldVal+1; k<=changedVal ; k++) {
 2900:            var elementName = current[k];
 2901:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 2902:         }
 2903:     } else {
 2904:         for (var k=changedVal; k<oldVal; k++) {
 2905:             var elementName = current[k];
 2906:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 2907:         }
 2908:     }
 2909:     return;
 2910: }
 2911: 
 2912: // ]]>
 2913: </script>
 2914: 
 2915: ENDSCRIPT
 2916: }
 2917: 
 2918: sub ltitools_javascript {
 2919:     my ($settings) = @_;
 2920:     my $togglejs = &ltitools_toggle_js();
 2921:     unless (ref($settings) eq 'HASH') {
 2922:         return $togglejs;
 2923:     }
 2924:     my (%ordered,$total,%jstext);
 2925:     $total = 0;
 2926:     foreach my $item (keys(%{$settings})) {
 2927:         if (ref($settings->{$item}) eq 'HASH') {
 2928:             my $num = $settings->{$item}{'order'};
 2929:             $ordered{$num} = $item;
 2930:         }
 2931:     }
 2932:     $total = scalar(keys(%{$settings}));
 2933:     my @jsarray = ();
 2934:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 2935:         push(@jsarray,$ordered{$item});
 2936:     }
 2937:     my $jstext = '    var ltitools = Array('."'".join("','",@jsarray)."'".');'."\n";
 2938:     return <<"ENDSCRIPT";
 2939: <script type="text/javascript">
 2940: // <![CDATA[
 2941: function reorderLTITools(form,item) {
 2942:     var changedVal;
 2943: $jstext
 2944:     var newpos = 'ltitools_add_pos';
 2945:     var maxh = 1 + $total;
 2946:     var current = new Array;
 2947:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 2948:     if (item == newpos) {
 2949:         changedVal = newitemVal;
 2950:     } else {
 2951:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 2952:         current[newitemVal] = newpos;
 2953:     }
 2954:     for (var i=0; i<ltitools.length; i++) {
 2955:         var elementName = 'ltitools_'+ltitools[i];
 2956:         if (elementName != item) {
 2957:             if (form.elements[elementName]) {
 2958:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 2959:                 current[currVal] = elementName;
 2960:             }
 2961:         }
 2962:     }
 2963:     var oldVal;
 2964:     for (var j=0; j<maxh; j++) {
 2965:         if (current[j] == undefined) {
 2966:             oldVal = j;
 2967:         }
 2968:     }
 2969:     if (oldVal < changedVal) {
 2970:         for (var k=oldVal+1; k<=changedVal ; k++) {
 2971:            var elementName = current[k];
 2972:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 2973:         }
 2974:     } else {
 2975:         for (var k=changedVal; k<oldVal; k++) {
 2976:             var elementName = current[k];
 2977:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 2978:         }
 2979:     }
 2980:     return;
 2981: }
 2982: 
 2983: // ]]>
 2984: </script>
 2985: 
 2986: $togglejs
 2987: 
 2988: ENDSCRIPT
 2989: }
 2990: 
 2991: sub ltitools_toggle_js {
 2992:     return <<"ENDSCRIPT";
 2993: <script type="text/javascript">
 2994: // <![CDATA[
 2995: 
 2996: function toggleLTITools(form,setting,item) {
 2997:     var radioname = '';
 2998:     var divid = '';
 2999:     if (setting == 'user') {
 3000:         divid = 'ltitools_'+setting+'_div_'+item;
 3001:         var checkid = 'ltitools_'+setting+'_field_'+item;
 3002:         if (document.getElementById(divid)) {
 3003:             if (document.getElementById(checkid)) {
 3004:                 if (document.getElementById(checkid).checked) {
 3005:                     document.getElementById(divid).style.display = 'inline-block';
 3006:                 } else {
 3007:                     document.getElementById(divid).style.display = 'none';
 3008:                 }
 3009:             }
 3010:         }
 3011:     }
 3012:     return;
 3013: }
 3014: // ]]>
 3015: </script>
 3016: 
 3017: ENDSCRIPT
 3018: }
 3019: 
 3020: sub wafproxy_javascript {
 3021:     my ($dom) = @_;
 3022:     return <<"ENDSCRIPT";
 3023: <script type="text/javascript">
 3024: // <![CDATA[
 3025: function updateWAF() {
 3026:     if (document.getElementById('wafproxy_remoteip')) {
 3027:         var wafremote = 0;
 3028:         if (document.display.wafproxy_remoteip.options[document.display.wafproxy_remoteip.selectedIndex].value == 'h') {
 3029:             wafremote = 1;
 3030:         }
 3031:         var fields = new Array('header','trust');
 3032:         for (var i=0; i<fields.length; i++) {
 3033:             if (document.getElementById('wafproxy_'+fields[i])) {
 3034:                 if (wafremote == 1) {
 3035:                     document.getElementById('wafproxy_'+fields[i]).style.display = 'table-row';
 3036:                 }
 3037:                 else {
 3038:                     document.getElementById('wafproxy_'+fields[i]).style.display = 'none';
 3039:                 }
 3040:             }
 3041:         }
 3042:         if (document.getElementById('wafproxyranges_$dom')) {
 3043:             if (wafremote == 1) {
 3044:                 document.getElementById('wafproxyranges_$dom').style.display = 'inline-block';
 3045:             } else {
 3046:                 for (var i=0; i<document.display.wafproxy_vpnaccess.length; i++) {
 3047:                     if (document.display.wafproxy_vpnaccess[i].checked) {
 3048:                         if (document.display.wafproxy_vpnaccess[i].value == 0) {
 3049:                             document.getElementById('wafproxyranges_$dom').style.display = 'none';
 3050:                         }
 3051:                     }
 3052:                 }
 3053:             }
 3054:         }
 3055:     }
 3056:     return;
 3057: }
 3058: 
 3059: function checkWAF() {
 3060:     if (document.getElementById('wafproxy_remoteip')) {
 3061:         var wafvpn = 0;
 3062:         for (var i=0; i<document.display.wafproxy_vpnaccess.length; i++) {
 3063:             if (document.display.wafproxy_vpnaccess[i].checked) {
 3064:                 if (document.display.wafproxy_vpnaccess[i].value == 1) {
 3065:                     wafvpn = 1;
 3066:                 }
 3067:                 break;
 3068:             }
 3069:         }
 3070:         var vpn = new Array('vpnint','vpnext');
 3071:         for (var i=0; i<vpn.length; i++) {
 3072:             if (document.getElementById('wafproxy_show_'+vpn[i])) {
 3073:                 if (wafvpn == 1) {
 3074:                     document.getElementById('wafproxy_show_'+vpn[i]).style.display = 'table-row';
 3075:                 }
 3076:                 else {
 3077:                     document.getElementById('wafproxy_show_'+vpn[i]).style.display = 'none';
 3078:                 }
 3079:             }
 3080:         }
 3081:         if (document.getElementById('wafproxyranges_$dom')) {
 3082:             if (wafvpn == 1) {
 3083:                 document.getElementById('wafproxyranges_$dom').style.display = 'inline-block';
 3084:             }
 3085:             else if (document.display.wafproxy_remoteip.options[document.display.wafproxy_remoteip.selectedIndex].value != 'h') {
 3086:                 document.getElementById('wafproxyranges_$dom').style.display = 'none';
 3087:             }
 3088:         }
 3089:     }
 3090:     return;
 3091: }
 3092: 
 3093: function toggleWAF() {
 3094:     if (document.getElementById('wafproxy_table')) {
 3095:         var wafproxy = 0;
 3096:         for (var i=0; i<document.display.wafproxy_${dom}.length; i++) {
 3097:              if (document.display.wafproxy_${dom}[i].checked) {
 3098:                  if (document.display.wafproxy_${dom}[i].value == 1) {
 3099:                      wafproxy = 1;
 3100:                      break;
 3101:                 }
 3102:             }
 3103:         }
 3104:         if (wafproxy == 1) {
 3105:             document.getElementById('wafproxy_table').style.display='inline';
 3106:         }
 3107:         else {
 3108:            document.getElementById('wafproxy_table').style.display='none';
 3109:         }
 3110:         if (document.getElementById('wafproxyrow_${dom}')) {
 3111:             if (wafproxy == 1) {
 3112:                 document.getElementById('wafproxyrow_${dom}').style.display = 'table-row';
 3113:             }
 3114:             else {
 3115:                 document.getElementById('wafproxyrow_${dom}').style.display = 'none';
 3116:             }
 3117:         }
 3118:         if (document.getElementById('nowafproxyrow_$dom')) {
 3119:             if (wafproxy == 1) {
 3120:                 document.getElementById('nowafproxyrow_${dom}').style.display = 'none';
 3121:             }
 3122:             else {
 3123:                 document.getElementById('nowafproxyrow_${dom}').style.display = 'table-row';
 3124:             }
 3125:         }
 3126:     }
 3127:     return;
 3128: }
 3129: // ]]>
 3130: </script>
 3131: 
 3132: ENDSCRIPT
 3133: }
 3134: 
 3135: sub lti_javascript {
 3136:     my ($dom,$settings) = @_;
 3137:     my $togglejs = &lti_toggle_js($dom);
 3138:     my $linkprot_js = &Apache::courseprefs::linkprot_javascript();
 3139:     return <<"ENDSCRIPT";
 3140: <script type="text/javascript">
 3141: // <![CDATA[
 3142: 
 3143: $linkprot_js
 3144: 
 3145: // ]]>
 3146: </script>
 3147: 
 3148: $togglejs
 3149: 
 3150: ENDSCRIPT
 3151: }
 3152: 
 3153: sub lti_toggle_js {
 3154:     my ($dom) = @_;
 3155:     my %servers = &Apache::lonnet::get_servers($dom,'library');
 3156:     my $primary = &Apache::lonnet::domain($dom,'primary');
 3157:     my $course_servers = "'".join("','",keys(%servers))."'";
 3158:     return <<"ENDSCRIPT";
 3159: <script type="text/javascript">
 3160: // <![CDATA[
 3161: function toggleLTIEncKey(form) {
 3162:     var shownhosts = new Array();
 3163:     var hiddenhosts = new Array();
 3164:     var forcourse = new Array($course_servers);
 3165:     var fromdomain = '$primary';
 3166:     var crsradio = form.elements['ltisec_crslinkprot'];
 3167:     if (crsradio.length) {
 3168:         for (var i=0; i<crsradio.length; i++) {
 3169:             if (crsradio[i].checked) {
 3170:                 if (crsradio[i].value == 1) {
 3171:                     if (forcourse.length > 0) {
 3172:                         for (var j=0; j<forcourse.length; j++) {
 3173:                             if (!shownhosts.includes(forcourse[j])) {
 3174:                                 shownhosts.push(forcourse[j]);
 3175:                             }
 3176:                         }
 3177:                     }
 3178:                 } else {
 3179:                     if (forcourse.length > 0) {
 3180:                         for (var j=0; j<forcourse.length; j++) {
 3181:                             if (!hiddenhosts.includes(forcourse[j])) {
 3182:                                 hiddenhosts.push(forcourse[j]);
 3183:                             }
 3184:                         }
 3185:                     }
 3186:                 }
 3187:             }
 3188:         }
 3189:     }
 3190:     var domradio = form.elements['ltisec_domlinkprot'];
 3191:     if (domradio.length) {
 3192:         for (var i=0; i<domradio.length; i++) {
 3193:             if (domradio[i].checked) {
 3194:                 if (domradio[i].value == 1) {
 3195:                     if (!shownhosts.includes(fromdomain)) {
 3196:                         shownhosts.push(fromdomain);
 3197:                     }
 3198:                 } else {
 3199:                     if (!hiddenhosts.includes(fromdomain)) {
 3200:                         hiddenhosts.push(fromdomain);
 3201:                     }
 3202:                 }
 3203:             }
 3204:         }
 3205:     }
 3206:     if (shownhosts.length > 0) {
 3207:         for (var i=0; i<shownhosts.length; i++) {
 3208:             if (document.getElementById('ltisec_info_'+shownhosts[i])) {
 3209:                 document.getElementById('ltisec_info_'+shownhosts[i]).style.display = 'block';
 3210:             }
 3211:         }
 3212:         if (document.getElementById('ltisec_noprivkey')) {
 3213:             document.getElementById('ltisec_noprivkey').style.display = 'none';
 3214:         }
 3215:     } else {
 3216:         if (document.getElementById('ltisec_noprivkey')) {
 3217:             document.getElementById('ltisec_noprivkey').style.display = 'inline-block';
 3218:         }
 3219:     }
 3220:     if (hiddenhosts.length > 0) {
 3221:         for (var i=0; i<hiddenhosts.length; i++) {
 3222:             if (!shownhosts.includes(hiddenhosts[i])) {
 3223:                 if (document.getElementById('ltisec_info_'+hiddenhosts[i])) {
 3224:                     document.getElementById('ltisec_info_'+hiddenhosts[i]).style.display = 'none';
 3225:                 }
 3226:             }
 3227:         }
 3228:     }
 3229:     return;
 3230: }
 3231: 
 3232: function togglePrivKey(form,hostid) {
 3233:     var radioname = '';
 3234:     var currdivid = '';
 3235:     var newdivid = '';
 3236:     if ((document.getElementById('ltisec_divcurrprivkey_'+hostid)) &&
 3237:         (document.getElementById('ltisec_divchgprivkey_'+hostid))) {
 3238:         currdivid = document.getElementById('ltisec_divcurrprivkey_'+hostid);
 3239:         newdivid = document.getElementById('ltisec_divchgprivkey_'+hostid);
 3240:         radioname = form.elements['ltisec_changeprivkey_'+hostid];
 3241:         if (radioname) {
 3242:             if (radioname.length > 0) {
 3243:                 var setvis;
 3244:                 for (var i=0; i<radioname.length; i++) {
 3245:                     if (radioname[i].checked == true) {
 3246:                         if (radioname[i].value == 1) {
 3247:                             newdivid.style.display = 'inline-block';
 3248:                             currdivid.style.display = 'none';
 3249:                             setvis = 1;
 3250:                         }
 3251:                         break;
 3252:                     }
 3253:                 }
 3254:                 if (!setvis) {
 3255:                     newdivid.style.display = 'none';
 3256:                     currdivid.style.display = 'inline-block';
 3257:                 }
 3258:             }
 3259:         }
 3260:     }
 3261: }
 3262: 
 3263: // ]]>
 3264: </script>
 3265: 
 3266: ENDSCRIPT
 3267: }
 3268: 
 3269: sub autoupdate_javascript {
 3270:     return <<"ENDSCRIPT";
 3271: <script type="text/javascript">
 3272: // <![CDATA[
 3273: function toggleLastActiveDays(form) {
 3274:     var radioname = 'lastactive';
 3275:     var divid = 'lastactive_div';
 3276:     var num = form.elements[radioname].length;
 3277:     if (num) {
 3278:         var setvis = '';
 3279:         for (var i=0; i<num; i++) {
 3280:             if (form.elements[radioname][i].checked) {
 3281:                 if (form.elements[radioname][i].value == '1') {
 3282:                     if (document.getElementById(divid)) {
 3283:                         document.getElementById(divid).style.display = 'inline-block';
 3284:                     }
 3285:                     setvis = 1;
 3286:                 }
 3287:                 break;
 3288:             }
 3289:         }
 3290:         if (!setvis) {
 3291:             if (document.getElementById(divid)) {
 3292:                 document.getElementById(divid).style.display = 'none';
 3293:             }
 3294:         }
 3295:     }
 3296:     return;
 3297: }
 3298: // ]]>
 3299: </script>
 3300: 
 3301: ENDSCRIPT
 3302: }
 3303: 
 3304: sub autoenroll_javascript {
 3305:     return <<"ENDSCRIPT";
 3306: <script type="text/javascript">
 3307: // <![CDATA[
 3308: function toggleFailsafe(form) {
 3309:     var radioname = 'autoenroll_failsafe';
 3310:     var divid = 'autoenroll_failsafe_div';
 3311:     var num = form.elements[radioname].length;
 3312:     if (num) {
 3313:         var setvis = '';
 3314:         for (var i=0; i<num; i++) {
 3315:             if (form.elements[radioname][i].checked) {
 3316:                 if ((form.elements[radioname][i].value == 'zero') || (form.elements[radioname][i].value == 'any')) {
 3317:                     if (document.getElementById(divid)) {
 3318:                         document.getElementById(divid).style.display = 'inline-block';
 3319:                     }
 3320:                     setvis = 1;
 3321:                 }
 3322:                 break;
 3323:             }
 3324:         }
 3325:         if (!setvis) {
 3326:             if (document.getElementById(divid)) {
 3327:                 document.getElementById(divid).style.display = 'none';
 3328:             }
 3329:         }
 3330:     }
 3331:     return;
 3332: }
 3333: // ]]>
 3334: </script>
 3335: 
 3336: ENDSCRIPT
 3337: }
 3338: 
 3339: sub saml_javascript {
 3340:     return <<"ENDSCRIPT";
 3341: <script type="text/javascript">
 3342: // <![CDATA[
 3343: function toggleSamlOptions(form,hostid) {
 3344:     var radioname = 'saml_'+hostid;
 3345:     var tablecellon = 'samloptionson_'+hostid;
 3346:     var tablecelloff = 'samloptionsoff_'+hostid;
 3347:     var num = form.elements[radioname].length;
 3348:     if (num) {
 3349:         var setvis = '';
 3350:         for (var i=0; i<num; i++) {
 3351:             if (form.elements[radioname][i].checked) {
 3352:                 if (form.elements[radioname][i].value == '1') {
 3353:                     if (document.getElementById(tablecellon)) {
 3354:                         document.getElementById(tablecellon).style.display='';
 3355:                     }
 3356:                     if (document.getElementById(tablecelloff)) {
 3357:                         document.getElementById(tablecelloff).style.display='none';
 3358:                     }
 3359:                     setvis = 1;
 3360:                 }
 3361:                 break;
 3362:             }
 3363:         }
 3364:         if (!setvis) {
 3365:             if (document.getElementById(tablecellon)) {
 3366:                 document.getElementById(tablecellon).style.display='none';
 3367:             }
 3368:             if (document.getElementById(tablecelloff)) {
 3369:                 document.getElementById(tablecelloff).style.display='';
 3370:             }
 3371:         }
 3372:     }
 3373:     return;
 3374: }
 3375: // ]]>
 3376: </script>
 3377: 
 3378: ENDSCRIPT
 3379: }
 3380: 
 3381: sub ipaccess_javascript {
 3382:     my ($settings) = @_;
 3383:     my (%ordered,$total,%jstext);
 3384:     $total = 0;
 3385:     if (ref($settings) eq 'HASH') {
 3386:         foreach my $item (keys(%{$settings})) {
 3387:             if (ref($settings->{$item}) eq 'HASH') {
 3388:                 my $num = $settings->{$item}{'order'};
 3389:                 $ordered{$num} = $item;
 3390:             }
 3391:         }
 3392:         $total = scalar(keys(%{$settings}));
 3393:     }
 3394:     my @jsarray = ();
 3395:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3396:         push(@jsarray,$ordered{$item});
 3397:     }
 3398:     my $jstext = '    var ipaccess = Array('."'".join("','",@jsarray)."'".');'."\n";
 3399:     return <<"ENDSCRIPT";
 3400: <script type="text/javascript">
 3401: // <![CDATA[
 3402: function reorderIPaccess(form,item) {
 3403:     var changedVal;
 3404: $jstext
 3405:     var newpos = 'ipaccess_pos_add';
 3406:     var maxh = 1 + $total;
 3407:     var current = new Array;
 3408:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 3409:     if (item == newpos) {
 3410:         changedVal = newitemVal;
 3411:     } else {
 3412:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3413:         current[newitemVal] = newpos;
 3414:     }
 3415:     for (var i=0; i<ipaccess.length; i++) {
 3416:         var elementName = 'ipaccess_pos_'+ipaccess[i];
 3417:         if (elementName != item) {
 3418:             if (form.elements[elementName]) {
 3419:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3420:                 current[currVal] = elementName;
 3421:             }
 3422:         }
 3423:     }
 3424:     var oldVal;
 3425:     for (var j=0; j<maxh; j++) {
 3426:         if (current[j] == undefined) {
 3427:             oldVal = j;
 3428:         }
 3429:     }
 3430:     if (oldVal < changedVal) {
 3431:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3432:            var elementName = current[k];
 3433:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3434:         }
 3435:     } else {
 3436:         for (var k=changedVal; k<oldVal; k++) {
 3437:             var elementName = current[k];
 3438:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3439:         }
 3440:     }
 3441:     return;
 3442: }
 3443: // ]]>
 3444: </script>
 3445: 
 3446: ENDSCRIPT
 3447: }
 3448: 
 3449: sub print_autoenroll {
 3450:     my ($dom,$settings,$rowtotal) = @_;
 3451:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
 3452:     my ($defdom,$runon,$runoff,$coownerson,$coownersoff,
 3453:         $failsafe,$autofailsafe,$failsafesty,%failsafechecked);
 3454:     $failsafesty = 'none';
 3455:     %failsafechecked = (
 3456:         off => ' checked="checked"',
 3457:     );
 3458:     if (ref($settings) eq 'HASH') {
 3459:         if (exists($settings->{'run'})) {
 3460:             if ($settings->{'run'} eq '0') {
 3461:                 $runoff = ' checked="checked" ';
 3462:                 $runon = ' ';
 3463:             } else {
 3464:                 $runon = ' checked="checked" ';
 3465:                 $runoff = ' ';
 3466:             }
 3467:         } else {
 3468:             if ($autorun) {
 3469:                 $runon = ' checked="checked" ';
 3470:                 $runoff = ' ';
 3471:             } else {
 3472:                 $runoff = ' checked="checked" ';
 3473:                 $runon = ' ';
 3474:             }
 3475:         }
 3476:         if (exists($settings->{'co-owners'})) {
 3477:             if ($settings->{'co-owners'} eq '0') {
 3478:                 $coownersoff = ' checked="checked" ';
 3479:                 $coownerson = ' ';
 3480:             } else {
 3481:                 $coownerson = ' checked="checked" ';
 3482:                 $coownersoff = ' ';
 3483:             }
 3484:         } else {
 3485:             $coownersoff = ' checked="checked" ';
 3486:             $coownerson = ' ';
 3487:         }
 3488:         if (exists($settings->{'sender_domain'})) {
 3489:             $defdom = $settings->{'sender_domain'};
 3490:         }
 3491:         if (exists($settings->{'failsafe'})) {
 3492:             $failsafe = $settings->{'failsafe'};
 3493:             if ($failsafe eq 'zero') {
 3494:                 $failsafechecked{'zero'} = ' checked="checked"';
 3495:                 $failsafechecked{'off'} = '';
 3496:                 $failsafesty = 'inline-block';
 3497:             } elsif ($failsafe eq 'any') {
 3498:                 $failsafechecked{'any'} = ' checked="checked"';
 3499:                 $failsafechecked{'off'} = '';
 3500:             }
 3501:             $autofailsafe = $settings->{'autofailsafe'};
 3502:         } elsif (exists($settings->{'autofailsafe'})) {
 3503:             $autofailsafe = $settings->{'autofailsafe'};
 3504:             if ($autofailsafe ne '') {
 3505:                 $failsafechecked{'zero'} = ' checked="checked"';
 3506:                 $failsafe = 'zero';
 3507:                 $failsafechecked{'off'} = '';
 3508:             }
 3509:         }
 3510:     } else {
 3511:         if ($autorun) {
 3512:             $runon = ' checked="checked" ';
 3513:             $runoff = ' ';
 3514:         } else {
 3515:             $runoff = ' checked="checked" ';
 3516:             $runon = ' ';
 3517:         }
 3518:     }
 3519:     my $domform = &Apache::loncommon::select_dom_form($defdom,'sender_domain',1);
 3520:     my $notif_sender;
 3521:     if (ref($settings) eq 'HASH') {
 3522:         $notif_sender = $settings->{'sender_uname'};
 3523:     }
 3524:     my $datatable='<tr class="LC_odd_row">'.
 3525:                   '<td>'.&mt('Auto-enrollment active?').'</td>'.
 3526:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3527:                   '<input type="radio" name="autoenroll_run"'.
 3528:                   $runon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3529:                   '<label><input type="radio" name="autoenroll_run"'.
 3530:                   $runoff.' value="0" />'.&mt('No').'</label></span></td>'.
 3531:                   '</tr><tr>'.
 3532:                   '<td>'.&mt('Notification messages - sender').
 3533:                   '</td><td class="LC_right_item"><span class="LC_nobreak">'.
 3534:                   &mt('username').':&nbsp;'.
 3535:                   '<input type="text" name="sender_uname" value="'.
 3536:                   $notif_sender.'" size="10" />&nbsp;&nbsp;'.&mt('domain').
 3537:                   ':&nbsp;'.$domform.'</span></td></tr>'.
 3538:                   '<tr class="LC_odd_row">'.
 3539:                   '<td>'.&mt('Automatically assign co-ownership').'</td>'.
 3540:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3541:                   '<input type="radio" name="autoassign_coowners"'.
 3542:                   $coownerson.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3543:                   '<label><input type="radio" name="autoassign_coowners"'.
 3544:                   $coownersoff.' value="0" />'.&mt('No').'</label></span></td>'.
 3545:                   '</tr><tr>'.
 3546:                   '<td>'.&mt('Failsafe for no drops when institutional data missing').'</td>'.
 3547:                   '<td class="LC_left_item"><span class="LC_nobreak">'.
 3548:                   '<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; '.
 3549:                   '<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 />'.
 3550:                   '<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>'.
 3551:                   '<div class="LC_floatleft" style="display:'.$failsafesty.';" id="autoenroll_failsafe_div">'.
 3552:                   '<span class="LC_nobreak">'.
 3553:                   &mt('Threshold for number of students in section to drop: [_1]',
 3554:                       '<input type="text" name="autoenroll_autofailsafe" value="'.$autofailsafe.'" size="4" />').
 3555:                   '</span></div></td></tr>';
 3556:     $$rowtotal += 4;
 3557:     return $datatable;
 3558: }
 3559: 
 3560: sub print_autoupdate {
 3561:     my ($position,$dom,$settings,$rowtotal) = @_;
 3562:     my ($enable,$datatable);
 3563:     if ($position eq 'top') {
 3564:         my %choices = &Apache::lonlocal::texthash (
 3565:                           run        => 'Auto-update active?',
 3566:                           classlists => 'Update information in classlists?',
 3567:                           unexpired  => 'Skip updates for users without active or future roles?',
 3568:                           lastactive => 'Skip updates for inactive users?',
 3569:         );
 3570:         my $itemcount = 0;
 3571:         my $updateon = ' ';
 3572:         my $updateoff = ' checked="checked" ';
 3573:         if (ref($settings) eq 'HASH') {
 3574:             if ($settings->{'run'} eq '1') {
 3575:                 $updateon = $updateoff;
 3576:                 $updateoff = ' ';
 3577:             }
 3578:         }
 3579:         $enable = '<tr class="LC_odd_row">'. 
 3580:                   '<td>'.&mt($choices{'run'}).'</td>'.
 3581:                   '<td class="LC_left_item"><span class="LC_nobreak"><label>'.
 3582:                   '<input type="radio" name="autoupdate_run"'.
 3583:                   $updateoff.'value="0" />'.&mt('No').'</label>&nbsp;'.
 3584:                   '<label><input type="radio" name="autoupdate_run"'.
 3585:                   $updateon.'value="1" />'.&mt('Yes').'</label></span></td>'.
 3586:                   '</tr>';
 3587:         my @toggles = ('classlists','unexpired');
 3588:         my %defaultchecked = ('classlists' => 'off',
 3589:                               'unexpired'  => 'off'
 3590:                               );
 3591:         $$rowtotal ++;
 3592:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 3593:                                                      \%choices,$itemcount,'','','left','no');
 3594:         $datatable = $enable.$datatable;
 3595:         $$rowtotal += $itemcount;
 3596:         my $lastactiveon = ' ';
 3597:         my $lastactiveoff = ' checked="checked" ';
 3598:         my $lastactivestyle = 'none';
 3599:         my $lastactivedays;
 3600:         my $onclick = ' onclick="javascript:toggleLastActiveDays(this.form);"';
 3601:         if (ref($settings) eq 'HASH') {
 3602:             if ($settings->{'lastactive'} =~ /^\d+$/) {
 3603:                 $lastactiveon = $lastactiveoff;
 3604:                 $lastactiveoff = ' ';
 3605:                 $lastactivestyle = 'inline-block';
 3606:                 $lastactivedays = $settings->{'lastactive'};
 3607:             }
 3608:         }
 3609:         my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 3610:         $datatable .= '<tr'.$css_class.'>'.
 3611:                       '<td>'.$choices{'lastactive'}.'</td>'.
 3612:                       '<td class="LC_left_item"><span class="LC_nobreak"><label>'.
 3613:                       '<input type="radio" name="lastactive"'.
 3614:                       $lastactiveoff.'value="0"'.$onclick.' />'.&mt('No').'</label>'.
 3615:                       '&nbsp;<label>'.
 3616:                       '<input type="radio" name="lastactive"'.
 3617:                       $lastactiveon.' value="1"'.$onclick.' />'.&mt('Yes').'</label>'.
 3618:                       '<div id="lastactive_div" style="display:'.$lastactivestyle.';">'.
 3619:                       ':&nbsp;'.&mt('inactive = no activity in last [_1] days',
 3620:                           '<input type="text" size="5" name="lastactivedays" value="'.
 3621:                           $lastactivedays.'" />').
 3622:                       '</span></td>'.
 3623:                       '</tr>';
 3624:         $$rowtotal ++;
 3625:     } elsif ($position eq 'middle') {
 3626:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3627:         my $numinrow = 3;
 3628:         my $locknamesettings;
 3629:         $datatable .= &insttypes_row($settings,$types,$usertypes,
 3630:                                      $dom,$numinrow,$othertitle,
 3631:                                     'lockablenames',$rowtotal);
 3632:         $$rowtotal ++;
 3633:     } else {
 3634:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3635:         my @fields = ('lastname','firstname','middlename','generation',
 3636:                       'permanentemail','id');
 3637:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3638:         my $numrows = 0;
 3639:         if (ref($types) eq 'ARRAY') {
 3640:             if (@{$types} > 0) {
 3641:                 $datatable = 
 3642:                     &usertype_update_row($settings,$usertypes,\%fieldtitles,
 3643:                                          \@fields,$types,\$numrows);
 3644:                     $$rowtotal += @{$types}; 
 3645:             }
 3646:         }
 3647:         $datatable .= 
 3648:             &usertype_update_row($settings,{'default' => $othertitle},
 3649:                                  \%fieldtitles,\@fields,['default'],
 3650:                                  \$numrows);
 3651:         $$rowtotal ++;     
 3652:     }
 3653:     return $datatable;
 3654: }
 3655: 
 3656: sub print_autocreate {
 3657:     my ($dom,$settings,$rowtotal) = @_;
 3658:     my (%createon,%createoff,%currhash);
 3659:     my @types = ('xml','req');
 3660:     if (ref($settings) eq 'HASH') {
 3661:         foreach my $item (@types) {
 3662:             $createoff{$item} = ' checked="checked" ';
 3663:             $createon{$item} = ' ';
 3664:             if (exists($settings->{$item})) {
 3665:                 if ($settings->{$item}) {
 3666:                     $createon{$item} = ' checked="checked" ';
 3667:                     $createoff{$item} = ' ';
 3668:                 }
 3669:             }
 3670:         }
 3671:         if ($settings->{'xmldc'} ne '') {
 3672:             $currhash{$settings->{'xmldc'}} = 1;
 3673:         }
 3674:     } else {
 3675:         foreach my $item (@types) {
 3676:             $createoff{$item} = ' checked="checked" ';
 3677:             $createon{$item} = ' ';
 3678:         }
 3679:     }
 3680:     $$rowtotal += 2;
 3681:     my $numinrow = 2;
 3682:     my $datatable='<tr class="LC_odd_row">'.
 3683:                   '<td>'.&mt('Create pending official courses from XML files').'</td>'.
 3684:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3685:                   '<input type="radio" name="autocreate_xml"'.
 3686:                   $createon{'xml'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3687:                   '<label><input type="radio" name="autocreate_xml"'.
 3688:                   $createoff{'xml'}.' value="0" />'.&mt('No').'</label></span>'.
 3689:                   '</td></tr><tr>'.
 3690:                   '<td>'.&mt('Create pending requests for official courses (if validated)').'</td>'.
 3691:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3692:                   '<input type="radio" name="autocreate_req"'.
 3693:                   $createon{'req'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3694:                   '<label><input type="radio" name="autocreate_req"'.
 3695:                   $createoff{'req'}.' value="0" />'.&mt('No').'</label></span>';
 3696:     my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 3697:                                                    'autocreate_xmldc',%currhash);
 3698:     $datatable .= '</td></tr><tr class="LC_odd_row"><td>';
 3699:     if ($numdc > 1) {
 3700:         $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)').
 3701:                       '</td><td class="LC_left_item">';
 3702:     } else {
 3703:         $datatable .= &mt('Course creation processed as:').
 3704:                       '</td><td class="LC_right_item">';
 3705:     }
 3706:     $datatable .= $dctable.'</td></tr>';
 3707:     $$rowtotal += $rows;
 3708:     return $datatable;
 3709: }
 3710: 
 3711: sub print_directorysrch {
 3712:     my ($position,$dom,$settings,$rowtotal) = @_;
 3713:     my $datatable;
 3714:     if ($position eq 'top') {
 3715:         my $instsrchon = ' ';
 3716:         my $instsrchoff = ' checked="checked" ';
 3717:         my ($exacton,$containson,$beginson);
 3718:         my $instlocalon = ' ';
 3719:         my $instlocaloff = ' checked="checked" ';
 3720:         if (ref($settings) eq 'HASH') {
 3721:             if ($settings->{'available'} eq '1') {
 3722:                 $instsrchon = $instsrchoff;
 3723:                 $instsrchoff = ' ';
 3724:             }
 3725:             if ($settings->{'localonly'} eq '1') {
 3726:                 $instlocalon = $instlocaloff;
 3727:                 $instlocaloff = ' ';
 3728:             }
 3729:             if (ref($settings->{'searchtypes'}) eq 'ARRAY') {
 3730:                 foreach my $type (@{$settings->{'searchtypes'}}) {
 3731:                     if ($type eq 'exact') {
 3732:                         $exacton = ' checked="checked" ';
 3733:                     } elsif ($type eq 'contains') {
 3734:                         $containson = ' checked="checked" ';
 3735:                     } elsif ($type eq 'begins') {
 3736:                         $beginson = ' checked="checked" ';
 3737:                     }
 3738:                 }
 3739:             } else {
 3740:                 if ($settings->{'searchtypes'} eq 'exact') {
 3741:                     $exacton = ' checked="checked" ';
 3742:                 } elsif ($settings->{'searchtypes'} eq 'contains') {
 3743:                     $containson = ' checked="checked" ';
 3744:                 } elsif ($settings->{'searchtypes'} eq 'specify') {
 3745:                     $exacton = ' checked="checked" ';
 3746:                     $containson = ' checked="checked" ';
 3747:                 }
 3748:             }
 3749:         }
 3750:         my ($searchtitles,$titleorder) = &sorted_searchtitles();
 3751:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3752: 
 3753:         my $numinrow = 4;
 3754:         my $cansrchrow = 0;
 3755:         $datatable='<tr class="LC_odd_row">'.
 3756:                    '<td colspan="2"><span class ="LC_nobreak">'.&mt('Institutional directory search available?').'</span></td>'.
 3757:                    '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3758:                    '<input type="radio" name="dirsrch_available"'.
 3759:                    $instsrchon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3760:                    '<label><input type="radio" name="dirsrch_available"'.
 3761:                    $instsrchoff.' value="0" />'.&mt('No').'</label></span></td>'.
 3762:                    '</tr><tr>'.
 3763:                    '<td colspan="2"><span class ="LC_nobreak">'.&mt('Other domains can search institution?').'</span></td>'.
 3764:                    '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3765:                    '<input type="radio" name="dirsrch_instlocalonly"'.
 3766:                    $instlocaloff.' value="0" />'.&mt('Yes').'</label>&nbsp;'.
 3767:                    '<label><input type="radio" name="dirsrch_instlocalonly"'.
 3768:                    $instlocalon.' value="1" />'.&mt('No').'</label></span></td>'.
 3769:                    '</tr>';
 3770:         $$rowtotal += 2;
 3771:         if (ref($usertypes) eq 'HASH') {
 3772:             if (keys(%{$usertypes}) > 0) {
 3773:                 $datatable .= &insttypes_row($settings,$types,$usertypes,$dom,
 3774:                                              $numinrow,$othertitle,'cansearch',
 3775:                                              $rowtotal);
 3776:                 $cansrchrow = 1;
 3777:             }
 3778:         }
 3779:         if ($cansrchrow) {
 3780:             $$rowtotal ++;
 3781:             $datatable .= '<tr>';
 3782:         } else {
 3783:             $datatable .= '<tr class="LC_odd_row">';
 3784:         }
 3785:         $datatable .= '<td><span class ="LC_nobreak">'.&mt('Supported search methods').
 3786:                       '</span></td><td class="LC_left_item" colspan="2"><table><tr>';
 3787:         foreach my $title (@{$titleorder}) {
 3788:             if (defined($searchtitles->{$title})) {
 3789:                 my $check = ' ';
 3790:                 if (ref($settings) eq 'HASH') {
 3791:                     if (ref($settings->{'searchby'}) eq 'ARRAY') {
 3792:                         if (grep(/^\Q$title\E$/,@{$settings->{'searchby'}})) {
 3793:                             $check = ' checked="checked" ';
 3794:                         }
 3795:                     }
 3796:                 }
 3797:                 $datatable .= '<td class="LC_left_item">'.
 3798:                               '<span class="LC_nobreak"><label>'.
 3799:                               '<input type="checkbox" name="searchby" '.
 3800:                               'value="'.$title.'"'.$check.'/>'.
 3801:                               $searchtitles->{$title}.'</label></span></td>';
 3802:             }
 3803:         }
 3804:         $datatable .= '</tr></table></td></tr>';
 3805:         $$rowtotal ++;
 3806:         if ($cansrchrow) {
 3807:             $datatable .= '<tr class="LC_odd_row">';
 3808:         } else {
 3809:             $datatable .= '<tr>';
 3810:         }
 3811:         $datatable .= '<td><span class ="LC_nobreak">'.&mt('Search latitude').'</span></td>'.   
 3812:                       '<td class="LC_left_item" colspan="2">'.
 3813:                       '<span class="LC_nobreak"><label>'.
 3814:                       '<input type="checkbox" name="searchtypes" '.
 3815:                       $exacton.' value="exact" />'.&mt('Exact match').
 3816:                       '</label>&nbsp;'.
 3817:                       '<label><input type="checkbox" name="searchtypes" '.
 3818:                       $beginson.' value="begins" />'.&mt('Begins with').
 3819:                       '</label>&nbsp;'.
 3820:                       '<label><input type="checkbox" name="searchtypes" '.
 3821:                       $containson.' value="contains" />'.&mt('Contains').
 3822:                       '</label></span></td></tr>';
 3823:         $$rowtotal ++;
 3824:     } else {
 3825:         my $domsrchon = ' checked="checked" ';
 3826:         my $domsrchoff = ' ';
 3827:         my $domlocalon = ' ';
 3828:         my $domlocaloff = ' checked="checked" ';
 3829:         if (ref($settings) eq 'HASH') {
 3830:             if ($settings->{'lclocalonly'} eq '1') {
 3831:                 $domlocalon = $domlocaloff;
 3832:                 $domlocaloff = ' ';
 3833:             }
 3834:             if ($settings->{'lcavailable'} eq '0') {
 3835:                 $domsrchoff = $domsrchon;
 3836:                 $domsrchon = ' ';
 3837:             }
 3838:         }
 3839:         $datatable='<tr class="LC_odd_row">'.
 3840:                       '<td colspan="2"><span class ="LC_nobreak">'.&mt('LON-CAPA directory search available?').'</span></td>'.
 3841:                       '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3842:                       '<input type="radio" name="dirsrch_domavailable"'.
 3843:                       $domsrchon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3844:                       '<label><input type="radio" name="dirsrch_domavailable"'.
 3845:                       $domsrchoff.' value="0" />'.&mt('No').'</label></span></td>'.
 3846:                       '</tr><tr>'.
 3847:                       '<td colspan="2"><span class ="LC_nobreak">'.&mt('Other domains can search LON-CAPA domain?').'</span></td>'.
 3848:                       '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3849:                       '<input type="radio" name="dirsrch_domlocalonly"'.
 3850:                       $domlocaloff.' value="0" />'.&mt('Yes').'</label>&nbsp;'.
 3851:                       '<label><input type="radio" name="dirsrch_domlocalonly"'.
 3852:                       $domlocalon.' value="1" />'.&mt('No').'</label></span></td>'.
 3853:                       '</tr>';
 3854:         $$rowtotal += 2;
 3855:     }
 3856:     return $datatable;
 3857: }
 3858: 
 3859: sub print_contacts {
 3860:     my ($position,$dom,$settings,$rowtotal) = @_;
 3861:     my $datatable;
 3862:     my @contacts = ('adminemail','supportemail');
 3863:     my (%checked,%to,%otheremails,%bccemails,%includestr,%includeloc,%currfield,
 3864:         $maxsize,$fields,$fieldtitles,$fieldoptions,$possoptions,@mailings,%lonstatus);
 3865:     if ($position eq 'top') {
 3866:         if (ref($settings) eq 'HASH') {
 3867:             foreach my $item (@contacts) {
 3868:                 if (exists($settings->{$item})) {
 3869:                     $to{$item} = $settings->{$item};
 3870:                 }
 3871:             }
 3872:         }
 3873:     } elsif ($position eq 'middle') {
 3874:         @mailings = ('errormail','packagesmail','lonstatusmail','requestsmail',
 3875:                      'updatesmail','idconflictsmail','hostipmail');
 3876:         foreach my $type (@mailings) {
 3877:             $otheremails{$type} = '';
 3878:         }
 3879:     } elsif ($position eq 'lower') {
 3880:         if (ref($settings) eq 'HASH') {
 3881:             if (ref($settings->{'lonstatus'}) eq 'HASH') {
 3882:                 %lonstatus = %{$settings->{'lonstatus'}};
 3883:             }
 3884:         }
 3885:     } else {
 3886:         @mailings = ('helpdeskmail','otherdomsmail');
 3887:         foreach my $type (@mailings) {
 3888:             $otheremails{$type} = '';
 3889:         }
 3890:         $bccemails{'helpdeskmail'} = '';
 3891:         $bccemails{'otherdomsmail'} = '';
 3892:         $includestr{'helpdeskmail'} = '';
 3893:         $includestr{'otherdomsmail'} = '';
 3894:         ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
 3895:     }
 3896:     if (ref($settings) eq 'HASH') {
 3897:         unless (($position eq 'top') || ($position eq 'lower')) {
 3898:             foreach my $type (@mailings) {
 3899:                 if (exists($settings->{$type})) {
 3900:                     if (ref($settings->{$type}) eq 'HASH') {
 3901:                         foreach my $item (@contacts) {
 3902:                             if ($settings->{$type}{$item}) {
 3903:                                 $checked{$type}{$item} = ' checked="checked" ';
 3904:                             }
 3905:                         }
 3906:                         $otheremails{$type} = $settings->{$type}{'others'};
 3907:                         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 3908:                             $bccemails{$type} = $settings->{$type}{'bcc'};
 3909:                             if ($settings->{$type}{'include'} ne '') {
 3910:                                 ($includeloc{$type},$includestr{$type}) = split(/:/,$settings->{$type}{'include'},2);
 3911:                                 $includestr{$type} = &unescape($includestr{$type});
 3912:                             }
 3913:                         }
 3914:                     }
 3915:                 } elsif ($type eq 'lonstatusmail') {
 3916:                     $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" ';
 3917:                 }
 3918:             }
 3919:         }
 3920:         if ($position eq 'bottom') {
 3921:             foreach my $type (@mailings) {
 3922:                 $bccemails{$type} = $settings->{$type}{'bcc'};
 3923:                 if ($settings->{$type}{'include'} ne '') {
 3924:                     ($includeloc{$type},$includestr{$type}) = split(/:/,$settings->{$type}{'include'},2);
 3925:                     $includestr{$type} = &unescape($includestr{$type});
 3926:                 }
 3927:             }
 3928:             if (ref($settings->{'helpform'}) eq 'HASH') {
 3929:                 if (ref($fields) eq 'ARRAY') {
 3930:                     foreach my $field (@{$fields}) {
 3931:                         $currfield{$field} = $settings->{'helpform'}{$field};
 3932:                     }
 3933:                 }
 3934:                 if (exists($settings->{'helpform'}{'maxsize'})) {
 3935:                     $maxsize = $settings->{'helpform'}{'maxsize'};
 3936:                 } else {
 3937:                     $maxsize = '1.0';
 3938:                 }
 3939:             } else {
 3940:                 if (ref($fields) eq 'ARRAY') {
 3941:                     foreach my $field (@{$fields}) {
 3942:                         $currfield{$field} = 'yes';
 3943:                     }
 3944:                 }
 3945:                 $maxsize = '1.0';
 3946:             }
 3947:         }
 3948:     } else {
 3949:         if ($position eq 'top') {
 3950:             $to{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
 3951:             $to{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
 3952:             $checked{'errormail'}{'adminemail'} = ' checked="checked" ';
 3953:             $checked{'packagesmail'}{'adminemail'} = ' checked="checked" ';
 3954:             $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" ';
 3955:             $checked{'requestsmail'}{'adminemail'} = ' checked="checked" ';
 3956:             $checked{'updatesmail'}{'adminemail'} = ' checked="checked" ';
 3957:             $checked{'idconflictsmail'}{'adminemail'} = ' checked="checked" ';
 3958:             $checked{'hostipmail'}{'adminemail'} = ' checked="checked" ';
 3959:         } elsif ($position eq 'bottom') {
 3960:             $checked{'helpdeskmail'}{'supportemail'} = ' checked="checked" ';
 3961:             $checked{'otherdomsmail'}{'supportemail'} = ' checked="checked" ';
 3962:             if (ref($fields) eq 'ARRAY') {
 3963:                 foreach my $field (@{$fields}) {
 3964:                     $currfield{$field} = 'yes';
 3965:                 }
 3966:             }
 3967:             $maxsize = '1.0';
 3968:         }
 3969:     }
 3970:     my ($titles,$short_titles) = &contact_titles();
 3971:     my $rownum = 0;
 3972:     my $css_class;
 3973:     if ($position eq 'top') {
 3974:         foreach my $item (@contacts) {
 3975:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 3976:             $datatable .= '<tr'.$css_class.'>'. 
 3977:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
 3978:                           '</span></td><td class="LC_right_item">'.
 3979:                           '<input type="text" name="'.$item.'" value="'.
 3980:                           $to{$item}.'" /></td></tr>';
 3981:             $rownum ++;
 3982:         }
 3983:     } elsif ($position eq 'bottom') {
 3984:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 3985:         $datatable .= '<tr'.$css_class.'>'.
 3986:                       '<td>'.&mt('Extra helpdesk form fields:').'<br />'.
 3987:                       &mt('(e-mail, subject, and description always shown)').
 3988:                       '</td><td class="LC_left_item">';
 3989:         if ((ref($fields) eq 'ARRAY') && (ref($fieldtitles) eq 'HASH') &&
 3990:             (ref($fieldoptions) eq 'HASH') && (ref($possoptions) eq 'HASH')) {
 3991:             $datatable .= '<table><tr><th>'.&mt('Field').'</th><th>'.&mt('Status').'</th></tr>';
 3992:             foreach my $field (@{$fields}) {
 3993:                 $datatable .= '<tr><td>'.$fieldtitles->{$field};
 3994:                 if (($field eq 'screenshot') || ($field eq 'cc')) {
 3995:                     $datatable .= ' '.&mt('(logged-in users)');
 3996:                 }
 3997:                 $datatable .='</td><td>';
 3998:                 my $clickaction;
 3999:                 if ($field eq 'screenshot') {
 4000:                     $clickaction = ' onclick="screenshotSize(this);"';
 4001:                 }
 4002:                 if (ref($possoptions->{$field}) eq 'ARRAY') {
 4003:                     foreach my $option (@{$possoptions->{$field}}) {
 4004:                         my $checked;
 4005:                         if ($currfield{$field} eq $option) {
 4006:                             $checked = ' checked="checked"';
 4007:                         }
 4008:                         $datatable .= '<span class="LC_nobreak"><label>'.
 4009:                                       '<input type="radio" name="helpform_'.$field.'" '.
 4010:                                       'value="'.$option.'"'.$checked.$clickaction.' />'.$fieldoptions->{$option}.
 4011:                                       '</label></span>'.('&nbsp;'x2);
 4012:                     }
 4013:                 }
 4014:                 if ($field eq 'screenshot') {
 4015:                     my $display;
 4016:                     if ($currfield{$field} eq 'no') {
 4017:                         $display = ' style="display:none"';
 4018:                     }
 4019:                     $datatable .= '</td></tr><tr id="help_screenshotsize"'.$display.'>'.
 4020:                                   '<td>'.&mt('Maximum size for upload (MB)').'</td><td>'.
 4021:                                   '<input type="text" size="5" name="helpform_maxsize" value="'.$maxsize.'" />';
 4022:                 }
 4023:                 $datatable .= '</td></tr>';
 4024:             }
 4025:             $datatable .= '</table>';
 4026:         }
 4027:         $datatable .= '</td></tr>'."\n";
 4028:         $rownum ++;
 4029:     }
 4030:     unless (($position eq 'top') || ($position eq 'lower')) {
 4031:         foreach my $type (@mailings) {
 4032:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 4033:             $datatable .= '<tr'.$css_class.'>'.
 4034:                           '<td><span class="LC_nobreak">'.
 4035:                           $titles->{$type}.': </span></td>'.
 4036:                           '<td class="LC_left_item">';
 4037:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 4038:                 $datatable .= '<fieldset><legend>'.&mt('E-mail recipient(s)').'</legend>';
 4039:             }
 4040:             $datatable .= '<span class="LC_nobreak">';
 4041:             foreach my $item (@contacts) {
 4042:                 $datatable .= '<label>'.
 4043:                               '<input type="checkbox" name="'.$type.'"'.
 4044:                               $checked{$type}{$item}.
 4045:                               ' value="'.$item.'" />'.$short_titles->{$item}.
 4046:                               '</label>&nbsp;';
 4047:             }
 4048:             $datatable .= '</span><br />'.&mt('Others').':&nbsp;&nbsp;'.
 4049:                           '<input type="text" name="'.$type.'_others" '.
 4050:                           'value="'.$otheremails{$type}.'"  />';
 4051:             my %locchecked;
 4052:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 4053:                 foreach my $loc ('s','b') {
 4054:                     if ($includeloc{$type} eq $loc) {
 4055:                         $locchecked{$loc} = ' checked="checked"';
 4056:                         last;
 4057:                     }
 4058:                 }
 4059:                 $datatable .= '<br />'.&mt('Bcc:').('&nbsp;'x6).
 4060:                               '<input type="text" name="'.$type.'_bcc" '.
 4061:                               'value="'.$bccemails{$type}.'"  /></fieldset>'.
 4062:                               '<fieldset><legend>'.&mt('Optional added text').'</legend>'.
 4063:                               &mt('Text automatically added to e-mail:').' '.
 4064:                               '<input type="text" name="'.$type.'_includestr" value="'.$includestr{$type}.'" /><br />'.
 4065:                               '<span class="LC_nobreak">'.&mt('Location:').'&nbsp;'.
 4066:                               '<label><input type="radio" name="'.$type.'_includeloc" value="s"'.$locchecked{'s'}.' />'.&mt('in subject').'</label>'.
 4067:                               ('&nbsp;'x2).
 4068:                               '<label><input type="radio" name="'.$type.'_includeloc" value="b"'.$locchecked{'b'}.' />'.&mt('in body').'</label>'.
 4069:                               '</span></fieldset>';
 4070:             }
 4071:             $datatable .= '</td></tr>'."\n";
 4072:             $rownum ++;
 4073:         }
 4074:     }
 4075:     if ($position eq 'middle') {
 4076:         my %choices;
 4077:         my $corelink = &core_link_msu();
 4078:         $choices{'reporterrors'} = &mt('E-mail error reports to [_1]',$corelink);
 4079:         $choices{'reportupdates'} = &mt('E-mail record of completed LON-CAPA updates to [_1]',
 4080:                                         $corelink);
 4081:         $choices{'reportstatus'} = &mt('E-mail status if errors above threshold to [_1]',$corelink);
 4082:         my @toggles = ('reporterrors','reportupdates','reportstatus');
 4083:         my %defaultchecked = ('reporterrors'  => 'on',
 4084:                               'reportupdates' => 'on',
 4085:                               'reportstatus'  => 'on');
 4086:         (my $reports,$rownum) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 4087:                                                    \%choices,$rownum);
 4088:         $datatable .= $reports;
 4089:     } elsif ($position eq 'lower') {
 4090:         my (%current,%excluded,%weights);
 4091:         my ($defaults,$names) = &Apache::loncommon::lon_status_items();
 4092:         if ($lonstatus{'threshold'} =~ /^\d+$/) {
 4093:             $current{'errorthreshold'} = $lonstatus{'threshold'};
 4094:         } else {
 4095:             $current{'errorthreshold'} = $defaults->{'threshold'};
 4096:         }
 4097:         if ($lonstatus{'sysmail'} =~ /^\d+$/) {
 4098:             $current{'errorsysmail'} = $lonstatus{'sysmail'};
 4099:         } else {
 4100:             $current{'errorsysmail'} = $defaults->{'sysmail'};
 4101:         }
 4102:         if (ref($lonstatus{'weights'}) eq 'HASH') {
 4103:             foreach my $type ('E','W','N','U') {
 4104:                 if ($lonstatus{'weights'}{$type} =~ /^\d+$/) {
 4105:                     $weights{$type} = $lonstatus{'weights'}{$type};
 4106:                 } else {
 4107:                     $weights{$type} = $defaults->{$type};
 4108:                 }
 4109:             }
 4110:         } else {
 4111:             foreach my $type ('E','W','N','U') {
 4112:                 $weights{$type} = $defaults->{$type};
 4113:             }
 4114:         }
 4115:         if (ref($lonstatus{'excluded'}) eq 'ARRAY') {
 4116:             if (@{$lonstatus{'excluded'}} > 0) {
 4117:                 map {$excluded{$_} = 1; } @{$lonstatus{'excluded'}};
 4118:             }
 4119:         }
 4120:         foreach my $item ('errorthreshold','errorsysmail') {
 4121:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 4122:             $datatable .= '<tr'.$css_class.'>'.
 4123:                           '<td class="LC_left_item"><span class="LC_nobreak">'.
 4124:                           $titles->{$item}.
 4125:                           '</span></td><td class="LC_left_item">'.
 4126:                           '<input type="text" name="'.$item.'" value="'.
 4127:                           $current{$item}.'" size="5" /></td></tr>';
 4128:             $rownum ++;
 4129:         }
 4130:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 4131:         $datatable .= '<tr'.$css_class.'>'.
 4132:                       '<td class="LC_left_item">'.
 4133:                       '<span class="LC_nobreak">'.$titles->{'errorweights'}.
 4134:                       '</span></td><td class="LC_left_item"><table><tr>';
 4135:         foreach my $type ('E','W','N','U') {
 4136:             $datatable .= '<td>'.$names->{$type}.'<br />'.
 4137:                           '<input type="text" name="errorweights_'.$type.'" value="'.
 4138:                           $weights{$type}.'" size="5" /></td>';
 4139:         }
 4140:         $datatable .= '</tr></table></tr>';
 4141:         $rownum ++;
 4142:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 4143:         $datatable .= '<tr'.$css_class.'><td class="LC_left_item">'.
 4144:                       $titles->{'errorexcluded'}.'</td>'.
 4145:                       '<td class="LC_left_item"><table>';
 4146:         my $numinrow = 4;
 4147:         my @ids = sort(values(%Apache::lonnet::serverhomeIDs));
 4148:         for (my $i=0; $i<@ids; $i++) {
 4149:             my $rem = $i%($numinrow);
 4150:             if ($rem == 0) {
 4151:                 if ($i > 0) {
 4152:                     $datatable .= '</tr>';
 4153:                 }
 4154:                 $datatable .= '<tr>';
 4155:             }
 4156:             my $check;
 4157:             if ($excluded{$ids[$i]}) {
 4158:                 $check = ' checked="checked" ';
 4159:             }
 4160:             $datatable .= '<td class="LC_left_item">'.
 4161:                           '<span class="LC_nobreak"><label>'.
 4162:                           '<input type="checkbox" name="errorexcluded" '.
 4163:                           'value="'.$ids[$i].'"'.$check.' />'.
 4164:                           $ids[$i].'</label></span></td>';
 4165:         }
 4166:         my $colsleft = $numinrow - @ids%($numinrow);
 4167:         if ($colsleft > 1 ) {
 4168:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 4169:                           '&nbsp;</td>';
 4170:         } elsif ($colsleft == 1) {
 4171:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 4172:         }
 4173:         $datatable .= '</tr></table></td></tr>';
 4174:         $rownum ++;
 4175:     } elsif ($position eq 'bottom') {
 4176:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4177:         my (@posstypes,%usertypeshash);
 4178:         if (ref($types) eq 'ARRAY') {
 4179:             @posstypes = @{$types};
 4180:         }
 4181:         if (@posstypes) {
 4182:             if (ref($usertypes) eq 'HASH') {
 4183:                 %usertypeshash = %{$usertypes};
 4184:             }
 4185:             my @overridden;
 4186:             my $numinrow = 4;
 4187:             if (ref($settings) eq 'HASH') {
 4188:                 if (ref($settings->{'overrides'}) eq 'HASH') {
 4189:                     foreach my $key (sort(keys(%{$settings->{'overrides'}}))) {
 4190:                         if (ref($settings->{'overrides'}{$key}) eq 'HASH') {
 4191:                             push(@overridden,$key);
 4192:                             foreach my $item (@contacts) {
 4193:                                 if ($settings->{'overrides'}{$key}{$item}) {
 4194:                                     $checked{'override_'.$key}{$item} = ' checked="checked" ';
 4195:                                 }
 4196:                             }
 4197:                             $otheremails{'override_'.$key} = $settings->{'overrides'}{$key}{'others'};
 4198:                             $bccemails{'override_'.$key} = $settings->{'overrides'}{$key}{'bcc'};
 4199:                             $includeloc{'override_'.$key} = '';
 4200:                             $includestr{'override_'.$key} = '';
 4201:                             if ($settings->{'overrides'}{$key}{'include'} ne '') {
 4202:                                 ($includeloc{'override_'.$key},$includestr{'override_'.$key}) =
 4203:                                     split(/:/,$settings->{'overrides'}{$key}{'include'},2);
 4204:                                 $includestr{'override_'.$key} = &unescape($includestr{'override_'.$key});
 4205:                             }
 4206:                         }
 4207:                     }
 4208:                 }
 4209:             }
 4210:             my $customclass = 'LC_helpdesk_override';
 4211:             my $optionsprefix = 'LC_options_helpdesk_';
 4212: 
 4213:             my $onclicktypes = "toggleHelpdeskRow(this.form,'overrides','$customclass','$optionsprefix');";
 4214: 
 4215:             $datatable .= &insttypes_row($settings,$types,$usertypes,$dom,
 4216:                                          $numinrow,$othertitle,'overrides',
 4217:                                          \$rownum,$onclicktypes,$customclass);
 4218:             $rownum ++;
 4219:             $usertypeshash{'default'} = $othertitle;
 4220:             foreach my $status (@posstypes) {
 4221:                 my $css_class;
 4222:                 if ($rownum%2) {
 4223:                     $css_class = 'LC_odd_row ';
 4224:                 }
 4225:                 $css_class .= $customclass;
 4226:                 my $rowid = $optionsprefix.$status;
 4227:                 my $hidden = 1;
 4228:                 my $currstyle = 'display:none';
 4229:                 if (grep(/^\Q$status\E$/,@overridden)) {
 4230:                     $currstyle = 'display:table-row';
 4231:                     $hidden = 0;
 4232:                 }
 4233:                 my $key = 'override_'.$status;
 4234:                 $datatable .= &overridden_helpdesk($checked{$key},$otheremails{$key},$bccemails{$key},
 4235:                                                   $includeloc{$key},$includestr{$key},$status,$rowid,
 4236:                                                   $usertypeshash{$status},$css_class,$currstyle,
 4237:                                                   \@contacts,$short_titles);
 4238:                 unless ($hidden) {
 4239:                     $rownum ++;
 4240:                 }
 4241:             }
 4242:         }
 4243:     }
 4244:     $$rowtotal += $rownum;
 4245:     return $datatable;
 4246: }
 4247: 
 4248: sub core_link_msu {
 4249:     return &Apache::loncommon::modal_link('http://loncapa.org/core.html',
 4250:                                           &mt('LON-CAPA core group - MSU'),600,500);
 4251: }
 4252: 
 4253: sub overridden_helpdesk {
 4254:     my ($checked,$otheremails,$bccemails,$includeloc,$includestr,$type,$rowid,
 4255:         $typetitle,$css_class,$rowstyle,$contacts,$short_titles) = @_;
 4256:     my $class = 'LC_left_item';
 4257:     if ($css_class) {
 4258:         $css_class = ' class="'.$css_class.'"';
 4259:     }
 4260:     if ($rowid) {
 4261:         $rowid = ' id="'.$rowid.'"';
 4262:     }
 4263:     if ($rowstyle) {
 4264:         $rowstyle = ' style="'.$rowstyle.'"';
 4265:     }
 4266:     my ($output,$description);
 4267:     $description = &mt('Helpdesk requests from: [_1] in this domain (overrides default)',"<b>$typetitle</b>");
 4268:     $output = '<tr'.$css_class.$rowid.$rowstyle.'>'.
 4269:               "<td>$description</td>\n".
 4270:               '<td class="'.$class.'" colspan="2">'.
 4271:               '<fieldset><legend>'.&mt('E-mail recipient(s)').'</legend>'.
 4272:               '<span class="LC_nobreak">';
 4273:     if (ref($contacts) eq 'ARRAY') {
 4274:         foreach my $item (@{$contacts}) {
 4275:             my $check;
 4276:             if (ref($checked) eq 'HASH') {
 4277:                $check = $checked->{$item};
 4278:             }
 4279:             my $title;
 4280:             if (ref($short_titles) eq 'HASH') {
 4281:                 $title = $short_titles->{$item};
 4282:             }
 4283:             $output .= '<label>'.
 4284:                        '<input type="checkbox" name="override_'.$type.'"'.$check.
 4285:                        ' value="'.$item.'" />'.$title.'</label>&nbsp;';
 4286:         }
 4287:     }
 4288:     $output .= '</span><br />'.&mt('Others').':&nbsp;&nbsp;'.
 4289:                '<input type="text" name="override_'.$type.'_others" '.
 4290:                'value="'.$otheremails.'"  />';
 4291:     my %locchecked;
 4292:     foreach my $loc ('s','b') {
 4293:         if ($includeloc eq $loc) {
 4294:             $locchecked{$loc} = ' checked="checked"';
 4295:             last;
 4296:         }
 4297:     }
 4298:     $output .= '<br />'.&mt('Bcc:').('&nbsp;'x6).
 4299:                '<input type="text" name="override_'.$type.'_bcc" '.
 4300:                'value="'.$bccemails.'"  /></fieldset>'.
 4301:                '<fieldset><legend>'.&mt('Optional added text').'</legend>'.
 4302:                &mt('Text automatically added to e-mail:').' '.
 4303:                '<input type="text" name="override_'.$type.'_includestr" value="'.$includestr.'" /><br />'.
 4304:                '<span class="LC_nobreak">'.&mt('Location:').'&nbsp;'.
 4305:                '<label><input type="radio" name="override_'.$type.'_includeloc" value="s"'.$locchecked{'s'}.' />'.&mt('in subject').'</label>'.
 4306:                ('&nbsp;'x2).
 4307:                '<label><input type="radio" name="override_'.$type.'_includeloc" value="b"'.$locchecked{'b'}.' />'.&mt('in body').'</label>'.
 4308:                '</span></fieldset>'.
 4309:                '</td></tr>'."\n";
 4310:     return $output;
 4311: }
 4312: 
 4313: sub contacts_javascript {
 4314:     return <<"ENDSCRIPT";
 4315: 
 4316: <script type="text/javascript">
 4317: // <![CDATA[
 4318: 
 4319: function screenshotSize(field) {
 4320:     if (document.getElementById('help_screenshotsize')) {
 4321:         if (field.value == 'no') {
 4322:             document.getElementById('help_screenshotsize').style.display="none";
 4323:         } else {
 4324:             document.getElementById('help_screenshotsize').style.display="";
 4325:         }
 4326:     }
 4327:     return;
 4328: }
 4329: 
 4330: function toggleHelpdeskRow(form,checkbox,target,prefix,docount) {
 4331:     if (form.elements[checkbox].length != undefined) {
 4332:         var count = 0;
 4333:         if (docount) {
 4334:             for (var i=0; i<form.elements[checkbox].length; i++) {
 4335:                 if (form.elements[checkbox][i].checked) {
 4336:                     count ++;
 4337:                 }
 4338:             }
 4339:         }
 4340:         for (var i=0; i<form.elements[checkbox].length; i++) {
 4341:             var type = form.elements[checkbox][i].value;
 4342:             if (document.getElementById(prefix+type)) {
 4343:                 if (form.elements[checkbox][i].checked) {
 4344:                     document.getElementById(prefix+type).style.display = 'table-row';
 4345:                     if (count % 2 == 1) {
 4346:                         document.getElementById(prefix+type).className = target+' LC_odd_row';
 4347:                     } else {
 4348:                         document.getElementById(prefix+type).className = target;
 4349:                     }
 4350:                     count ++;
 4351:                 } else {
 4352:                     document.getElementById(prefix+type).style.display = 'none';
 4353:                 }
 4354:             }
 4355:         }
 4356:     }
 4357:     return;
 4358: }
 4359: 
 4360: // ]]>
 4361: </script>
 4362: 
 4363: ENDSCRIPT
 4364: }
 4365: 
 4366: sub print_helpsettings {
 4367:     my ($position,$dom,$settings,$rowtotal) = @_;
 4368:     my $confname = $dom.'-domainconfig';
 4369:     my $formname = 'display';
 4370:     my ($datatable,$itemcount);
 4371:     if ($position eq 'top') {
 4372:         $itemcount = 1;
 4373:         my (%choices,%defaultchecked,@toggles);
 4374:         $choices{'submitbugs'} = &mt('Display link to: [_1]?',
 4375:                                      &Apache::loncommon::modal_link('http://bugs.loncapa.org',
 4376:                                      &mt('LON-CAPA bug tracker'),600,500));
 4377:         %defaultchecked = ('submitbugs' => 'on');
 4378:         @toggles = ('submitbugs');
 4379:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 4380:                                                      \%choices,$itemcount);
 4381:         $$rowtotal ++;
 4382:     } else {
 4383:         my $css_class;
 4384:         my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
 4385:         my (%customroles,%ordered,%current);
 4386:         if (ref($settings) eq 'HASH') {
 4387:             if (ref($settings->{'adhoc'}) eq 'HASH') {
 4388:                 %current = %{$settings->{'adhoc'}};
 4389:             }
 4390:         }
 4391:         my $count = 0;
 4392:         foreach my $key (sort(keys(%existing))) {
 4393:             if ($key=~/^rolesdef\_(\w+)$/) {
 4394:                 my $rolename = $1;
 4395:                 my (%privs,$order);
 4396:                 ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 4397:                 $customroles{$rolename} = \%privs;
 4398:                 if (ref($current{$rolename}) eq 'HASH') {
 4399:                     $order = $current{$rolename}{'order'};
 4400:                 }
 4401:                 if ($order eq '') {
 4402:                     $order = $count;
 4403:                 }
 4404:                 $ordered{$order} = $rolename;
 4405:                 $count++;
 4406:             }
 4407:         }
 4408:         my $maxnum = scalar(keys(%ordered));
 4409:         my @roles_by_num = ();
 4410:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 4411:             push(@roles_by_num,$item);
 4412:         }
 4413:         my $context = 'domprefs';
 4414:         my $crstype = 'Course';
 4415:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4416:         my @accesstypes = ('all','dh','da','none');
 4417:         my ($numstatustypes,@jsarray);
 4418:         if (ref($types) eq 'ARRAY') {
 4419:             if (@{$types} > 0) {
 4420:                 $numstatustypes = scalar(@{$types});
 4421:                 push(@accesstypes,'status');
 4422:                 @jsarray = ('bystatus');
 4423:             }
 4424:         }
 4425:         my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh','da']);
 4426:         if (keys(%domhelpdesk)) {
 4427:             push(@accesstypes,('inc','exc'));
 4428:             push(@jsarray,('notinc','notexc'));
 4429:         }
 4430:         my $hiddenstr = join("','",@jsarray);
 4431:         $datatable .= &helpsettings_javascript(\@roles_by_num,$maxnum,$hiddenstr,$formname);
 4432:         my $context = 'domprefs';
 4433:         my $crstype = 'Course';
 4434:         my $prefix = 'helproles_';
 4435:         my $add_class = 'LC_hidden';
 4436:         foreach my $num (@roles_by_num) {
 4437:             my $role = $ordered{$num};
 4438:             my ($desc,$access,@statuses);
 4439:             if (ref($current{$role}) eq 'HASH') {
 4440:                 $desc = $current{$role}{'desc'};
 4441:                 $access = $current{$role}{'access'};
 4442:                 if (ref($current{$role}{'insttypes'}) eq 'ARRAY') {
 4443:                     @statuses = @{$current{$role}{'insttypes'}};
 4444:                 }
 4445:             }
 4446:             if ($desc eq '') {
 4447:                 $desc = $role;
 4448:             }
 4449:             my $identifier = 'custhelp'.$num;
 4450:             my %full=();
 4451:             my %levels= (
 4452:                          course => {},
 4453:                          domain => {},
 4454:                          system => {},
 4455:                         );
 4456:             my %levelscurrent=(
 4457:                                course => {},
 4458:                                domain => {},
 4459:                                system => {},
 4460:                               );
 4461:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 4462:             my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4463:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4464:             my $chgstr = ' onchange="javascript:reorderHelpRoles(this.form,'."'helproles_".$num."_pos'".');"';
 4465:             $datatable .= '<tr '.$css_class.'><td valign="top"><b>'.$role.'</b><br />'.
 4466:                           '<select name="helproles_'.$num.'_pos"'.$chgstr.'>';
 4467:             for (my $k=0; $k<=$maxnum; $k++) {
 4468:                 my $vpos = $k+1;
 4469:                 my $selstr;
 4470:                 if ($k == $num) {
 4471:                     $selstr = ' selected="selected" ';
 4472:                 }
 4473:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 4474:             }
 4475:             $datatable .= '</select>'.('&nbsp;'x2).
 4476:                           '<input type="hidden" name="helproles_'.$num.'" value="'.$role.'" />'.
 4477:                           '</td>'.
 4478:                           '<td><fieldset><legend>'.&mt('Role name').'</legend>'.
 4479:                           &mt('Name shown to users:').
 4480:                           '<input type="text" name="helproles_'.$num.'_desc" value="'.$desc.'" />'.
 4481:                           '</fieldset>'.
 4482:                           &helpdeskroles_access($dom,$prefix,$num,$add_class,$current{$role},\@accesstypes,
 4483:                                                 $othertitle,$usertypes,$types,\%domhelpdesk).
 4484:                           '<fieldset>'.
 4485:                           '<legend>'.&mt('Role privileges').&adhocbutton($prefix,$num,'privs','show').'</legend>'.
 4486:                           &Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 4487:                                                                    \%levelscurrent,$identifier,
 4488:                                                                    'LC_hidden',$prefix.$num.'_privs').
 4489:                           '</fieldset></td>';
 4490:             $itemcount ++;
 4491:         }
 4492:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4493:         my $newcust = 'custhelp'.$count;
 4494:         my (%privs,%levelscurrent);
 4495:         my %full=();
 4496:         my %levels= (
 4497:                      course => {},
 4498:                      domain => {},
 4499:                      system => {},
 4500:                     );
 4501:         &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 4502:         my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4503:         my $chgstr = ' onchange="javascript:reorderHelpRoles(this.form,'."'helproles_".$count."_pos'".');"';
 4504:         $datatable .= '<tr '.$css_class.'><td valign="top"><span class="LC_nobreak"><label>'.
 4505:                       '<input type="hidden" name="helproles_maxnum" value="'.$maxnum.'" />'."\n".
 4506:                       '<select name="helproles_'.$count.'_pos"'.$chgstr.'>';
 4507:         for (my $k=0; $k<$maxnum+1; $k++) {
 4508:             my $vpos = $k+1;
 4509:             my $selstr;
 4510:             if ($k == $maxnum) {
 4511:                 $selstr = ' selected="selected" ';
 4512:             }
 4513:             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 4514:         }
 4515:         $datatable .= '</select>&nbsp;'."\n".
 4516:                       '<input type="checkbox" name="newcusthelp" value="'.$count.'" />'. &mt('Add').
 4517:                       '</label></span></td>'.
 4518:                       '<td><fieldset><legend>'.&mt('Role name').'</legend>'.
 4519:                       '<span class="LC_nobreak">'.
 4520:                       &mt('Internal name:').
 4521:                       '<input type="text" size="10" name="custhelpname'.$count.'" value="" />'.
 4522:                       '</span>'.('&nbsp;'x4).
 4523:                       '<span class="LC_nobreak">'.
 4524:                       &mt('Name shown to users:').
 4525:                       '<input type="text" size="20" name="helproles_'.$count.'_desc" value="" />'.
 4526:                       '</span></fieldset>'.
 4527:                        &helpdeskroles_access($dom,$prefix,$count,'',undef,\@accesstypes,$othertitle,
 4528:                                              $usertypes,$types,\%domhelpdesk).
 4529:                       '<fieldset><legend>'.&mt('Role privileges').'</legend>'.
 4530:                       &Apache::lonuserutils::custom_role_header($context,$crstype,
 4531:                                                                 \@templateroles,$newcust).
 4532:                       &Apache::lonuserutils::custom_role_table('Course',\%full,\%levels,
 4533:                                                                \%levelscurrent,$newcust).
 4534:                       '</fieldset>'.
 4535:                       &helpsettings_javascript(\@roles_by_num,$maxnum,$hiddenstr,$formname).
 4536:                       '</td></tr>';
 4537:         $count ++;
 4538:         $$rowtotal += $count;
 4539:     }
 4540:     return $datatable;
 4541: }
 4542: 
 4543: sub adhocbutton {
 4544:     my ($prefix,$num,$field,$visibility) = @_;
 4545:     my %lt = &Apache::lonlocal::texthash(
 4546:                                           show => 'Show details',
 4547:                                           hide => 'Hide details',
 4548:                                         );
 4549:     return '<span style="text-decoration:line-through; font-weight: normal;">'.('&nbsp;'x10).
 4550:            '</span>'.('&nbsp;'x2).'<input type="button" id="'.$prefix.$num.'_'.$field.'_vis"'.
 4551:            ' value="'.$lt{$visibility}.'" style="height:20px;" '.
 4552:            'onclick="toggleHelpdeskItem('."'$num','$field'".');" />'.('&nbsp;'x2);
 4553: }
 4554: 
 4555: sub helpsettings_javascript {
 4556:     my ($roles_by_num,$total,$hiddenstr,$formname) = @_;
 4557:     return unless(ref($roles_by_num) eq 'ARRAY');
 4558:     my %html_js_lt = &Apache::lonlocal::texthash(
 4559:                                           show => 'Show details',
 4560:                                           hide => 'Hide details',
 4561:                                         );
 4562:     &html_escape(\%html_js_lt);
 4563:     my $jstext = '    var helproles = Array('."'".join("','",@{$roles_by_num})."'".');'."\n";
 4564:     return <<"ENDSCRIPT";
 4565: <script type="text/javascript">
 4566: // <![CDATA[
 4567: 
 4568: function reorderHelpRoles(form,item) {
 4569:     var changedVal;
 4570: $jstext
 4571:     var newpos = 'helproles_${total}_pos';
 4572:     var maxh = 1 + $total;
 4573:     var current = new Array();
 4574:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 4575:     if (item == newpos) {
 4576:         changedVal = newitemVal;
 4577:     } else {
 4578:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 4579:         current[newitemVal] = newpos;
 4580:     }
 4581:     for (var i=0; i<helproles.length; i++) {
 4582:         var elementName = 'helproles_'+helproles[i]+'_pos';
 4583:         if (elementName != item) {
 4584:             if (form.elements[elementName]) {
 4585:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 4586:                 current[currVal] = elementName;
 4587:             }
 4588:         }
 4589:     }
 4590:     var oldVal;
 4591:     for (var j=0; j<maxh; j++) {
 4592:         if (current[j] == undefined) {
 4593:             oldVal = j;
 4594:         }
 4595:     }
 4596:     if (oldVal < changedVal) {
 4597:         for (var k=oldVal+1; k<=changedVal ; k++) {
 4598:            var elementName = current[k];
 4599:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 4600:         }
 4601:     } else {
 4602:         for (var k=changedVal; k<oldVal; k++) {
 4603:             var elementName = current[k];
 4604:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 4605:         }
 4606:     }
 4607:     return;
 4608: }
 4609: 
 4610: function helpdeskAccess(num) {
 4611:     var curraccess = null;
 4612:     if (document.$formname.elements['helproles_'+num+'_access'].length) {
 4613:         for (var i=0; i<document.$formname.elements['helproles_'+num+'_access'].length; i++) {
 4614:             if (document.$formname.elements['helproles_'+num+'_access'][i].checked) {
 4615:                 curraccess = document.$formname.elements['helproles_'+num+'_access'][i].value;
 4616:             }
 4617:         }
 4618:     }
 4619:     var shown = Array();
 4620:     var hidden = Array();
 4621:     if (curraccess == 'none') {
 4622:         hidden = Array('$hiddenstr');
 4623:     } else {
 4624:         if (curraccess == 'status') {
 4625:             shown = Array('bystatus');
 4626:             hidden = Array('notinc','notexc');
 4627:         } else {
 4628:             if (curraccess == 'exc') {
 4629:                 shown = Array('notexc');
 4630:                 hidden = Array('notinc','bystatus');
 4631:             }
 4632:             if (curraccess == 'inc') {
 4633:                 shown = Array('notinc');
 4634:                 hidden = Array('notexc','bystatus');
 4635:             }
 4636:             if ((curraccess == 'all') || (curraccess == 'dh') || (curraccess == 'da')) {
 4637:                 hidden = Array('notinc','notexc','bystatus');
 4638:             }
 4639:         }
 4640:     }
 4641:     if (hidden.length > 0) {
 4642:         for (var i=0; i<hidden.length; i++) {
 4643:             if (document.getElementById('helproles_'+num+'_'+hidden[i])) {
 4644:                 document.getElementById('helproles_'+num+'_'+hidden[i]).style.display = 'none';
 4645:             }
 4646:         }
 4647:     }
 4648:     if (shown.length > 0) {
 4649:         for (var i=0; i<shown.length; i++) {
 4650:             if (document.getElementById('helproles_'+num+'_'+shown[i])) {
 4651:                 if (shown[i] == 'privs') {
 4652:                     document.getElementById('helproles_'+num+'_'+shown[i]).style.display = 'block';
 4653:                 } else {
 4654:                     document.getElementById('helproles_'+num+'_'+shown[i]).style.display = 'inline-block';
 4655:                 }
 4656:             }
 4657:         }
 4658:     }
 4659:     return;
 4660: }
 4661: 
 4662: function toggleHelpdeskItem(num,field) {
 4663:     if (document.getElementById('helproles_'+num+'_'+field)) {
 4664:         if (document.getElementById('helproles_'+num+'_'+field).className.match(/(?:^|\\s)LC_hidden(?!\\S)/)) {
 4665:             document.getElementById('helproles_'+num+'_'+field).className =
 4666:                 document.getElementById('helproles_'+num+'_'+field).className.replace(/(?:^|\\s)LC_hidden(?!\\S)/g ,'');
 4667:             if (document.getElementById('helproles_'+num+'_'+field+'_vis')) {
 4668:                 document.getElementById('helproles_'+num+'_'+field+'_vis').value = '$html_js_lt{hide}';
 4669:             }
 4670:         } else {
 4671:             document.getElementById('helproles_'+num+'_'+field).className += ' LC_hidden';
 4672:             if (document.getElementById('helproles_'+num+'_'+field+'_vis')) {
 4673:                 document.getElementById('helproles_'+num+'_'+field+'_vis').value = '$html_js_lt{show}';
 4674:             }
 4675:         }
 4676:     }
 4677:     return;
 4678: }
 4679: 
 4680: // ]]>
 4681: </script>
 4682: 
 4683: ENDSCRIPT
 4684: }
 4685: 
 4686: sub helpdeskroles_access {
 4687:     my ($dom,$prefix,$num,$add_class,$current,$accesstypes,$othertitle,
 4688:         $usertypes,$types,$domhelpdesk) = @_;
 4689:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($domhelpdesk) eq 'HASH'));
 4690:     my %lt = &Apache::lonlocal::texthash(
 4691:                     'rou'    => 'Role usage',
 4692:                     'whi'    => 'Which helpdesk personnel may use this role?',
 4693:                     'all'    => 'All with domain helpdesk or helpdesk assistant role',
 4694:                     'dh'     => 'All with domain helpdesk role',
 4695:                     'da'     => 'All with domain helpdesk assistant role',
 4696:                     'none'   => 'None',
 4697:                     'status' => 'Determined based on institutional status',
 4698:                     'inc'    => 'Include all, but exclude specific personnel',
 4699:                     'exc'    => 'Exclude all, but include specific personnel',
 4700:                   );
 4701:     my %usecheck = (
 4702:                      all => ' checked="checked"',
 4703:                    );
 4704:     my %displaydiv = (
 4705:                       status => 'none',
 4706:                       inc    => 'none',
 4707:                       exc    => 'none',
 4708:                       priv   => 'block',
 4709:                      );
 4710:     my $output;
 4711:     if (ref($current) eq 'HASH') {
 4712:         if (($current->{'access'} ne '') && ($current->{'access'} ne 'all')) {
 4713:             if (grep(/^\Q$current->{access}\E$/,@{$accesstypes})) {
 4714:                 $usecheck{$current->{access}} = $usecheck{'all'};
 4715:                 delete($usecheck{'all'});
 4716:                 if ($current->{access} =~ /^(status|inc|exc)$/) {
 4717:                     my $access = $1;
 4718:                     $displaydiv{$access} = 'inline';
 4719:                 } elsif ($current->{access} eq 'none') {
 4720:                     $displaydiv{'priv'} = 'none';
 4721:                 }
 4722:             }
 4723:         }
 4724:     }
 4725:     $output = '<fieldset id="'.$prefix.$num.'_usage"><legend>'.$lt{'rou'}.'</legend>'.
 4726:               '<p>'.$lt{'whi'}.'</p>';
 4727:     foreach my $access (@{$accesstypes}) {
 4728:         $output .= '<p><label><input type="radio" name="'.$prefix.$num.'_access" value="'.$access.'" '.$usecheck{$access}.
 4729:                    ' onclick="helpdeskAccess('."'$num'".');" />'.
 4730:                    $lt{$access}.'</label>';
 4731:         if ($access eq 'status') {
 4732:             $output .= '<div id="'.$prefix.$num.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 4733:                        &Apache::lonuserutils::adhoc_status_types($dom,$prefix,$num,$current->{$access},
 4734:                                                                  $othertitle,$usertypes,$types).
 4735:                        '</div>';
 4736:         } elsif (($access eq 'inc') && (keys(%{$domhelpdesk}) > 0)) {
 4737:             $output .= '<div id="'.$prefix.$num.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 4738:                        &Apache::lonuserutils::adhoc_staff($access,$prefix,$num,$current->{$access},$domhelpdesk).
 4739:                        '</div>';
 4740:         } elsif (($access eq 'exc') && (keys(%{$domhelpdesk}) > 0)) {
 4741:             $output .= '<div id="'.$prefix.$num.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 4742:                        &Apache::lonuserutils::adhoc_staff($access,$prefix,$num,$current->{$access},$domhelpdesk).
 4743:                        '</div>';
 4744:         }
 4745:         $output .= '</p>';
 4746:     }
 4747:     $output .= '</fieldset>';
 4748:     return $output;
 4749: }
 4750: 
 4751: sub radiobutton_prefs {
 4752:     my ($settings,$toggles,$defaultchecked,$choices,$itemcount,$onclick,
 4753:         $additional,$align,$firstval) = @_;
 4754:     return unless ((ref($toggles) eq 'ARRAY') && (ref($defaultchecked) eq 'HASH') &&
 4755:                    (ref($choices) eq 'HASH'));
 4756: 
 4757:     my (%checkedon,%checkedoff,$datatable,$css_class);
 4758: 
 4759:     foreach my $item (@{$toggles}) {
 4760:         if ($defaultchecked->{$item} eq 'on') {
 4761:             $checkedon{$item} = ' checked="checked" ';
 4762:             $checkedoff{$item} = ' ';
 4763:         } elsif ($defaultchecked->{$item} eq 'off') {
 4764:             $checkedoff{$item} = ' checked="checked" ';
 4765:             $checkedon{$item} = ' ';
 4766:         }
 4767:     }
 4768:     if (ref($settings) eq 'HASH') {
 4769:         foreach my $item (@{$toggles}) {
 4770:             if ($settings->{$item} eq '1') {
 4771:                 $checkedon{$item} =  ' checked="checked" ';
 4772:                 $checkedoff{$item} = ' ';
 4773:             } elsif ($settings->{$item} eq '0') {
 4774:                 $checkedoff{$item} =  ' checked="checked" ';
 4775:                 $checkedon{$item} = ' ';
 4776:             }
 4777:         }
 4778:     }
 4779:     if ($onclick) {
 4780:         $onclick = ' onclick="'.$onclick.'"';
 4781:     }
 4782:     foreach my $item (@{$toggles}) {
 4783:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4784:         $datatable .=
 4785:             '<tr'.$css_class.'><td valign="top">'.
 4786:             '<span class="LC_nobreak">'.$choices->{$item}.
 4787:             '</span></td>';
 4788:         if ($align eq 'left') {
 4789:             $datatable .= '<td class="LC_left_item">';
 4790:         } else {
 4791:             $datatable .= '<td class="LC_right_item">';
 4792:         }
 4793:         $datatable .= '<span class="LC_nobreak">';
 4794:         if ($firstval eq 'no') {
 4795:             $datatable .=
 4796:                 '<label><input type="radio" name="'.
 4797:                 $item.'" '.$checkedoff{$item}.' value="0"'.$onclick.' />'.&mt('No').
 4798:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'" '.
 4799:                 $checkedon{$item}.' value="1"'.$onclick.' />'.&mt('Yes').'</label>';
 4800:         } else {
 4801:             $datatable .=
 4802:             '<label><input type="radio" name="'.
 4803:             $item.'" '.$checkedon{$item}.' value="1"'.$onclick.' />'.&mt('Yes').
 4804:             '</label>&nbsp;<label><input type="radio" name="'.$item.'" '.
 4805:             $checkedoff{$item}.' value="0"'.$onclick.' />'.&mt('No').'</label>';
 4806:         }
 4807:         $datatable .= '</span>'.$additional.'</td></tr>';
 4808:         $itemcount ++;
 4809:     }
 4810:     return ($datatable,$itemcount);
 4811: }
 4812: 
 4813: sub print_ltitools {
 4814:     my ($dom,$settings,$rowtotal) = @_;
 4815:     my $rownum = 0;
 4816:     my $css_class;
 4817:     my $itemcount = 1;
 4818:     my $maxnum = 0;
 4819:     my %ordered;
 4820:     if (ref($settings) eq 'HASH') {
 4821:         foreach my $item (keys(%{$settings})) {
 4822:             if (ref($settings->{$item}) eq 'HASH') {
 4823:                 my $num = $settings->{$item}{'order'};
 4824:                 $ordered{$num} = $item;
 4825:             }
 4826:         }
 4827:     }
 4828:     my $confname = $dom.'-domainconfig';
 4829:     my $switchserver = &check_switchserver($dom,$confname);
 4830:     my $maxnum = scalar(keys(%ordered));
 4831:     my $datatable;
 4832:     my %lt = &ltitools_names();
 4833:     my @courseroles = ('cc','in','ta','ep','st');
 4834:     my @ltiroles = qw(Instructor ContentDeveloper TeachingAssistant Learner);
 4835:     my @fields = ('fullname','firstname','lastname','email','roles','user');
 4836:     if (keys(%ordered)) {
 4837:         my @items = sort { $a <=> $b } keys(%ordered);
 4838:         for (my $i=0; $i<@items; $i++) {
 4839:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4840:             my $item = $ordered{$items[$i]};
 4841:             my ($title,$key,$secret,$url,$lifetime,$imgsrc,%sigsel);
 4842:             if (ref($settings->{$item}) eq 'HASH') {
 4843:                 $title = $settings->{$item}->{'title'};
 4844:                 $url = $settings->{$item}->{'url'};
 4845:                 $key = $settings->{$item}->{'key'};
 4846:                 $secret = $settings->{$item}->{'secret'};
 4847:                 $lifetime = $settings->{$item}->{'lifetime'};
 4848:                 my $image = $settings->{$item}->{'image'};
 4849:                 if ($image ne '') {
 4850:                     $imgsrc = '<img src="'.$image.'" alt="'.&mt('Tool Provider icon').'" />';
 4851:                 }
 4852:                 if ($settings->{$item}->{'sigmethod'} eq 'HMAC-256') {
 4853:                     $sigsel{'HMAC-256'} = ' selected="selected"';
 4854:                 } else {
 4855:                     $sigsel{'HMAC-SHA1'} = ' selected="selected"';
 4856:                 }
 4857:             }
 4858:             my $chgstr = ' onchange="javascript:reorderLTITools(this.form,'."'ltitools_".$item."'".');"';
 4859:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 4860:                          .'<select name="ltitools_'.$item.'"'.$chgstr.'>';
 4861:             for (my $k=0; $k<=$maxnum; $k++) {
 4862:                 my $vpos = $k+1;
 4863:                 my $selstr;
 4864:                 if ($k == $i) {
 4865:                     $selstr = ' selected="selected" ';
 4866:                 }
 4867:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 4868:             }
 4869:             $datatable .= '</select>'.('&nbsp;'x2).
 4870:                 '<label><input type="checkbox" name="ltitools_del" value="'.$item.'" />'.
 4871:                 &mt('Delete?').'</label></span></td>'.
 4872:                 '<td colspan="2">'.
 4873:                 '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 4874:                 '<span class="LC_nobreak">'.$lt{'title'}.':<input type="text" size="20" name="ltitools_title_'.$i.'" value="'.$title.'" /></span> '.
 4875:                 ('&nbsp;'x2).
 4876:                 '<span class="LC_nobreak">'.$lt{'version'}.':<select name="ltitools_version_'.$i.'">'.
 4877:                 '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '.
 4878:                 ('&nbsp;'x2).
 4879:                 '<span class="LC_nobreak">'.$lt{'msgtype'}.':<select name="ltitools_msgtype_'.$i.'">'.
 4880:                 '<option value="basic-lti-launch-request" selected="selected">Launch</option></select></span> '.
 4881:                 ('&nbsp;'x2).
 4882:                 '<span class="LC_nobreak">'.$lt{'sigmethod'}.':<select name="ltitools_sigmethod_'.$i.'">'.
 4883:                 '<option value="HMAC-SHA1"'.$sigsel{'HMAC-SHA1'}.'>HMAC-SHA1</option>'.
 4884:                 '<option value="HMAC-SHA256"'.$sigsel{'HMAC-SHA256'}.'>HMAC-SHA256</option></select></span>'.
 4885:                 '<br /><br />'.
 4886:                 '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="40" name="ltitools_url_'.$i.'"'.
 4887:                 ' value="'.$url.'" /></span>'.
 4888:                 ('&nbsp;'x2).
 4889:                 '<span class="LC_nobreak">'.$lt{'key'}.':'.
 4890:                 '<input type="text" size="25" name="ltitools_key_'.$i.'" value="'.$key.'" /></span> '.
 4891:                 ('&nbsp;'x2).
 4892:                 '<span class="LC_nobreak">'.$lt{'lifetime'}.':'.
 4893:                 '<input type="text" size="5" name="ltitools_lifetime_'.$i.'" value="'.$lifetime.'" /></span> '.
 4894:                 ('&nbsp;'x2).
 4895:                 '<span class="LC_nobreak">'.$lt{'secret'}.':'.
 4896:                 '<input type="password" size="20" name="ltitools_secret_'.$i.'" value="'.$secret.'" />'.
 4897:                 '<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.ltitools_secret_'.$i.'.type='."'text'".' } else { this.form.ltitools_secret_'.$i.'.type='."'password'".' }" />'.&mt('Visible input').'</label>'.
 4898:                 '<input type="hidden" name="ltitools_id_'.$i.'" value="'.$item.'" /></span>'.
 4899:                 '</fieldset>'.
 4900:                 '<fieldset><legend>'.&mt('Optional settings').'</legend>'.
 4901:                 '<span class="LC_nobreak">'.&mt('Display target:');
 4902:             my %currdisp;
 4903:             if (ref($settings->{$item}->{'display'}) eq 'HASH') {
 4904:                 if ($settings->{$item}->{'display'}->{'target'} eq 'window') {
 4905:                     $currdisp{'window'} = ' checked="checked"';
 4906:                 } elsif ($settings->{$item}->{'display'}->{'target'} eq 'tab') {
 4907:                     $currdisp{'tab'} = ' checked="checked"';
 4908:                 } else {
 4909:                     $currdisp{'iframe'} = ' checked="checked"';
 4910:                 }
 4911:                 if ($settings->{$item}->{'display'}->{'width'} =~ /^(\d+)$/) {
 4912:                     $currdisp{'width'} = $1;
 4913:                 }
 4914:                 if ($settings->{$item}->{'display'}->{'height'} =~ /^(\d+)$/) {
 4915:                      $currdisp{'height'} = $1;
 4916:                 }
 4917:                 $currdisp{'linktext'} = $settings->{$item}->{'display'}->{'linktext'};
 4918:                 $currdisp{'explanation'} = $settings->{$item}->{'display'}->{'explanation'};
 4919:             } else {
 4920:                 $currdisp{'iframe'} = ' checked="checked"';
 4921:             }
 4922:             foreach my $disp ('iframe','tab','window') {
 4923:                 $datatable .= '<label><input type="radio" name="ltitools_target_'.$i.'" value="'.$disp.'"'.$currdisp{$disp}.' />'.
 4924:                               $lt{$disp}.'</label>'.('&nbsp;'x2);
 4925:             }
 4926:             $datatable .= ('&nbsp;'x4);
 4927:             foreach my $dimen ('width','height') {
 4928:                 $datatable .= '<label>'.$lt{$dimen}.'&nbsp;'.
 4929:                               '<input type="text" name="ltitools_'.$dimen.'_'.$i.'" size="5" value="'.$currdisp{$dimen}.'" /></label>'.
 4930:                               ('&nbsp;'x2);
 4931:             }
 4932:             $datatable .= '</span><br />'.
 4933:                           '<div class="LC_left_float">'.$lt{'linktext'}.'<br />'.
 4934:                           '<input type="text" name="ltitools_linktext_'.$i.'" size="25" value="'.$currdisp{'linktext'}.'" /></div>'.
 4935:                           '<div class="LC_left_float">'.$lt{'explanation'}.'<br />'.
 4936:                           '<textarea name="ltitools_explanation_'.$i.'" rows="5" cols="40">'.$currdisp{'explanation'}.
 4937:                           '</textarea></div><div style=""></div>'.
 4938:                           '<div style="padding:0;clear:both;margin:0;border:0"></div>';
 4939:             $datatable .= '<span class="LC_nobreak">'.$lt{'icon'}.':&nbsp;';
 4940:             if ($imgsrc) {
 4941:                 $datatable .= $imgsrc.
 4942:                               '<label><input type="checkbox" name="ltitools_image_del"'.
 4943:                               ' value="'.$item.'" />'.&mt('Delete?').'</label></span> '.
 4944:                               '<span class="LC_nobreak">&nbsp;'.&mt('Replace:').'&nbsp;';
 4945:             } else {
 4946:                 $datatable .= '('.&mt('if larger than 21x21 pixels, image will be scaled').')&nbsp;';
 4947:             }
 4948:             if ($switchserver) {
 4949:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 4950:             } else {
 4951:                 $datatable .= '<input type="file" name="ltitools_image_'.$i.'" value="" />';
 4952:             }
 4953:             $datatable .= '</span></fieldset>';
 4954:             my (%checkedfields,%rolemaps,$userincdom);
 4955:             if (ref($settings->{$item}) eq 'HASH') {
 4956:                 if (ref($settings->{$item}->{'fields'}) eq 'HASH') {
 4957:                     %checkedfields = %{$settings->{$item}->{'fields'}};
 4958:                 }
 4959:                 $userincdom = $settings->{$item}->{'incdom'};
 4960:                 if (ref($settings->{$item}->{'roles'}) eq 'HASH') {
 4961:                     %rolemaps = %{$settings->{$item}->{'roles'}};
 4962:                     $checkedfields{'roles'} = 1;
 4963:                 }
 4964:             }
 4965:             $datatable .= '<fieldset><legend>'.&mt('User data sent on launch').'</legend>'.
 4966:                           '<span class="LC_nobreak">';
 4967:             my $userfieldstyle = 'display:none;';
 4968:             my $seluserdom = '';
 4969:             my $unseluserdom = ' selected="selected"';
 4970:             foreach my $field (@fields) {
 4971:                 my ($checked,$onclick,$id,$spacer);
 4972:                 if ($checkedfields{$field}) {
 4973:                     $checked = ' checked="checked"';
 4974:                 }
 4975:                 if ($field eq 'user') {
 4976:                     $id = ' id="ltitools_user_field_'.$i.'"';
 4977:                     $onclick = ' onclick="toggleLTITools(this.form,'."'$field','$i'".')"';
 4978:                     if ($checked) {
 4979:                         $userfieldstyle = 'display:inline-block';
 4980:                         if ($userincdom) {
 4981:                             $seluserdom = $unseluserdom;
 4982:                             $unseluserdom = '';
 4983:                         }
 4984:                     }
 4985:                 } else {
 4986:                     $spacer = ('&nbsp;' x2);
 4987:                 }
 4988:                 $datatable .= '<label>'.
 4989:                               '<input type="checkbox" name="ltitools_fields_'.$i.'" value="'.$field.'"'.$id.$checked.$onclick.' />'.
 4990:                               $lt{$field}.'</label>'.$spacer;
 4991:             }
 4992:             $datatable .= '</span>';
 4993:             $datatable .= '<div style="'.$userfieldstyle.'" id="ltitools_user_div_'.$i.'">'.
 4994:                           '<span class="LC_nobreak"> : '.
 4995:                           '<select name="ltitools_userincdom_'.$i.'">'.
 4996:                           '<option value="">'.&mt('Select').'</option>'.
 4997:                           '<option value="0"'.$unseluserdom.'>'.&mt('username').'</option>'.
 4998:                           '<option value="1"'.$seluserdom.'>'.&mt('username:domain').'</option>'.
 4999:                           '</select></span></div>';
 5000:             $datatable .= '</fieldset>'.
 5001:                           '<fieldset><legend>'.&mt('Role mapping').'</legend><table><tr>';
 5002:             foreach my $role (@courseroles) {
 5003:                 my ($selected,$selectnone);
 5004:                 if (!$rolemaps{$role}) {
 5005:                     $selectnone = ' selected="selected"';
 5006:                 }
 5007:                 $datatable .= '<td align="center">'.
 5008:                               &Apache::lonnet::plaintext($role,'Course').'<br />'.
 5009:                               '<select name="ltitools_roles_'.$role.'_'.$i.'">'.
 5010:                               '<option value=""'.$selectnone.'>'.&mt('Select').'</option>';
 5011:                 foreach my $ltirole (@ltiroles) {
 5012:                     unless ($selectnone) {
 5013:                         if ($rolemaps{$role} eq $ltirole) {
 5014:                             $selected = ' selected="selected"';
 5015:                         } else {
 5016:                             $selected = '';
 5017:                         }
 5018:                     }
 5019:                     $datatable .= '<option value="'.$ltirole.'"'.$selected.'>'.$ltirole.'</option>';
 5020:                 }
 5021:                 $datatable .= '</select></td>';
 5022:             }
 5023:             $datatable .= '</tr></table></fieldset>';
 5024:             my %courseconfig;
 5025:             if (ref($settings->{$item}) eq 'HASH') {
 5026:                 if (ref($settings->{$item}->{'crsconf'}) eq 'HASH') {
 5027:                     %courseconfig = %{$settings->{$item}->{'crsconf'}};
 5028:                 }
 5029:             }
 5030:             $datatable .= '<fieldset><legend>'.&mt('Configurable in course').'</legend><span class="LC_nobreak">';
 5031:             foreach my $item ('label','title','target','linktext','explanation','append') {
 5032:                 my $checked;
 5033:                 if ($courseconfig{$item}) {
 5034:                     $checked = ' checked="checked"';
 5035:                 }
 5036:                 $datatable .= '<label>'.
 5037:                        '<input type="checkbox" name="ltitools_courseconfig_'.$i.'" value="'.$item.'"'.$checked.' />'.
 5038:                        $lt{'crs'.$item}.'</label>'.('&nbsp;' x2)."\n";
 5039:             }
 5040:             $datatable .= '</span></fieldset>'.
 5041:                           '<fieldset><legend>'.&mt('Custom items sent on launch').'</legend>'.
 5042:                           '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>';
 5043:             if (ref($settings->{$item}->{'custom'}) eq 'HASH') {
 5044:                 my %custom = %{$settings->{$item}->{'custom'}};
 5045:                 if (keys(%custom) > 0) {
 5046:                     foreach my $key (sort(keys(%custom))) {
 5047:                         $datatable .= '<tr><td><span class="LC_nobreak">'.
 5048:                                       '<label><input type="checkbox" name="ltitools_customdel_'.$i.'" value="'.
 5049:                                       $key.'" />'.&mt('Delete').'</label></span></td><td>'.$key.'</td>'.
 5050:                                       '<td><input type="text" name="ltitools_customval_'.$key.'_'.$i.'"'.
 5051:                                       ' value="'.$custom{$key}.'" /></td></tr>';
 5052:                     }
 5053:                 }
 5054:             }
 5055:             $datatable .= '<tr><td><span class="LC_nobreak">'.
 5056:                           '<label><input type="checkbox" name="ltitools_customadd" value="'.$i.'" />'.
 5057:                           &mt('Add').'</label></span></td><td><input type="text" name="ltitools_custom_name_'.$i.'" />'.
 5058:                           '</td><td><input type="text" name="ltitools_custom_value_'.$i.'" /></td></tr>';
 5059:             $datatable .= '</table></fieldset></td></tr>'."\n";
 5060:             $itemcount ++;
 5061:         }
 5062:     }
 5063:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5064:     my $chgstr = ' onchange="javascript:reorderLTITools(this.form,'."'ltitools_add_pos'".');"';
 5065:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 5066:                   '<input type="hidden" name="ltitools_maxnum" value="'.$maxnum.'" />'."\n".
 5067:                   '<select name="ltitools_add_pos"'.$chgstr.'>';
 5068:     for (my $k=0; $k<$maxnum+1; $k++) {
 5069:         my $vpos = $k+1;
 5070:         my $selstr;
 5071:         if ($k == $maxnum) {
 5072:             $selstr = ' selected="selected" ';
 5073:         }
 5074:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5075:     }
 5076:     $datatable .= '</select>&nbsp;'."\n".
 5077:                   '<input type="checkbox" name="ltitools_add" value="1" />'.&mt('Add').'</span></td>'."\n".
 5078:                   '<td colspan="2">'.
 5079:                   '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 5080:                   '<span class="LC_nobreak">'.$lt{'title'}.':<input type="text" size="20" name="ltitools_add_title" value="" /></span> '."\n".
 5081:                   ('&nbsp;'x2).
 5082:                   '<span class="LC_nobreak">'.$lt{'version'}.':<select name="ltitools_add_version">'.
 5083:                   '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '."\n".
 5084:                   ('&nbsp;'x2).
 5085:                   '<span class="LC_nobreak">'.$lt{'msgtype'}.':<select name="ltitools_add_msgtype">'.
 5086:                   '<option value="basic-lti-launch-request" selected="selected">Launch</option></select></span> '.
 5087:                   '<span class="LC_nobreak">'.$lt{'sigmethod'}.':<select name="ltitools_add_sigmethod">'.
 5088:                   '<option value="HMAC-SHA1" selected="selected">HMAC-SHA1</option>'.
 5089:                   '<option value="HMAC-SHA256">HMAC-SHA256</option></select></span>'.
 5090:                   '<br />'.
 5091:                   '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="40" name="ltitools_add_url" value="" /></span> '."\n".
 5092:                   ('&nbsp;'x2).
 5093:                   '<span class="LC_nobreak">'.$lt{'key'}.':<input type="text" size="25" name="ltitools_add_key" value="" /></span> '."\n".
 5094:                   ('&nbsp;'x2).
 5095:                   '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" size="5" name="ltitools_add_lifetime" value="300" /></span> '."\n".
 5096:                   ('&nbsp;'x2).
 5097:                   '<span class="LC_nobreak">'.$lt{'secret'}.':<input type="password" size="20" name="ltitools_add_secret" value="" />'.
 5098:                   '<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.ltitools_add_secret.type='."'text'".' } else { this.form.ltitools_add_secret.type='."'password'".' }" />'.&mt('Visible input').'</label></span> '."\n".
 5099:                   '</fieldset>'.
 5100:                   '<fieldset><legend>'.&mt('Optional settings').'</legend>'.
 5101:                   '<span class="LC_nobreak">'.&mt('Display target:');
 5102:     my %defaultdisp;
 5103:     $defaultdisp{'iframe'} = ' checked="checked"';
 5104:     foreach my $disp ('iframe','tab','window') {
 5105:         $datatable .= '<label><input type="radio" name="ltitools_add_target" value="'.$disp.'"'.$defaultdisp{$disp}.' />'.
 5106:                       $lt{$disp}.'</label>'.('&nbsp;'x2);
 5107:     }
 5108:     $datatable .= ('&nbsp;'x4);
 5109:     foreach my $dimen ('width','height') {
 5110:         $datatable .= '<label>'.$lt{$dimen}.'&nbsp;'.
 5111:                       '<input type="text" name="ltitools_add_'.$dimen.'" size="5" /></label>'.
 5112:                       ('&nbsp;'x2);
 5113:     }
 5114:     $datatable .= '</span><br />'.
 5115:                   '<div class="LC_left_float">'.$lt{'linktext'}.'<br />'.
 5116:                   '<input type="text" name="ltitools_add_linktext" size="5" /></div>'.
 5117:                   '<div class="LC_left_float">'.$lt{'explanation'}.'<br />'.
 5118:                   '<textarea name="ltitools_add_explanation" rows="5" cols="40"></textarea>'.
 5119:                   '</div><div style=""></div>'.
 5120:                   '<div style="padding:0;clear:both;margin:0;border:0"></div>';
 5121:     $datatable .= '<span class="LC_nobreak">'.$lt{'icon'}.':&nbsp;'.
 5122:                   '('.&mt('if larger than 21x21 pixels, image will be scaled').')&nbsp;';
 5123:     if ($switchserver) {
 5124:         $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 5125:     } else {
 5126:         $datatable .= '<input type="file" name="ltitools_add_image" value="" />';
 5127:     }
 5128:     $datatable .= '</span></fieldset>'.
 5129:                   '<fieldset><legend>'.&mt('User data sent on launch').'</legend>'.
 5130:                   '<span class="LC_nobreak">';
 5131:     foreach my $field (@fields) {
 5132:         my ($id,$onclick,$spacer);
 5133:         if ($field eq 'user') {
 5134:             $id = ' id="ltitools_user_field_add"';
 5135:             $onclick = ' onclick="toggleLTITools(this.form,'."'$field','add'".')"';
 5136:         } else {
 5137:             $spacer = ('&nbsp;' x2);
 5138:         }
 5139:         $datatable .= '<label>'.
 5140:                       '<input type="checkbox" name="ltitools_add_fields" value="'.$field.'"'.$id.$onclick.' />'.
 5141:                       $lt{$field}.'</label>'.$spacer;
 5142:     }
 5143:     $datatable .= '</span>'.
 5144:                   '<div style="display:none;" id="ltitools_user_div_add">'.
 5145:                   '<span class="LC_nobreak"> : '.
 5146:                   '<select name="ltitools_userincdom_add">'.
 5147:                   '<option value="" selected="selected">'.&mt('Select').'</option>'.
 5148:                   '<option value="0">'.&mt('username').'</option>'.
 5149:                   '<option value="1">'.&mt('username:domain').'</option>'.
 5150:                   '</select></span></div></fieldset>';
 5151:     $datatable .= '<fieldset><legend>'.&mt('Role mapping').'</legend><table><tr>';
 5152:     foreach my $role (@courseroles) {
 5153:         my ($checked,$checkednone);
 5154:         $datatable .= '<td align="center">'.
 5155:                       &Apache::lonnet::plaintext($role,'Course').'<br />'.
 5156:                       '<select name="ltitools_add_roles_'.$role.'">'.
 5157:                       '<option value="" selected="selected">'.&mt('Select').'</option>';
 5158:         foreach my $ltirole (@ltiroles) {
 5159:             $datatable .= '<option value="'.$ltirole.'">'.$ltirole.'</option>';
 5160:         }
 5161:         $datatable .= '</select></td>';
 5162:     }
 5163:     $datatable .= '</tr></table></fieldset>'.
 5164:                   '<fieldset><legend>'.&mt('Configurable in course').'</legend><span class="LC_nobreak">';
 5165:     foreach my $item ('label','title','target','linktext','explanation','append') {
 5166:         $datatable .= '<label>'.
 5167:                       '<input type="checkbox" name="ltitools_courseconfig" value="'.$item.'" checked="checked" />'.
 5168:                       $lt{'crs'.$item}.'</label>'.('&nbsp;' x2)."\n";
 5169:     }
 5170:     $datatable .= '</span></fieldset>'.
 5171:                   '<fieldset><legend>'.&mt('Custom items sent on launch').'</legend>'.
 5172:                   '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>'.
 5173:                   '<tr><td><span class="LC_nobreak">'.
 5174:                   '<label><input type="checkbox" name="ltitools_add_custom" value="1" />'.
 5175:                   &mt('Add').'</label></span></td><td><input type="text" name="ltitools_add_custom_name" />'.
 5176:                   '</td><td><input type="text" name="ltitools_add_custom_value" /></td></tr>'.
 5177:                   '</table></fieldset>'."\n".
 5178:                   '</td>'."\n".
 5179:                   '</tr>'."\n";
 5180:     $itemcount ++;
 5181:     return $datatable;
 5182: }
 5183: 
 5184: sub ltitools_names {
 5185:     my %lt = &Apache::lonlocal::texthash(
 5186:                                           'title'          => 'Title',
 5187:                                           'version'        => 'Version',
 5188:                                           'msgtype'        => 'Message Type',
 5189:                                           'sigmethod'      => 'Signature Method',
 5190:                                           'url'            => 'URL',
 5191:                                           'key'            => 'Key',
 5192:                                           'lifetime'       => 'Nonce lifetime (s)',
 5193:                                           'secret'         => 'Secret',
 5194:                                           'icon'           => 'Icon',
 5195:                                           'user'           => 'User',
 5196:                                           'fullname'       => 'Full Name',
 5197:                                           'firstname'      => 'First Name',
 5198:                                           'lastname'       => 'Last Name',
 5199:                                           'email'          => 'E-mail',
 5200:                                           'roles'          => 'Role',
 5201:                                           'window'         => 'Window',
 5202:                                           'tab'            => 'Tab',
 5203:                                           'iframe'         => 'iFrame',
 5204:                                           'height'         => 'Height',
 5205:                                           'width'          => 'Width',
 5206:                                           'linktext'       => 'Default Link Text',
 5207:                                           'explanation'    => 'Default Explanation',
 5208:                                           'crstarget'      => 'Display target',
 5209:                                           'crslabel'       => 'Course label',
 5210:                                           'crstitle'       => 'Course title',
 5211:                                           'crslinktext'    => 'Link Text',
 5212:                                           'crsexplanation' => 'Explanation',
 5213:                                           'crsappend'      => 'Provider URL',
 5214:                                         );
 5215: 
 5216:     return %lt;
 5217: }
 5218: 
 5219: sub print_lti {
 5220:     my ($position,$dom,$settings,$rowtotal) = @_;
 5221:     my $itemcount = 1;
 5222:     my ($datatable,$css_class);
 5223:     my (%rules,%encrypt,%privkeys,%linkprot);
 5224:     if (ref($settings) eq 'HASH') {
 5225:         if ($position eq 'top') {
 5226:             if (exists($settings->{'encrypt'})) {
 5227:                 if (ref($settings->{'encrypt'}) eq 'HASH') {
 5228:                     foreach my $key (keys(%{$settings->{'encrypt'}})) {
 5229:                         $encrypt{'ltisec_'.$key.'linkprot'} = $settings->{'encrypt'}{$key};
 5230:                     }
 5231:                 }
 5232:             }
 5233:             if (exists($settings->{'private'})) {
 5234:                 if (ref($settings->{'private'}) eq 'HASH') {
 5235:                     if (ref($settings->{'private'}) eq 'HASH') {
 5236:                         if (ref($settings->{'private'}{'keys'}) eq 'ARRAY') {
 5237:                             map { $privkeys{$_} = 1; } (@{$settings->{'private'}{'keys'}});
 5238:                         }
 5239:                     }
 5240:                 }
 5241:             }
 5242:         } elsif ($position eq 'middle') {
 5243:             if (exists($settings->{'rules'})) {
 5244:                 if (ref($settings->{'rules'}) eq 'HASH') {
 5245:                     %rules = %{$settings->{'rules'}};
 5246:                 }
 5247:             }
 5248:         } elsif ($position eq 'bottom') {
 5249:             if (exists($settings->{'linkprot'})) {
 5250:                 if (ref($settings->{'linkprot'}) eq 'HASH') {
 5251:                     %linkprot = %{$settings->{'linkprot'}};
 5252:                     if ($linkprot{'lock'}) {
 5253:                         delete($linkprot{'lock'});
 5254:                     }
 5255:                 }
 5256:             }
 5257:         }
 5258:     }
 5259:     if ($position eq 'top') {
 5260:         my @ids=&Apache::lonnet::current_machine_ids();
 5261:         my %servers = &Apache::lonnet::get_servers($dom,'library');
 5262:         my $primary = &Apache::lonnet::domain($dom,'primary');
 5263:         my ($extra,$numshown);
 5264:         foreach my $hostid (sort(keys(%servers))) {
 5265:             my ($showextra,$divsty,$switch);
 5266:             if ($hostid eq $primary) {
 5267:                 if ($encrypt{'ltisec_domlinkprot'}) {
 5268:                     $showextra = 1;
 5269:                 }
 5270:             }
 5271:             if ($encrypt{'ltisec_crslinkprot'}) {
 5272:                 $showextra = 1;
 5273:             }
 5274:             unless (grep(/^\Q$hostid\E$/,@ids)) {
 5275:                 $switch = 1;
 5276:             }
 5277:             if ($showextra) {
 5278:                 $numshown ++;
 5279:                 $divsty = 'display:inline-block';
 5280:             } else {
 5281:                 $divsty = 'display:none';
 5282:             }
 5283:             $extra .= '<fieldset id="ltisec_info_'.$hostid.'" style="'.$divsty.'">'.
 5284:                       '<legend>'.$hostid.'</legend>';
 5285:             if ($switch) {
 5286:                 my $switchserver = '<a href="/adm/switchserver?otherserver='.$hostid.'&amp;role='.
 5287:                                    &HTML::Entities::encode($env{'request.role'},'\'<>"&').
 5288:                                    '&amp;destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
 5289:                 if (exists($privkeys{$hostid})) {
 5290:                     $extra .= '<div id="ltisec_divcurrprivkey_'.$hostid.'" style="display:inline-block" />'.
 5291:                               '<span class="LC_nobreak">'.
 5292:                               &mt('Encryption Key').': ['.&mt('not shown').'] '.('&nbsp;'x2).'</span></div>'.
 5293:                               '<span class="LC_nobreak">'.&mt('Change?').
 5294:                               '<label><input type="radio" value="0" name="ltisec_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$hostid'".');" checked="checked" />'.&mt('No').'</label>'.
 5295:                               ('&nbsp;'x2).
 5296:                               '<label><input type="radio" value="1" name="ltisec_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$hostid'".');" />'.&mt('Yes').
 5297:                               '</label>&nbsp;&nbsp;</span><div id="ltisec_divchgprivkey_'.$hostid.'" style="display:none" />'.
 5298:                               '<span class="LC_nobreak"> - '.&mt('submit from server ([_1]): [_2].',$hostid,$switchserver).
 5299:                               '</span></div>';
 5300:                 } else {
 5301:                     $extra .= '<span class="LC_nobreak">'.
 5302:                               &mt('Key required').' - '.&mt('submit from server ([_1]): [_2].',$hostid,$switchserver).
 5303:                               '</span>'."\n";
 5304:                 }
 5305:             } elsif (exists($privkeys{$hostid})) {
 5306:                 $extra .= '<div id="ltisec_divcurrprivkey_'.$hostid.'" style="display:inline-block" /><span class="LC_nobreak">'.
 5307:                           &mt('Encryption Key').': ['.&mt('not shown').'] '.('&nbsp;'x2).'</span></div>'.
 5308:                           '<span class="LC_nobreak">'.&mt('Change?').
 5309:                           '<label><input type="radio" value="0" name="ltisec_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$hostid'".');" checked="checked" />'.&mt('No').'</label>'.
 5310:                           ('&nbsp;'x2).
 5311:                           '<label><input type="radio" value="1" name="ltisec_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$hostid'".');" />'.&mt('Yes').
 5312:                           '</label>&nbsp;&nbsp;</span><div id="ltisec_divchgprivkey_'.$hostid.'" style="display:none" />'.
 5313:                           '<span class="LC_nobreak">'.&mt('New Key').':'.
 5314:                           '<input type="password" size="20" name="ltisec_privkey_'.$hostid.'" value="" autocomplete="off" />'.
 5315:                           '<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.ltisec_privkey_'.$hostid.'.type='."'text'".' } else { this.form.ltisec_privkey_'.$hostid.'.type='."'password'".' }" />'.&mt('Visible input').'</label>'.
 5316:                           '</span></div>';
 5317:             } else {
 5318:                 $extra .= '<span class="LC_nobreak">'.&mt('Encryption Key').':'.
 5319:                           '<input type="password" size="20" name="ltisec_privkey_'.$hostid.'" value="" autocomplete="off" />'.
 5320:                           '<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.ltisec_privkey_'.$hostid.'.type='."'text'".' } else { this.form.ltisec_privkey_'.$hostid.'.type='."'password'".' }" />'.&mt('Visible input').'</label>';
 5321:             }
 5322:             $extra .= '</fieldset>';
 5323:         }
 5324:         my %choices = &Apache::lonlocal::texthash (
 5325:                                                       ltisec_crslinkprot => 'Encrypt stored link protection secrets defined in courses',
 5326:                                                       ltisec_domlinkprot => 'Encrypt stored link protection secrets defined in domain',
 5327:                                                   );
 5328:         my @toggles = qw(ltisec_crslinkprot ltisec_domlinkprot);
 5329:         my %defaultchecked = (
 5330:                                'ltisec_crslinkprot' => 'off',
 5331:                                'ltisec_domlinkprot' => 'off',
 5332:                              );
 5333:         my ($onclick,$itemcount);
 5334:         $onclick = 'javascript:toggleLTIEncKey(this.form);';
 5335:         ($datatable,$itemcount) = &radiobutton_prefs(\%encrypt,\@toggles,\%defaultchecked,
 5336:                                                      \%choices,$itemcount,$onclick,'','left','no');
 5337: 
 5338:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5339:         my $noprivkeysty = 'display:inline-block';
 5340:         if ($numshown) {
 5341:             $noprivkeysty = 'display:none';
 5342:         }
 5343:         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.&mt('Encryption Key(s)').'</td>'.
 5344:                       '<td><div id="ltisec_noprivkey" style="'.$noprivkeysty.'" >'.
 5345:                       '<span class="LC_nobreak">'.&mt('Not in use').'</span></div>'.
 5346:                       $extra.
 5347:                       '</td></tr>';
 5348:         $itemcount ++;
 5349:         $$rowtotal += $itemcount;
 5350:     } elsif ($position eq 'middle') {
 5351:         $datatable = &password_rules('secrets',\$itemcount,\%rules);
 5352:         $$rowtotal += $itemcount;
 5353:     } elsif ($position eq 'bottom') {
 5354:          $datatable .= &Apache::courseprefs::print_linkprotection($dom,'',$settings,$rowtotal,'','','domain');
 5355:     }
 5356:     return $datatable;
 5357: }
 5358: 
 5359: sub print_coursedefaults {
 5360:     my ($position,$dom,$settings,$rowtotal) = @_;
 5361:     my ($css_class,$datatable,%checkedon,%checkedoff,%defaultchecked,@toggles);
 5362:     my $itemcount = 1;
 5363:     my %choices =  &Apache::lonlocal::texthash (
 5364:         uploadquota          => 'Default quota for files uploaded directly to course/community using Course Editor (MB)',
 5365:         anonsurvey_threshold => 'Responder count needed before showing submissions for anonymous surveys',
 5366:         coursecredits        => 'Credits can be specified for courses',
 5367:         uselcmath            => 'Math preview uses LON-CAPA previewer (javascript) in place of DragMath (Java)',
 5368:         usejsme              => 'Molecule editor uses JSME (HTML5) in place of JME (Java)',
 5369:         inline_chem          => 'Use inline previewer for chemical reaction response in place of pop-up',
 5370:         texengine            => 'Default method to display mathematics',
 5371:         postsubmit           => 'Disable submit button/keypress following student submission',
 5372:         canclone             => "People who may clone a course (besides course's owner and coordinators)",
 5373:         mysqltables          => 'Lifetime (s) of "Temporary" MySQL tables (student performance data) on homeserver',
 5374:     );
 5375:         ltiauth              => 'Student username in LTI launch of deep-linked URL can be accepted without re-authentication',
 5376:     my %staticdefaults = (
 5377:                            anonsurvey_threshold => 10,
 5378:                            uploadquota          => 500,
 5379:                            postsubmit           => 60,
 5380:                            mysqltables          => 172800,
 5381:                          );
 5382:     if ($position eq 'top') {
 5383:         %defaultchecked = (
 5384:                             'uselcmath'       => 'on',
 5385:                             'usejsme'         => 'on',
 5386:                             'inline_chem'     => 'on',
 5387:                             'canclone'        => 'none',
 5388:                           );
 5389:         @toggles = ('uselcmath','usejsme','inline_chem');
 5390:         my $deftex = $Apache::lonnet::deftex;
 5391:         if (ref($settings) eq 'HASH') {
 5392:             if ($settings->{'texengine'}) {
 5393:                 if ($settings->{'texengine'} =~ /^(MathJax|mimetex|tth)$/) {
 5394:                     $deftex = $settings->{'texengine'};
 5395:                 }
 5396:             }
 5397:         }
 5398:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5399:         my $mathdisp = '<tr'.$css_class.'><td style="vertical-align: top">'.
 5400:                        '<span class="LC_nobreak">'.$choices{'texengine'}.
 5401:                        '</span></td><td class="LC_right_item">'.
 5402:                        '<select name="texengine">'."\n";
 5403:         my %texoptions = (
 5404:                             MathJax  => 'MathJax',
 5405:                             mimetex  => &mt('Convert to Images'),
 5406:                             tth      => &mt('TeX to HTML'),
 5407:                          );
 5408:         foreach my $renderer ('MathJax','mimetex','tth') {
 5409:             my $selected = '';
 5410:             if ($renderer eq $deftex) {
 5411:                 $selected = ' selected="selected"';
 5412:             }
 5413:             $mathdisp .= '<option value="'.$renderer.'"'.$selected.'>'.$texoptions{$renderer}.'</option>'."\n";
 5414:         }
 5415:         $mathdisp .= '</select></td></tr>'."\n";
 5416:         $itemcount ++;
 5417:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 5418:                                                      \%choices,$itemcount);
 5419:         $datatable = $mathdisp.$datatable;
 5420:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5421:         $datatable .=
 5422:             '<tr'.$css_class.'><td valign="top">'.
 5423:             '<span class="LC_nobreak">'.$choices{'canclone'}.
 5424:             '</span></td><td class="LC_left_item">';
 5425:         my $currcanclone = 'none';
 5426:         my $onclick;
 5427:         my @cloneoptions = ('none','domain');
 5428:         my %clonetitles = &Apache::lonlocal::texthash (
 5429:                              none     => 'No additional course requesters',
 5430:                              domain   => "Any course requester in course's domain",
 5431:                              instcode => 'Course requests for official courses ...',
 5432:                           );
 5433:         my (%codedefaults,@code_order,@posscodes);
 5434:         if (&Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
 5435:                                                     \@code_order) eq 'ok') {
 5436:             if (@code_order > 0) {
 5437:                 push(@cloneoptions,'instcode');
 5438:                 $onclick = ' onclick="toggleDisplay(this.form,'."'cloneinstcode'".');"';
 5439:             }
 5440:         }
 5441:         if (ref($settings) eq 'HASH') {
 5442:             if ($settings->{'canclone'}) {
 5443:                 if (ref($settings->{'canclone'}) eq 'HASH') {
 5444:                     if (ref($settings->{'canclone'}{'instcode'}) eq 'ARRAY') {
 5445:                         if (@code_order > 0) {
 5446:                             $currcanclone = 'instcode';
 5447:                             @posscodes = @{$settings->{'canclone'}{'instcode'}};
 5448:                         }
 5449:                     }
 5450:                 } elsif ($settings->{'canclone'} eq 'domain') {
 5451:                     $currcanclone = $settings->{'canclone'};
 5452:                 }
 5453:             }
 5454:         }
 5455:         foreach my $option (@cloneoptions) {
 5456:             my ($checked,$additional);
 5457:             if ($currcanclone eq $option) {
 5458:                 $checked = ' checked="checked"';
 5459:             }
 5460:             if ($option eq 'instcode') {
 5461:                 if (@code_order) {
 5462:                     my $show = 'none';
 5463:                     if ($checked) {
 5464:                         $show = 'block';
 5465:                     }
 5466:                     $additional = '<div id="cloneinstcode" style="display:'.$show.'" />'.
 5467:                                   &mt('Institutional codes for new and cloned course have identical:').
 5468:                                   '<br />';
 5469:                     foreach my $item (@code_order) {
 5470:                         my $codechk;
 5471:                         if ($checked) {
 5472:                             if (grep(/^\Q$item\E$/,@posscodes)) {
 5473:                                 $codechk = ' checked="checked"';
 5474:                             }
 5475:                         }
 5476:                         $additional .= '<label>'.
 5477:                                        '<input type="checkbox" name="clonecode" value="'.$item.'"'.$codechk.' />'.
 5478:                                        $item.'</label>';
 5479:                     }
 5480:                     $additional .= ('&nbsp;'x2).'('.&mt('check as many as needed').')</div>';
 5481:                 }
 5482:             }
 5483:             $datatable .=
 5484:                 '<span class="LC_nobreak"><label><input type="radio" name="canclone"'.$checked.
 5485:                 ' value="'.$option.'"'.$onclick.' />'.$clonetitles{$option}.
 5486:                 '</label>&nbsp;'.$additional.'</span><br />';
 5487:         }
 5488:         $datatable .= '</td>'.
 5489:                       '</tr>';
 5490:         $itemcount ++;
 5491:     } else {
 5492:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 5493:         my ($currdefresponder,%defcredits,%curruploadquota,%deftimeout,%currmysql);
 5494:         my $currusecredits = 0;
 5495:         my $postsubmitclient = 1;
 5496:         my $ltiauth = 0;
 5497:         my @types = ('official','unofficial','community','textbook');
 5498:         if (ref($settings) eq 'HASH') {
 5499:             if ($settings->{'ltiauth'}) {
 5500:                 $ltiauth = 1;
 5501:             }
 5502:             $currdefresponder = $settings->{'anonsurvey_threshold'};
 5503:             if (ref($settings->{'uploadquota'}) eq 'HASH') {
 5504:                 foreach my $type (keys(%{$settings->{'uploadquota'}})) {
 5505:                     $curruploadquota{$type} = $settings->{'uploadquota'}{$type};
 5506:                 }
 5507:             }
 5508:             if (ref($settings->{'coursecredits'}) eq 'HASH') {
 5509:                 foreach my $type (@types) {
 5510:                     next if ($type eq 'community');
 5511:                     $defcredits{$type} = $settings->{'coursecredits'}->{$type};
 5512:                     if ($defcredits{$type} ne '') {
 5513:                         $currusecredits = 1;
 5514:                     }
 5515:                 }
 5516:             }
 5517:             if (ref($settings->{'postsubmit'}) eq 'HASH') {
 5518:                 if ($settings->{'postsubmit'}->{'client'} eq 'off') {
 5519:                     $postsubmitclient = 0;
 5520:                     foreach my $type (@types) {
 5521:                         $deftimeout{$type} = $staticdefaults{'postsubmit'};
 5522:                     }
 5523:                 } else {
 5524:                     foreach my $type (@types) {
 5525:                         if (ref($settings->{'postsubmit'}->{'timeout'}) eq 'HASH') {
 5526:                             if ($settings->{'postsubmit'}->{'timeout'}->{$type} =~ /^\d+$/) {
 5527:                                 $deftimeout{$type} = $settings->{'postsubmit'}->{'timeout'}->{$type};
 5528:                             } else {
 5529:                                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 5530:                             }
 5531:                         } else {
 5532:                             $deftimeout{$type} = $staticdefaults{'postsubmit'};
 5533:                         }
 5534:                     }
 5535:                 }
 5536:             } else {
 5537:                 foreach my $type (@types) {
 5538:                     $deftimeout{$type} = $staticdefaults{'postsubmit'};
 5539:                 }
 5540:             }
 5541:             if (ref($settings->{'mysqltables'}) eq 'HASH') {
 5542:                 foreach my $type (keys(%{$settings->{'mysqltables'}})) {
 5543:                     $currmysql{$type} = $settings->{'mysqltables'}{$type};
 5544:                 }
 5545:             } else {
 5546:                 foreach my $type (@types) {
 5547:                     $currmysql{$type} = $staticdefaults{'mysqltables'};
 5548:                 }
 5549:             }
 5550:         } else {
 5551:             foreach my $type (@types) {
 5552:                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 5553:             }
 5554:         }
 5555:         if (!$currdefresponder) {
 5556:             $currdefresponder = $staticdefaults{'anonsurvey_threshold'};
 5557:         } elsif ($currdefresponder < 1) {
 5558:             $currdefresponder = 1;
 5559:         }
 5560:         foreach my $type (@types) {
 5561:             if ($curruploadquota{$type} eq '') {
 5562:                 $curruploadquota{$type} = $staticdefaults{'uploadquota'};
 5563:             }
 5564:         }
 5565:         $datatable .=
 5566:                 '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 5567:                 $choices{'anonsurvey_threshold'}.
 5568:                 '</span></td>'.
 5569:                 '<td class="LC_right_item"><span class="LC_nobreak">'.
 5570:                 '<input type="text" name="anonsurvey_threshold"'.
 5571:                 ' value="'.$currdefresponder.'" size="5" /></span>'.
 5572:                 '</td></tr>'."\n";
 5573:         $itemcount ++;
 5574:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 5575:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 5576:                       $choices{'uploadquota'}.
 5577:                       '</span></td>'.
 5578:                       '<td align="right" class="LC_right_item">'.
 5579:                       '<table><tr>';
 5580:         foreach my $type (@types) {
 5581:             $datatable .= '<td align="center">'.&mt($type).'<br />'.
 5582:                            '<input type="text" name="uploadquota_'.$type.'"'.
 5583:                            ' value="'.$curruploadquota{$type}.'" size="5" /></td>';
 5584:         }
 5585:         $datatable .= '</tr></table></td></tr>'."\n";
 5586:         $itemcount ++;
 5587:         my $onclick = "toggleDisplay(this.form,'credits');";
 5588:         my $display = 'none';
 5589:         if ($currusecredits) {
 5590:             $display = 'block';
 5591:         }
 5592:         my $additional = '<div id="credits" style="display: '.$display.'">'.
 5593:                          '<i>'.&mt('Default credits').'</i><br /><table><tr>';
 5594:         foreach my $type (@types) {
 5595:             next if ($type eq 'community');
 5596:             $additional .= '<td align="center">'.&mt($type).'<br />'.
 5597:                            '<input type="text" name="'.$type.'_credits"'.
 5598:                            ' value="'.$defcredits{$type}.'" size="3" /></td>';
 5599:         }
 5600:         $additional .= '</tr></table></div>'."\n";
 5601:         %defaultchecked = ('coursecredits' => 'off');
 5602:         @toggles = ('coursecredits');
 5603:         my $current = {
 5604:                         'coursecredits' => $currusecredits,
 5605:                       };
 5606:         (my $table,$itemcount) =
 5607:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 5608:                                \%choices,$itemcount,$onclick,$additional,'left');
 5609:         $datatable .= $table;
 5610:         $onclick = "toggleDisplay(this.form,'studentsubmission');";
 5611:         my $display = 'none';
 5612:         if ($postsubmitclient) {
 5613:             $display = 'block';
 5614:         }
 5615:         $additional = '<div id="studentsubmission" style="display: '.$display.'">'.
 5616:                       &mt('Number of seconds submit is disabled').'<br />'.
 5617:                       '<i>'.&mt('Enter 0 to remain disabled until page reload.').'</i><br />'.
 5618:                       '<table><tr>';
 5619:         foreach my $type (@types) {
 5620:             $additional .= '<td align="center">'.&mt($type).'<br />'.
 5621:                            '<input type="text" name="'.$type.'_timeout" value="'.
 5622:                            $deftimeout{$type}.'" size="5" /></td>';
 5623:         }
 5624:         $additional .= '</tr></table></div>'."\n";
 5625:         %defaultchecked = ('postsubmit' => 'on');
 5626:         @toggles = ('postsubmit');
 5627:         $current = {
 5628:                        'postsubmit' => $postsubmitclient,
 5629:                    };
 5630:         ($table,$itemcount) =
 5631:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 5632:                                \%choices,$itemcount,$onclick,$additional,'left');
 5633:         $datatable .= $table;
 5634:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 5635:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 5636:                       $choices{'mysqltables'}.
 5637:                       '</span></td>'.
 5638:                       '<td align="right" class="LC_right_item">'.
 5639:                       '<table><tr>';
 5640:         foreach my $type (@types) {
 5641:             $datatable .= '<td align="center">'.&mt($type).'<br />'.
 5642:                            '<input type="text" name="mysqltables_'.$type.'"'.
 5643:                            ' value="'.$currmysql{$type}.'" size="8" /></td>';
 5644:         }
 5645:         $datatable .= '</tr></table></td></tr>'."\n";
 5646:         $itemcount ++;
 5647:         %defaultchecked = ('ltiauth' => 'off');
 5648:         @toggles = ('ltiauth');
 5649:         $current = {
 5650:                        'ltiauth' => $ltiauth,
 5651:                    };
 5652:         ($table,$itemcount) =
 5653:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 5654:                                \%choices,$itemcount,undef,undef,'left');
 5655:         $datatable .= $table;
 5656:         $itemcount ++;
 5657:     }
 5658:     $$rowtotal += $itemcount;
 5659:     return $datatable;
 5660: }
 5661: 
 5662: sub print_selfenrollment {
 5663:     my ($position,$dom,$settings,$rowtotal) = @_;
 5664:     my ($css_class,$datatable);
 5665:     my $itemcount = 1;
 5666:     my @types = ('official','unofficial','community','textbook');
 5667:     if (($position eq 'top') || ($position eq 'middle')) {
 5668:         my ($rowsref,$titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
 5669:         my %descs = &Apache::lonuserutils::selfenroll_default_descs();
 5670:         my @rows;
 5671:         my $key;
 5672:         if ($position eq 'top') {
 5673:             $key = 'admin'; 
 5674:             if (ref($rowsref) eq 'ARRAY') {
 5675:                 @rows = @{$rowsref};
 5676:             }
 5677:         } elsif ($position eq 'middle') {
 5678:             $key = 'default';
 5679:             @rows = ('types','registered','approval','limit');
 5680:         }
 5681:         foreach my $row (@rows) {
 5682:             if (defined($titlesref->{$row})) {
 5683:                 $itemcount ++;
 5684:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5685:                 $datatable .= '<tr'.$css_class.'>'.
 5686:                               '<td>'.$titlesref->{$row}.'</td>'.
 5687:                               '<td class="LC_left_item">'.
 5688:                               '<table><tr>';
 5689:                 my (%current,%currentcap);
 5690:                 if (ref($settings) eq 'HASH') {
 5691:                     if (ref($settings->{$key}) eq 'HASH') {
 5692:                         foreach my $type (@types) {
 5693:                             if (ref($settings->{$key}->{$type}) eq 'HASH') {
 5694:                                 $current{$type} = $settings->{$key}->{$type}->{$row};
 5695:                             }
 5696:                             if (($row eq 'limit') && ($key eq 'default')) {
 5697:                                 if (ref($settings->{$key}->{$type}) eq 'HASH') {
 5698:                                     $currentcap{$type} = $settings->{$key}->{$type}->{'cap'};
 5699:                                 }
 5700:                             }
 5701:                         }
 5702:                     }
 5703:                 }
 5704:                 my %roles = (
 5705:                              '0' => &Apache::lonnet::plaintext('dc'),
 5706:                             ); 
 5707:             
 5708:                 foreach my $type (@types) {
 5709:                     unless (($row eq 'registered') && ($key eq 'default')) {
 5710:                         $datatable .= '<th>'.&mt($type).'</th>';
 5711:                     }
 5712:                 }
 5713:                 unless (($row eq 'registered') && ($key eq 'default')) {
 5714:                     $datatable .= '</tr><tr>';
 5715:                 }
 5716:                 foreach my $type (@types) {
 5717:                     if ($type eq 'community') {
 5718:                         $roles{'1'} = &mt('Community personnel');
 5719:                     } else {
 5720:                         $roles{'1'} = &mt('Course personnel');
 5721:                     }
 5722:                     $datatable .= '<td style="vertical-align: top">';
 5723:                     if ($position eq 'top') {
 5724:                         my %checked;
 5725:                         if ($current{$type} eq '0') {
 5726:                             $checked{'0'} = ' checked="checked"';
 5727:                         } else {
 5728:                             $checked{'1'} = ' checked="checked"';
 5729:                         }
 5730:                         foreach my $role ('1','0') {
 5731:                             $datatable .= '<span class="LC_nobreak"><label>'.
 5732:                                           '<input type="radio" name="selfenrolladmin_'.$row.'_'.$type.'" '.
 5733:                                           'value="'.$role.'"'.$checked{$role}.' />'.
 5734:                                           $roles{$role}.'</label></span> ';
 5735:                         }
 5736:                     } else {
 5737:                         if ($row eq 'types') {
 5738:                             my %checked;
 5739:                             if ($current{$type} =~ /^(all|dom)$/) {
 5740:                                 $checked{$1} = ' checked="checked"';
 5741:                             } else {
 5742:                                 $checked{''} = ' checked="checked"';
 5743:                             }
 5744:                             foreach my $val ('','dom','all') {
 5745:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 5746:                                               '<input type ="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 5747:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 5748:                             }
 5749:                         } elsif ($row eq 'registered') {
 5750:                             my %checked;
 5751:                             if ($current{$type} eq '1') {
 5752:                                 $checked{'1'} = ' checked="checked"';
 5753:                             } else {
 5754:                                 $checked{'0'} = ' checked="checked"';
 5755:                             }
 5756:                             foreach my $val ('0','1') {
 5757:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 5758:                                               '<input type ="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 5759:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 5760:                             }
 5761:                         } elsif ($row eq 'approval') {
 5762:                             my %checked;
 5763:                             if ($current{$type} =~ /^([12])$/) {
 5764:                                 $checked{$1} = ' checked="checked"';
 5765:                             } else {
 5766:                                 $checked{'0'} = ' checked="checked"';
 5767:                             }
 5768:                             for my $val (0..2) {
 5769:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 5770:                                               '<input type="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 5771:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 5772:                             }
 5773:                         } elsif ($row eq 'limit') {
 5774:                             my %checked;
 5775:                             if ($current{$type} =~ /^(allstudents|selfenrolled)$/) {
 5776:                                 $checked{$1} = ' checked="checked"';
 5777:                             } else {
 5778:                                 $checked{'none'} = ' checked="checked"';
 5779:                             }
 5780:                             my $cap;
 5781:                             if ($currentcap{$type} =~ /^\d+$/) {
 5782:                                 $cap = $currentcap{$type};
 5783:                             }
 5784:                             foreach my $val ('none','allstudents','selfenrolled') {
 5785:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 5786:                                               '<input type="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 5787:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 5788:                             }
 5789:                             $datatable .= '<br />'.
 5790:                                           '<span class="LC_nobreak">'.&mt('Maximum allowed: ').
 5791:                                           '<input type="text" name="selfenrolldefault_cap_'.$type.'" size = "5" value="'.$cap.'" />'.
 5792:                                           '</span>'; 
 5793:                         }
 5794:                     }
 5795:                     $datatable .= '</td>';
 5796:                 }
 5797:                 $datatable .= '</tr>';
 5798:             }
 5799:             $datatable .= '</table></td></tr>';
 5800:         }
 5801:     } elsif ($position eq 'bottom') {
 5802:         $datatable .= &print_validation_rows('selfenroll',$dom,$settings,\$itemcount);
 5803:     }
 5804:     $$rowtotal += $itemcount;
 5805:     return $datatable;
 5806: }
 5807: 
 5808: sub print_validation_rows {
 5809:     my ($caller,$dom,$settings,$rowtotal) = @_;
 5810:     my ($itemsref,$namesref,$fieldsref);
 5811:     if ($caller eq 'selfenroll') { 
 5812:         ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
 5813:     } elsif ($caller eq 'requestcourses') {
 5814:         ($itemsref,$namesref,$fieldsref) = &Apache::loncoursequeueadmin::requestcourses_validation_types();
 5815:     }
 5816:     my %currvalidation;
 5817:     if (ref($settings) eq 'HASH') {
 5818:         if (ref($settings->{'validation'}) eq 'HASH') {
 5819:             %currvalidation = %{$settings->{'validation'}};
 5820:         }
 5821:     }
 5822:     my $datatable;
 5823:     my $itemcount = 0;
 5824:     foreach my $item (@{$itemsref}) {
 5825:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 5826:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 5827:                       $namesref->{$item}.
 5828:                       '</span></td>'.
 5829:                       '<td class="LC_left_item">';
 5830:         if (($item eq 'url') || ($item eq 'button')) {
 5831:             $datatable .= '<span class="LC_nobreak">'.
 5832:                           '<input type="text" name="'.$caller.'_validation_'.$item.'"'.
 5833:                           ' value="'.$currvalidation{$item}.'" size="50" /></span>';
 5834:         } elsif ($item eq 'fields') {
 5835:             my @currfields;
 5836:             if (ref($currvalidation{$item}) eq 'ARRAY') {
 5837:                 @currfields = @{$currvalidation{$item}};
 5838:             }
 5839:             foreach my $field (@{$fieldsref}) {
 5840:                 my $check = '';
 5841:                 if (grep(/^\Q$field\E$/,@currfields)) {
 5842:                     $check = ' checked="checked"';
 5843:                 }
 5844:                 $datatable .= '<span class="LC_nobreak"><label>'.
 5845:                               '<input type="checkbox" name="'.$caller.'_validation_fields"'.
 5846:                               ' value="'.$field.'"'.$check.' />'.$field.
 5847:                               '</label></span> ';
 5848:             }
 5849:         } elsif ($item eq 'markup') {
 5850:             $datatable .= '<textarea name="'.$caller.'_validation_markup" cols="50" rows="5">'.
 5851:                            $currvalidation{$item}.
 5852:                               '</textarea>';
 5853:         }
 5854:         $datatable .= '</td></tr>'."\n";
 5855:         if (ref($rowtotal)) {
 5856:             $itemcount ++;
 5857:         }
 5858:     }
 5859:     if ($caller eq 'requestcourses') {
 5860:         my %currhash;
 5861:         if (ref($settings) eq 'HASH') {
 5862:             if (ref($settings->{'validation'}) eq 'HASH') {
 5863:                 if ($settings->{'validation'}{'dc'} ne '') {
 5864:                     $currhash{$settings->{'validation'}{'dc'}} = 1;
 5865:                 }
 5866:             }
 5867:         }
 5868:         my $numinrow = 2;
 5869:         my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 5870:                                                        'validationdc',%currhash);
 5871:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 5872:         $datatable .= '<tr'.$css_class.'><td>';
 5873:         if ($numdc > 1) {
 5874:             $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)');
 5875:         } else {
 5876:             $datatable .=  &mt('Course creation processed as: ');
 5877:         }
 5878:         $datatable .= '</td><td class="LC_left_item">'.$dctable.'</td></tr>';
 5879:         $itemcount ++;
 5880:     }
 5881:     if (ref($rowtotal)) {
 5882:         $$rowtotal += $itemcount;
 5883:     }
 5884:     return $datatable;
 5885: }
 5886: 
 5887: sub print_passwords {
 5888:     my ($position,$dom,$confname,$settings,$rowtotal) = @_;
 5889:     my ($datatable,$css_class);
 5890:     my $itemcount = 0;
 5891:     my %titles = &Apache::lonlocal::texthash (
 5892:         captcha        => '"Forgot Password" CAPTCHA validation',
 5893:         link           => 'Reset link expiration (hours)',
 5894:         case           => 'Case-sensitive usernames/e-mail',
 5895:         prelink        => 'Information required (form 1)',
 5896:         postlink       => 'Information required (form 2)',
 5897:         emailsrc       => 'LON-CAPA e-mail address type(s)',
 5898:         customtext     => 'Domain specific text (HTML)',
 5899:         intauth_cost   => 'Encryption cost for bcrypt (positive integer)',
 5900:         intauth_check  => 'Check bcrypt cost if authenticated',
 5901:         intauth_switch => 'Existing crypt-based switched to bcrypt on authentication',
 5902:         permanent      => 'Permanent e-mail address',
 5903:         critical       => 'Critical notification address',
 5904:         notify         => 'Notification address',
 5905:         min            => 'Minimum password length',
 5906:         max            => 'Maximum password length',
 5907:         chars          => 'Required characters',
 5908:         numsaved       => 'Number of previous passwords to save and disallow reuse',
 5909:     );
 5910:     if ($position eq 'top') {
 5911:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 5912:         my $shownlinklife = 2;
 5913:         my $prelink = 'both';
 5914:         my (%casesens,%postlink,%emailsrc,$nostdtext,$customurl);
 5915:         if (ref($settings) eq 'HASH') {
 5916:             if ($settings->{resetlink} =~ /^\d+(|\.\d*)$/) {
 5917:                 $shownlinklife = $settings->{resetlink};
 5918:             }
 5919:             if (ref($settings->{resetcase}) eq 'ARRAY') {
 5920:                 map { $casesens{$_} = 1; } (@{$settings->{resetcase}});
 5921:             }
 5922:             if ($settings->{resetprelink} =~ /^(both|either)$/) {
 5923:                 $prelink = $settings->{resetprelink};
 5924:             }
 5925:             if (ref($settings->{resetpostlink}) eq 'HASH') {
 5926:                 %postlink = %{$settings->{resetpostlink}};
 5927:             }
 5928:             if (ref($settings->{resetemail}) eq 'ARRAY') {
 5929:                 map { $emailsrc{$_} = 1; } (@{$settings->{resetemail}});
 5930:             }
 5931:             if ($settings->{resetremove}) {
 5932:                 $nostdtext = 1;
 5933:             }
 5934:             if ($settings->{resetcustom}) {
 5935:                 $customurl = $settings->{resetcustom};
 5936:             }
 5937:         } else {
 5938:             if (ref($types) eq 'ARRAY') {
 5939:                 foreach my $item (@{$types}) {
 5940:                     $casesens{$item} = 1;
 5941:                     $postlink{$item} = ['username','email'];
 5942:                 }
 5943:             }
 5944:             $casesens{'default'} = 1;
 5945:             $postlink{'default'} = ['username','email'];
 5946:             $prelink = 'both';
 5947:             %emailsrc = (
 5948:                           permanent => 1,
 5949:                           critical  => 1,
 5950:                           notify    => 1,
 5951:             );
 5952:         }
 5953:         $datatable = &captcha_choice('passwords',$settings,$$rowtotal);
 5954:         $itemcount ++;
 5955:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5956:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'link'}.'</td>'.
 5957:                       '<td class="LC_left_item">'.
 5958:                       '<input type="textbox" value="'.$shownlinklife.'" '.
 5959:                       'name="passwords_link" size="3" /></td></tr>';
 5960:         $itemcount ++;
 5961:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5962:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'case'}.'</td>'.
 5963:                       '<td class="LC_left_item">';
 5964:         if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 5965:             foreach my $item (@{$types}) {
 5966:                 my $checkedcase;
 5967:                 if ($casesens{$item}) {
 5968:                     $checkedcase = ' checked="checked"';
 5969:                 }
 5970:                 $datatable .= '<span class="LC_nobreak"><label>'.
 5971:                               '<input type="checkbox" name="passwords_case_sensitive" value="'.
 5972:                               $item.'"'.$checkedcase.' />'.$usertypes->{$item}.'</label>'.
 5973:                               '</span>&nbsp;&nbsp; ';
 5974:             }
 5975:         }
 5976:         my $checkedcase;
 5977:         if ($casesens{'default'}) {
 5978:             $checkedcase = ' checked="checked"';
 5979:         }
 5980:         $datatable .= '<span class="LC_nobreak"><label><input type="checkbox" '.
 5981:                       'name="passwords_case_sensitive" value="default"'.$checkedcase.' />'.
 5982:                       $othertitle.'</label></span></td>';
 5983:         $itemcount ++;
 5984:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5985:         my %checkedpre = (
 5986:                              both => ' checked="checked"',
 5987:                              either => '',
 5988:                          );
 5989:         if ($prelink eq 'either') {
 5990:             $checkedpre{either} = ' checked="checked"';
 5991:             $checkedpre{both} = '';
 5992:         }
 5993:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'prelink'}.'</td>'.
 5994:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 5995:                       '<label><input type="radio" name="passwords_prelink" value="both"'.$checkedpre{'both'}.' />'.
 5996:                       &mt('Both username and e-mail address').'</label></span>&nbsp;&nbsp; '.
 5997:                       '<span class="LC_nobreak"><label>'.
 5998:                       '<input type="radio" name="passwords_prelink" value="either"'.$checkedpre{'either'}.' />'.
 5999:                       &mt('Either username or e-mail address').'</label></span></td></tr>';
 6000:         $itemcount ++;
 6001:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6002:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'postlink'}.'</td>'.
 6003:                       '<td class="LC_left_item">';
 6004:         my %postlinked;
 6005:         if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6006:             foreach my $item (@{$types}) {
 6007:                 undef(%postlinked);
 6008:                 $datatable .= '<fieldset style="display: inline-block;">'.
 6009:                               '<legend>'.$usertypes->{$item}.'</legend>';
 6010:                 if (ref($postlink{$item}) eq 'ARRAY') {
 6011:                     map { $postlinked{$_} = 1; } (@{$postlink{$item}});
 6012:                 }
 6013:                 foreach my $field ('email','username') {
 6014:                     my $checked;
 6015:                     if ($postlinked{$field}) {
 6016:                         $checked = ' checked="checked"';
 6017:                     }
 6018:                     $datatable .= '<span class="LC_nobreak"><label>'.
 6019:                                   '<input type="checkbox" name="passwords_postlink_'.$item.'" value="'.
 6020:                                   $field.'"'.$checked.' />'.$field.'</label>'.
 6021:                                   '<span>&nbsp;&nbsp; ';
 6022:                 }
 6023:                 $datatable .= '</fieldset>';
 6024:             }
 6025:         }
 6026:         if (ref($postlink{'default'}) eq 'ARRAY') {
 6027:             map { $postlinked{$_} = 1; } (@{$postlink{'default'}});
 6028:         }
 6029:         $datatable .= '<fieldset style="display: inline-block;">'.
 6030:                       '<legend>'.$othertitle.'</legend>';
 6031:         foreach my $field ('email','username') {
 6032:             my $checked;
 6033:             if ($postlinked{$field}) {
 6034:                 $checked = ' checked="checked"';
 6035:             }
 6036:             $datatable .= '<span class="LC_nobreak"><label>'.
 6037:                           '<input type="checkbox" name="passwords_postlink_default" value="'.
 6038:                           $field.'"'.$checked.' />'.$field.'</label>'.
 6039:                           '<span>&nbsp;&nbsp; ';
 6040:         }
 6041:         $datatable .= '</fieldset></td></tr>';
 6042:         $itemcount ++;
 6043:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6044:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'emailsrc'}.'</td>'.
 6045:                       '<td class="LC_left_item">';
 6046:         foreach my $type ('permanent','critical','notify') {
 6047:             my $checkedemail;
 6048:             if ($emailsrc{$type}) {
 6049:                 $checkedemail = ' checked="checked"';
 6050:             }
 6051:             $datatable .= '<span class="LC_nobreak"><label>'.
 6052:                           '<input type="checkbox" name="passwords_emailsrc" value="'.
 6053:                           $type.'"'.$checkedemail.' />'.$titles{$type}.'</label>'.
 6054:                           '<span>&nbsp;&nbsp; ';
 6055:         }
 6056:         $datatable .= '</td></tr>';
 6057:         $itemcount ++;
 6058:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6059:         my $switchserver = &check_switchserver($dom,$confname);
 6060:         my ($showstd,$noshowstd);
 6061:         if ($nostdtext) {
 6062:             $noshowstd = ' checked="checked"';
 6063:         } else {
 6064:             $showstd = ' checked="checked"';
 6065:         }
 6066:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'customtext'}.'</td>'.
 6067:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 6068:                       &mt('Retain standard text:').
 6069:                       '<label><input type="radio" name="passwords_stdtext" value="1"'.$showstd.' />'.
 6070:                       &mt('Yes').'</label>'.'&nbsp;'.
 6071:                       '<label><input type="radio" name="passwords_stdtext" value="0"'.$noshowstd.' />'.
 6072:                       &mt('No').'</label></span><br />'.
 6073:                       '<span class="LC_fontsize_small">'.
 6074:                       &mt('(If you use the same account ...  reset a password from this page.)').'</span><br /><br />'.
 6075:                       &mt('Include custom text:');
 6076:         if ($customurl) {
 6077:             my $link =  &Apache::loncommon::modal_link($customurl,&mt('custom text'),600,500,
 6078:                                                        undef,undef,undef,undef,'background-color:#ffffff');
 6079:             $datatable .= '<span class="LC_nobreak">&nbsp;'.$link.
 6080:                           '<label><input type="checkbox" name="passwords_custom_del"'.
 6081:                           ' value="1" />'.&mt('Delete?').'</label></span>'.
 6082:                           ' <span class="LC_nobreak">&nbsp;'.&mt('Replace:').'</span>';
 6083:         }
 6084:         if ($switchserver) {
 6085:             $datatable .= '<span class="LC_nobreak">&nbsp;'.&mt('Upload to library server: [_1]',$switchserver).'</span>';
 6086:         } else {
 6087:             $datatable .='<span class="LC_nobreak">&nbsp;'.
 6088:                          '<input type="file" name="passwords_customfile" /></span>';
 6089:         }
 6090:         $datatable .= '</td></tr>';
 6091:     } elsif ($position eq 'middle') {
 6092:         my %domconf = &Apache::lonnet::get_dom('configuration',['defaults'],$dom);
 6093:         my @items = ('intauth_cost','intauth_check','intauth_switch');
 6094:         my %defaults;
 6095:         if (ref($domconf{'defaults'}) eq 'HASH') {
 6096:             %defaults = %{$domconf{'defaults'}};
 6097:             if ($defaults{'intauth_cost'} !~ /^\d+$/) {
 6098:                 $defaults{'intauth_cost'} = 10;
 6099:             }
 6100:             if ($defaults{'intauth_check'} !~ /^(0|1|2)$/) {
 6101:                 $defaults{'intauth_check'} = 0;
 6102:             }
 6103:             if ($defaults{'intauth_switch'} !~ /^(0|1|2)$/) {
 6104:                 $defaults{'intauth_switch'} = 0;
 6105:             }
 6106:         } else {
 6107:             %defaults = (
 6108:                           'intauth_cost'   => 10,
 6109:                           'intauth_check'  => 0,
 6110:                           'intauth_switch' => 0,
 6111:                         );
 6112:         }
 6113:         foreach my $item (@items) {
 6114:             if ($itemcount%2) {
 6115:                 $css_class = '';
 6116:             } else {
 6117:                 $css_class = ' class="LC_odd_row" ';
 6118:             }
 6119:             $datatable .= '<tr'.$css_class.'>'.
 6120:                           '<td><span class="LC_nobreak">'.$titles{$item}.
 6121:                           '</span></td><td class="LC_left_item" colspan="3">';
 6122:             if ($item eq 'intauth_switch') {
 6123:                 my @options = (0,1,2);
 6124:                 my %optiondesc = &Apache::lonlocal::texthash (
 6125:                                    0 => 'No',
 6126:                                    1 => 'Yes',
 6127:                                    2 => 'Yes, and copy existing passwd file to passwd.bak file',
 6128:                                  );
 6129:                 $datatable .= '<table width="100%">';
 6130:                 foreach my $option (@options) {
 6131:                     my $checked = ' ';
 6132:                     if ($defaults{$item} eq $option) {
 6133:                         $checked = ' checked="checked"';
 6134:                     }
 6135:                     $datatable .= '<tr><td class="LC_left_item"><span class="LC_nobreak">'.
 6136:                                   '<label><input type="radio" name="'.$item.
 6137:                                   '" value="'.$option.'"'.$checked.' />'.
 6138:                                   $optiondesc{$option}.'</label></span></td></tr>';
 6139:                 }
 6140:                 $datatable .= '</table>';
 6141:             } elsif ($item eq 'intauth_check') {
 6142:                 my @options = (0,1,2);
 6143:                 my %optiondesc = &Apache::lonlocal::texthash (
 6144:                                    0 => 'No',
 6145:                                    1 => 'Yes, allow login then update passwd file using default cost (if higher)',
 6146:                                    2 => 'Yes, disallow login if stored cost is less than domain default',
 6147:                                  );
 6148:                 $datatable .= '<table width="100%">';
 6149:                 foreach my $option (@options) {
 6150:                     my $checked = ' ';
 6151:                     my $onclick;
 6152:                     if ($defaults{$item} eq $option) {
 6153:                         $checked = ' checked="checked"';
 6154:                     }
 6155:                     if ($option == 2) {
 6156:                         $onclick = ' onclick="javascript:warnIntAuth(this);"';
 6157:                     }
 6158:                     $datatable .= '<tr><td class="LC_left_item"><span class="LC_nobreak">'.
 6159:                                   '<label><input type="radio" name="'.$item.
 6160:                                   '" value="'.$option.'"'.$checked.$onclick.' />'.
 6161:                                   $optiondesc{$option}.'</label></span></td></tr>';
 6162:                 }
 6163:                 $datatable .= '</table>';
 6164:             } else {
 6165:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
 6166:                               $defaults{$item}.'" size="3" onblur="javascript:warnIntAuth(this);" />';
 6167:             }
 6168:             $datatable .= '</td></tr>';
 6169:             $itemcount ++;
 6170:         }
 6171:     } elsif ($position eq 'lower') {
 6172:         $datatable .= &password_rules('passwords',\$itemcount,$settings);
 6173:     } else {
 6174:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 6175:         my %ownerchg = (
 6176:                           by  => {},
 6177:                           for => {},
 6178:                        );
 6179:         my %ownertitles = &Apache::lonlocal::texthash (
 6180:                             by  => 'Course owner status(es) allowed',
 6181:                             for => 'Student status(es) allowed',
 6182:                           );
 6183:         if (ref($settings) eq 'HASH') {
 6184:             if (ref($settings->{crsownerchg}) eq 'HASH') {
 6185:                 if (ref($settings->{crsownerchg}{'by'}) eq 'ARRAY') {
 6186:                     map { $ownerchg{by}{$_} = 1; } (@{$settings->{crsownerchg}{'by'}});
 6187:                 }
 6188:                 if (ref($settings->{crsownerchg}{'for'}) eq 'ARRAY') {
 6189:                     map { $ownerchg{for}{$_} = 1; } (@{$settings->{crsownerchg}{'for'}});
 6190:                 }
 6191:             }
 6192:         }
 6193:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6194:         $datatable .= '<tr '.$css_class.'>'.
 6195:                       '<td>'.
 6196:                       &mt('Requirements').'<ul>'.
 6197:                       '<li>'.&mt("Course 'type' is not a Community").'</li>'.
 6198:                       '<li>'.&mt('User is Course Coordinator and also course owner').'</li>'.
 6199:                       '<li>'.&mt("Student's only active roles are student role(s) in course(s) owned by this user").'</li>'.
 6200:                       '<li>'.&mt('User, course, and student share same domain').'</li>'.
 6201:                       '</ul>'.
 6202:                       '</td>'.
 6203:                       '<td class="LC_left_item">';
 6204:         foreach my $item ('by','for') {
 6205:             $datatable .= '<fieldset style="display: inline-block;">'.
 6206:                           '<legend>'.$ownertitles{$item}.'</legend>';
 6207:             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6208:                 foreach my $type (@{$types}) {
 6209:                     my $checked;
 6210:                     if ($ownerchg{$item}{$type}) {
 6211:                         $checked = ' checked="checked"';
 6212:                     }
 6213:                     $datatable .= '<span class="LC_nobreak"><label>'.
 6214:                                   '<input type="checkbox" name="passwords_crsowner_'.$item.'" value="'.
 6215:                                   $type.'"'.$checked.' />'.$usertypes->{$type}.'</label>'.
 6216:                                   '</span>&nbsp;&nbsp; ';
 6217:                 }
 6218:             }
 6219:             my $checked;
 6220:             if ($ownerchg{$item}{'default'}) {
 6221:                 $checked = ' checked="checked"';
 6222:             }
 6223:             $datatable .= '<span class="LC_nobreak"><label><input type="checkbox" '.
 6224:                           'name="passwords_crsowner_'.$item.'" value="default"'.$checked.' />'.
 6225:                           $othertitle.'</label></span></fieldset>';
 6226:         }
 6227:         $datatable .= '</td></tr>';
 6228:     }
 6229:     return $datatable;
 6230: }
 6231: 
 6232: sub password_rules {
 6233:     my ($prefix,$itemcountref,$settings) = @_;
 6234:     my ($min,$max,%chars,$numsaved,$numinrow);
 6235:     my %titles;
 6236:     if ($prefix eq 'passwords') {
 6237:         %titles = &Apache::lonlocal::texthash (
 6238:             min            => 'Minimum password length',
 6239:             max            => 'Maximum password length',
 6240:             chars          => 'Required characters',
 6241:         );
 6242:     } elsif ($prefix eq 'secrets') {
 6243:         %titles = &Apache::lonlocal::texthash (
 6244:             min            => 'Minimum secret length',
 6245:             max            => 'Maximum secret length',
 6246:             chars          => 'Required characters',
 6247:         );
 6248:     }
 6249:     $min = $Apache::lonnet::passwdmin;
 6250:     my $datatable;
 6251:     my $itemcount;
 6252:     if (ref($itemcountref)) {
 6253:         $itemcount = $$itemcountref;
 6254:     }
 6255:     if (ref($settings) eq 'HASH') {
 6256:         if ($settings->{min}) {
 6257:             $min = $settings->{min};
 6258:         }
 6259:         if ($settings->{max}) {
 6260:             $max = $settings->{max};
 6261:         }
 6262:         if (ref($settings->{chars}) eq 'ARRAY') {
 6263:             map { $chars{$_} = 1; } (@{$settings->{chars}});
 6264:         }
 6265:         if ($prefix eq 'passwords') {
 6266:             if ($settings->{numsaved}) {
 6267:                 $numsaved = $settings->{numsaved};
 6268:             }
 6269:         }
 6270:     }
 6271:     my %rulenames = &Apache::lonlocal::texthash(
 6272:                                                  uc => 'At least one upper case letter',
 6273:                                                  lc => 'At least one lower case letter',
 6274:                                                  num => 'At least one number',
 6275:                                                  spec => 'At least one non-alphanumeric',
 6276:                                                );
 6277:     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6278:     $datatable .= '<tr'.$css_class.'><td>'.$titles{'min'}.'</td>'.
 6279:                   '<td class="LC_left_item"><span class="LC_nobreak">'.
 6280:                   '<input type="text" name="'.$prefix.'_min" value="'.$min.'" size="3" '.
 6281:                   'onblur="javascript:warnInt'.$prefix.'(this);" />'.
 6282:                   '<span class="LC_fontsize_small"> '.&mt('(Enter an integer: 7 or larger)').'</span>'.
 6283:                   '</span></td></tr>';
 6284:     $itemcount ++;
 6285:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6286:     $datatable .= '<tr'.$css_class.'><td>'.$titles{'max'}.'</td>'.
 6287:                   '<td class="LC_left_item"><span class="LC_nobreak">'.
 6288:                   '<input type="text" name="'.$prefix.'_max" value="'.$max.'" size="3" '.
 6289:                   'onblur="javascript:warnInt'.$prefix.'(this);" />'.
 6290:                   '<span class="LC_fontsize_small"> '.&mt('(Leave blank for no maximum)').'</span>'.
 6291:                   '</span></td></tr>';
 6292:     $itemcount ++;
 6293:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6294:     $datatable .= '<tr'.$css_class.'><td>'.$titles{'chars'}.'<br />'.
 6295:                   '<span class="LC_nobreak LC_fontsize_small">'.&mt('(Leave unchecked if not required)').
 6296:                   '</span></td>';
 6297:     my $numinrow = 2;
 6298:     my @possrules = ('uc','lc','num','spec');
 6299:     $datatable .= '<td class="LC_left_item"><table>';
 6300:     for (my $i=0; $i<@possrules; $i++) {
 6301:         my ($rem,$checked);
 6302:         if ($chars{$possrules[$i]}) {
 6303:             $checked = ' checked="checked"';
 6304:         }
 6305:         $rem = $i%($numinrow);
 6306:         if ($rem == 0) {
 6307:             if ($i > 0) {
 6308:                 $datatable .= '</tr>';
 6309:             }
 6310:             $datatable .= '<tr>';
 6311:         }
 6312:         $datatable .= '<td><span class="LC_nobreak"><label>'.
 6313:                       '<input type="checkbox" name="'.$prefix.'_chars" value="'.$possrules[$i].'"'.$checked.' />'.
 6314:                       $rulenames{$possrules[$i]}.'</label></span></td>';
 6315:     }
 6316:     my $rem = @possrules%($numinrow);
 6317:     my $colsleft = $numinrow - $rem;
 6318:     if ($colsleft > 1 ) {
 6319:         $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 6320:                       '&nbsp;</td>';
 6321:     } elsif ($colsleft == 1) {
 6322:         $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 6323:     }
 6324:     $datatable .='</table></td></tr>';
 6325:     $itemcount ++;
 6326:     if ($prefix eq 'passwords') {
 6327:         $titles{'numsaved'} = &mt('Number of previous passwords to save and disallow reuse');
 6328:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6329:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'numsaved'}.'</td>'.
 6330:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 6331:                       '<input type="text" name="'.$prefix.'_numsaved" value="'.$numsaved.'" size="3" '.
 6332:                       'onblur="javascript:warnInt'.$prefix.'(this);" />'.
 6333:                       '<span class="LC_fontsize_small"> '.&mt('(Leave blank to not save previous passwords)').'</span>'.
 6334:                       '</span></td></tr>';
 6335:         $itemcount ++;
 6336:     }
 6337:     if (ref($itemcountref)) {
 6338:         $$itemcountref += $itemcount;
 6339:     }
 6340:     return $datatable;
 6341: }
 6342: 
 6343: sub print_wafproxy {
 6344:     my ($position,$dom,$settings,$rowtotal) = @_;
 6345:     my $css_class;
 6346:     my $itemcount = 0;
 6347:     my $datatable;
 6348:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 6349:     my (%othercontrol,%otherdoms,%aliases,%saml,%values,$setdom,$showdom);
 6350:     my %lt = &wafproxy_titles();
 6351:     foreach my $server (sort(keys(%servers))) {
 6352:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
 6353:         next if ($serverhome eq '');
 6354:         my $serverdom;
 6355:         if ($serverhome ne $server) {
 6356:             $serverdom = &Apache::lonnet::host_domain($serverhome);
 6357:             if (($serverdom ne '') && (&Apache::lonnet::domain($serverdom) ne '')) {
 6358:                 $othercontrol{$server} = $serverdom;
 6359:             }
 6360:         } else {
 6361:             $serverdom = &Apache::lonnet::host_domain($server);
 6362:             next if (($serverdom eq '') || (&Apache::lonnet::domain($serverdom) eq ''));
 6363:             if ($serverdom ne $dom) {
 6364:                 $othercontrol{$server} = $serverdom;
 6365:             } else {
 6366:                 $setdom = 1;
 6367:                 if (ref($settings) eq 'HASH') {
 6368:                     if (ref($settings->{'alias'}) eq 'HASH') {
 6369:                         $aliases{$dom} = $settings->{'alias'};
 6370:                         if ($aliases{$dom} ne '') {
 6371:                             $showdom = 1;
 6372:                         }
 6373:                     }
 6374:                     if (ref($settings->{'saml'}) eq 'HASH') {
 6375:                         $saml{$dom} = $settings->{'saml'};
 6376:                     }
 6377:                 }
 6378:             }
 6379:         }
 6380:     }
 6381:     if ($setdom) {
 6382:         %{$values{$dom}} = ();
 6383:         if (ref($settings) eq 'HASH') {
 6384:             foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext') {
 6385:                 $values{$dom}{$item} = $settings->{$item};
 6386:             }
 6387:         }
 6388:     }
 6389:     if (keys(%othercontrol)) {
 6390:         %otherdoms = reverse(%othercontrol);
 6391:         foreach my $domain (keys(%otherdoms)) {
 6392:             %{$values{$domain}} = ();
 6393:             my %config = &Apache::lonnet::get_dom('configuration',['wafproxy'],$domain);
 6394:             if (ref($config{'wafproxy'}) eq 'HASH') {
 6395:                 $aliases{$domain} = $config{'wafproxy'}{'alias'};
 6396:                 if (exists($config{'wafproxy'}{'saml'})) {
 6397:                     $saml{$domain} = $config{'wafproxy'}{'saml'};
 6398:                 }
 6399:                 foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext') {
 6400:                     $values{$domain}{$item} = $config{'wafproxy'}{$item};
 6401:                 }
 6402:             }
 6403:         }
 6404:     }
 6405:     if ($position eq 'top') {
 6406:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 6407:         my %aliasinfo;
 6408:         foreach my $server (sort(keys(%servers))) {
 6409:             $itemcount ++;
 6410:             my $dom_in_effect;
 6411:             my $aliasrows = '<tr>'.
 6412:                             '<td class="LC_left_item" style="vertical-align: baseline;">'.
 6413:                             &mt('Hostname').':&nbsp;'.
 6414:                             '<i>'.&Apache::lonnet::hostname($server).'</i></td><td>&nbsp;</td>';
 6415:             if ($othercontrol{$server}) {
 6416:                 $dom_in_effect = $othercontrol{$server};
 6417:                 my ($current,$forsaml);
 6418:                 if (ref($aliases{$dom_in_effect}) eq 'HASH') {
 6419:                     $current = $aliases{$dom_in_effect}{$server};
 6420:                 }
 6421:                 if (ref($saml{$dom_in_effect}) eq 'HASH') {
 6422:                     if ($saml{$dom_in_effect}{$server}) {
 6423:                         $forsaml = 1;
 6424:                     }
 6425:                 }
 6426:                 $aliasrows .= '<td class="LC_left_item" style="vertical-align: baseline;">'.
 6427:                               &mt('Alias').':&nbsp';
 6428:                 if ($current) {
 6429:                     $aliasrows .= $current;
 6430:                     if ($forsaml) {
 6431:                          $aliasrows .= '&nbsp;('.&mt('also for SSO Auth').')';
 6432:                     }
 6433:                 } else {
 6434:                     $aliasrows .= &mt('None');
 6435:                 }
 6436:                 $aliasrows .= '&nbsp;<span class="LC_small">('.
 6437:                               &mt('controlled by domain: [_1]',
 6438:                                   '<b>'.$dom_in_effect.'</b>').')</span></td>';
 6439:             } else {
 6440:                 $dom_in_effect = $dom;
 6441:                 my ($current,$samlon,$samloff);
 6442:                 $samloff = ' checked="checked"';
 6443:                 if (ref($aliases{$dom}) eq 'HASH') {
 6444:                     if ($aliases{$dom}{$server}) {
 6445:                         $current = $aliases{$dom}{$server};
 6446:                     }
 6447:                 }
 6448:                 if (ref($saml{$dom}) eq 'HASH') {
 6449:                     if ($saml{$dom}{$server}) {
 6450:                         $samlon = $samloff;
 6451:                         undef($samloff);
 6452:                     }
 6453:                 }
 6454:                 $aliasrows .= '<td class="LC_left_item" style="vertical-align: baseline;">'.
 6455:                               &mt('Alias').':&nbsp;'.
 6456:                               '<input type="text" name="wafproxy_alias_'.$server.'" '.
 6457:                               'value="'.$current.'" size="30" />'.
 6458:                               ('&nbsp;'x2).'<span class="LC_nobreak">'.
 6459:                               &mt('Alias used for SSO Auth').':&nbsp;<label>'.
 6460:                               '<input type="radio" value="0"'.$samloff.' name="wafproxy_alias_saml_'.$server.'" />'.
 6461:                               &mt('No').'</label>&nbsp;<label>'.
 6462:                               '<input type="radio" value="1"'.$samlon.' name="wafproxy_alias_saml_'.$server.'" />'.
 6463:                               &mt('Yes').'</label></span>'.
 6464:                               '</td>';
 6465:             }
 6466:             $aliasrows .= '</tr>';
 6467:             $aliasinfo{$dom_in_effect} .= $aliasrows;
 6468:         }
 6469:         if ($aliasinfo{$dom}) {
 6470:             my ($onclick,$wafon,$wafoff,$showtable);
 6471:             $onclick = ' onclick="javascript:toggleWAF();"';
 6472:             $wafoff = ' checked="checked"';
 6473:             $showtable = ' style="display:none";';
 6474:             if ($showdom) {
 6475:                 $wafon = $wafoff;
 6476:                 $wafoff = '';
 6477:                 $showtable = ' style="display:inline;"';
 6478:             }
 6479:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6480:             $datatable = '<tr'.$css_class.'>'.
 6481:                          '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'<br />'.
 6482:                          '<span class="LC_nobreak">'.&mt('WAF in use?').'&nbsp;<label>'.
 6483:                          '<input type="radio" name="wafproxy_'.$dom.'" value="1"'.$wafon.$onclick.' />'.
 6484:                          &mt('Yes').'</label>'.('&nbsp;'x2).'<label>'.
 6485:                          '<input type="radio" name="wafproxy_'.$dom.'" value="0"'.$wafoff.$onclick.' />'.
 6486:                          &mt('No').'</label></span></td>'.
 6487:                          '<td class="LC_left_item">'.
 6488:                          '<table id="wafproxy_table"'.$showtable.'>'.$aliasinfo{$dom}.
 6489:                          '</table></td></tr>';
 6490:             $itemcount++;
 6491:         }
 6492:         if (keys(%otherdoms)) {
 6493:             foreach my $key (sort(keys(%otherdoms))) {
 6494:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6495:                 $datatable .= '<tr'.$css_class.'>'.
 6496:                               '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$key.'</b>').'</td>'.
 6497:                               '<td class="LC_left_item"><table>'.$aliasinfo{$key}.
 6498:                               '</table></td></tr>';
 6499:                 $itemcount++;
 6500:             }
 6501:         }
 6502:     } else {
 6503:         my %ip_methods = &remoteip_methods();
 6504:         if ($setdom) {
 6505:             $itemcount ++;
 6506:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6507:             my ($nowafstyle,$wafstyle,$curr_remotip,$currwafdisplay,$vpndircheck,$vpnaliascheck,
 6508:                 $currwafvpn,$wafrangestyle,$alltossl,$ssltossl);
 6509:             $wafstyle = ' style="display:none;"';
 6510:             $nowafstyle = ' style="display:table-row;"';
 6511:             $currwafdisplay = ' style="display: none"';
 6512:             $wafrangestyle = ' style="display: none"';
 6513:             $curr_remotip = 'n';
 6514:             $ssltossl = ' checked="checked"';
 6515:             if ($showdom) {
 6516:                 $wafstyle = ' style="display:table-row;"';
 6517:                 $nowafstyle =  ' style="display:none;"';
 6518:                 if (keys(%{$values{$dom}})) {
 6519:                     if ($values{$dom}{remoteip} =~ /^[nmh]$/) {
 6520:                         $curr_remotip = $values{$dom}{remoteip};
 6521:                     }
 6522:                     if ($curr_remotip eq 'h') {
 6523:                         $currwafdisplay = ' style="display:table-row"';
 6524:                         $wafrangestyle = ' style="display:inline-block;"';
 6525:                     }
 6526:                     if ($values{$dom}{'sslopt'}) {
 6527:                         $alltossl = ' checked="checked"';
 6528:                         $ssltossl = '';
 6529:                     }
 6530:                 }
 6531:                 if (($values{$dom}{'vpnint'} ne '') || ($values{$dom}{'vpnext'} ne '')) {
 6532:                     $vpndircheck = ' checked="checked"';
 6533:                     $currwafvpn = ' style="display:table-row;"';
 6534:                     $wafrangestyle = ' style="display:inline-block;"';
 6535:                 } else {
 6536:                     $vpnaliascheck = ' checked="checked"';
 6537:                     $currwafvpn = ' style="display:none;"';
 6538:                 }
 6539:             }
 6540:             $datatable .= '<tr'.$css_class.' id="nowafproxyrow_'.$dom.'"'.$wafstyle.'>'.
 6541:                           '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'</td>'.
 6542:                           '<td class="LC_right_item">'.&mt('WAF not in use, nothing to set').'</td>'.
 6543:                           '</tr>'.
 6544:                           '<tr'.$css_class.' id="wafproxyrow_'.$dom.'"'.$wafstyle.'>'.
 6545:                           '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'<br /><br />'.
 6546:                           '<div id="wafproxyranges_'.$dom.'">'.&mt('Format for comma separated IP ranges').':<br />'.
 6547:                           &mt('A.B.C.D/N or A.B.C.D-E.F.G.H').'<br />'.
 6548:                           &mt('Range(s) stored in CIDR notation').'</div></td>'.
 6549:                           '<td class="LC_left_item"><table>'.
 6550:                           '<tr>'.
 6551:                           '<td valign="top">'.$lt{'remoteip'}.':&nbsp;'.
 6552:                           '<select name="wafproxy_remoteip" id="wafproxy_remoteip" onchange="javascript:updateWAF();">';
 6553:             foreach my $option ('m','h','n') {
 6554:                 my $sel;
 6555:                 if ($option eq $curr_remotip) {
 6556:                    $sel = ' selected="selected"';
 6557:                 }
 6558:                 $datatable .= '<option value="'.$option.'"'.$sel.'>'.
 6559:                               $ip_methods{$option}.'</option>';
 6560:             }
 6561:             $datatable .= '</select></td></tr>'."\n".
 6562:                           '<tr id="wafproxy_header"'.$currwafdisplay.'><td>'.
 6563:                           $lt{'ipheader'}.':&nbsp;'.
 6564:                           '<input type="text" value="'.$values{$dom}{'ipheader'}.'" '.
 6565:                           'name="wafproxy_ipheader" />'.
 6566:                           '</td></tr>'."\n".
 6567:                           '<tr id="wafproxy_trust"'.$currwafdisplay.'><td>'.
 6568:                           $lt{'trusted'}.':<br />'.
 6569:                           '<textarea name="wafproxy_trusted" rows="3" cols="80">'.
 6570:                           $values{$dom}{'trusted'}.'</textarea>'.
 6571:                           '</td></tr>'."\n".
 6572:                           '<tr><td><hr /></td></tr>'."\n".
 6573:                           '<tr>'.
 6574:                           '<td valign="top">'.$lt{'vpnaccess'}.':<br /><span class="LC_nobreak">'.
 6575:                           '<label><input type="radio" name="wafproxy_vpnaccess"'.$vpndircheck.' value="1" onclick="javascript:checkWAF();" />'.
 6576:                           $lt{'vpndirect'}.'</label>'.('&nbsp;'x2).
 6577:                           '<label><input type="radio" name="wafproxy_vpnaccess"'.$vpnaliascheck.' value="0" onclick="javascript:checkWAF();" />'.
 6578:                           $lt{'vpnaliased'}.'</label></span></td></tr>';
 6579:             foreach my $item ('vpnint','vpnext') {
 6580:                 $datatable .= '<tr id="wafproxy_show_'.$item.'"'.$currwafvpn.'>'.
 6581:                               '<td valign="top">'.$lt{$item}.':<br />'.
 6582:                               '<textarea name="wafproxy_'.$item.'" rows="3" cols="80">'.
 6583:                               $values{$dom}{$item}.'</textarea>'.
 6584:                               '</td></tr>'."\n";
 6585:             }
 6586:             $datatable .= '<tr><td><hr /></td></tr>'."\n".
 6587:                           '<tr>'.
 6588:                           '<td valign="top">'.$lt{'sslopt'}.':<br /><span class="LC_nobreak">'.
 6589:                           '<label><input type="radio" name="wafproxy_sslopt"'.$alltossl.' value="1" />'.
 6590:                           $lt{'alltossl'}.'</label>'.('&nbsp;'x2).
 6591:                           '<label><input type="radio" name="wafproxy_sslopt"'.$ssltossl.' value="0" />'.
 6592:                           $lt{'ssltossl'}.'</label></span></td></tr>'."\n".
 6593:                           '</table></td></tr>';
 6594:         }
 6595:         if (keys(%otherdoms)) {
 6596:             foreach my $domain (sort(keys(%otherdoms))) {
 6597:                 $itemcount ++;
 6598:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6599:                 $datatable .= '<tr'.$css_class.'>'.
 6600:                               '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$domain.'</b>').'</td>'.
 6601:                               '<td class="LC_left_item"><table>';
 6602:                 foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
 6603:                     my $showval = &mt('None');
 6604:                     if ($item eq 'ssl') {
 6605:                         $showval = $lt{'ssltossl'};
 6606:                     }
 6607:                     if ($values{$domain}{$item}) {
 6608:                         $showval = $values{$domain}{$item};
 6609:                         if ($item eq 'ssl') {
 6610:                             $showval = $lt{'alltossl'};
 6611:                         } elsif ($item eq 'remoteip') {
 6612:                             $showval = $ip_methods{$values{$domain}{$item}};
 6613:                         }
 6614:                     }
 6615:                     $datatable .= '<tr>'.
 6616:                                   '<td>'.$lt{$item}.':&nbsp;'.$showval.'</td></tr>';
 6617:                 }
 6618:                 $datatable .= '</table></td></tr>';
 6619:             }
 6620:         }
 6621:     }
 6622:     $$rowtotal += $itemcount;
 6623:     return $datatable;
 6624: }
 6625: 
 6626: sub wafproxy_titles {
 6627:     return &Apache::lonlocal::texthash(
 6628:                remoteip   => "Method for determining user's IP",
 6629:                ipheader   => 'Request header containing remote IP',
 6630:                trusted    => 'Trusted IP range(s)',
 6631:                vpnaccess  => 'Access from institutional VPN',
 6632:                vpndirect  => 'via regular hostname (no WAF)',
 6633:                vpnaliased => 'via aliased hostname (WAF)',
 6634:                vpnint     => 'Internal IP Range(s) for VPN sessions',
 6635:                vpnext     => 'IP Range(s) for backend WAF connections',
 6636:                sslopt     => 'Forwarding http/https',
 6637:                alltossl   => 'WAF forwards both http and https requests to https',
 6638:                ssltossl   => 'WAF forwards http requests to http and https to https',
 6639:            );
 6640: }
 6641: 
 6642: sub remoteip_methods {
 6643:     return &Apache::lonlocal::texthash(
 6644:               m => 'Use Apache mod_remoteip',
 6645:               h => 'Use headers parsed by LON-CAPA',
 6646:               n => 'Not in use',
 6647:            );
 6648: }
 6649: 
 6650: sub print_usersessions {
 6651:     my ($position,$dom,$settings,$rowtotal) = @_;
 6652:     my ($css_class,$datatable,%checked,%choices);
 6653:     my (%by_ip,%by_location,@intdoms);
 6654:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location);
 6655: 
 6656:     my @alldoms = &Apache::lonnet::all_domains();
 6657:     my %serverhomes = %Apache::lonnet::serverhomeIDs;
 6658:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 6659:     my %altids = &id_for_thisdom(%servers);
 6660:     my $itemcount = 1;
 6661:     if ($position eq 'top') {
 6662:         if (keys(%serverhomes) > 1) {
 6663:             my %spareid = &current_offloads_to($dom,$settings,\%servers);
 6664:             my ($curroffloadnow,$curroffloadoth);
 6665:             if (ref($settings) eq 'HASH') {
 6666:                 if (ref($settings->{'offloadnow'}) eq 'HASH') {
 6667:                     $curroffloadnow = $settings->{'offloadnow'};
 6668:                 }
 6669:                 if (ref($settings->{'offloadoth'}) eq 'HASH') {
 6670:                     $curroffloadoth = $settings->{'offloadoth'};
 6671:                 }
 6672:             }
 6673:             my $other_insts = scalar(keys(%by_location));
 6674:             $datatable .= &spares_row($dom,\%servers,\%spareid,\%serverhomes,\%altids,
 6675:                                       $other_insts,$curroffloadnow,$curroffloadoth,$rowtotal);
 6676:         } else {
 6677:             $datatable .= '<tr'.$css_class.'><td colspan="2">'.
 6678:                           &mt('Nothing to set here, as the cluster to which this domain belongs only contains one server.');
 6679:         }
 6680:     } else {
 6681:         if (keys(%by_location) == 0) {
 6682:             $datatable .= '<tr'.$css_class.'><td colspan="2">'.
 6683:                           &mt('Nothing to set here, as the cluster to which this domain belongs only contains one institution.');
 6684:         } else {
 6685:             my %lt = &usersession_titles();
 6686:             my $numinrow = 5;
 6687:             my $prefix;
 6688:             my @types;
 6689:             if ($position eq 'bottom') {
 6690:                 $prefix = 'remote';
 6691:                 @types = ('version','excludedomain','includedomain');
 6692:             } else {
 6693:                 $prefix = 'hosted';
 6694:                 @types = ('excludedomain','includedomain');
 6695:             }
 6696:             my (%current,%checkedon,%checkedoff);
 6697:             my @lcversions = &Apache::lonnet::all_loncaparevs();
 6698:             my @locations = sort(keys(%by_location));
 6699:             foreach my $type (@types) {
 6700:                 $checkedon{$type} = '';
 6701:                 $checkedoff{$type} = ' checked="checked"';
 6702:             }
 6703:             if (ref($settings) eq 'HASH') {
 6704:                 if (ref($settings->{$prefix}) eq 'HASH') {
 6705:                     foreach my $key (keys(%{$settings->{$prefix}})) {
 6706:                         $current{$key} = $settings->{$prefix}{$key};
 6707:                         if ($key eq 'version') {
 6708:                             if ($current{$key} ne '') {
 6709:                                 $checkedon{$key} = ' checked="checked"';
 6710:                                 $checkedoff{$key} = '';
 6711:                             }
 6712:                         } elsif (ref($current{$key}) eq 'ARRAY') {
 6713:                             $checkedon{$key} = ' checked="checked"';
 6714:                             $checkedoff{$key} = '';
 6715:                         }
 6716:                     }
 6717:                 }
 6718:             }
 6719:             foreach my $type (@types) {
 6720:                 next if ($type ne 'version' && !@locations);
 6721:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6722:                 $datatable .= '<tr'.$css_class.'>
 6723:                                <td><span class="LC_nobreak">'.$lt{$type}.'</span><br />
 6724:                                <span class="LC_nobreak">&nbsp;
 6725:                                <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedoff{$type}.' value="0" />'.&mt('Not in use').'</label>&nbsp;
 6726:                                <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedon{$type}.' value="1" />'.&mt('In use').'</label></span></td><td>';
 6727:                 if ($type eq 'version') {
 6728:                     my $selector = '<select name="'.$prefix.'_version">';
 6729:                     foreach my $version (@lcversions) {
 6730:                         my $selected = '';
 6731:                         if ($current{'version'} eq $version) {
 6732:                             $selected = ' selected="selected"';
 6733:                         }
 6734:                         $selector .= ' <option value="'.$version.'"'.
 6735:                                      $selected.'>'.$version.'</option>';
 6736:                     }
 6737:                     $selector .= '</select> ';
 6738:                     $datatable .= &mt('remote server must be version: [_1] or later',$selector);
 6739:                 } else {
 6740:                     $datatable.= '<div><input type="button" value="'.&mt('check all').'" '.
 6741:                                  'onclick="javascript:checkAll(document.display.'.$prefix.'_'.$type.')"'.
 6742:                                  ' />'.('&nbsp;'x2).
 6743:                                  '<input type="button" value="'.&mt('uncheck all').'" '.
 6744:                                  'onclick="javascript:uncheckAll(document.display.'.$prefix.'_'.$type.')" />'.
 6745:                                  "\n".
 6746:                                  '</div><div><table>';
 6747:                     my $rem;
 6748:                     for (my $i=0; $i<@locations; $i++) {
 6749:                         my ($showloc,$value,$checkedtype);
 6750:                         if (ref($by_location{$locations[$i]}) eq 'ARRAY') {
 6751:                             my $ip = $by_location{$locations[$i]}->[0];
 6752:                             if (ref($by_ip{$ip}) eq 'ARRAY') {
 6753:                                  $value = join(':',@{$by_ip{$ip}});
 6754:                                 $showloc = join(', ',@{$by_ip{$ip}});
 6755:                                 if (ref($current{$type}) eq 'ARRAY') {
 6756:                                     foreach my $loc (@{$by_ip{$ip}}) {  
 6757:                                         if (grep(/^\Q$loc\E$/,@{$current{$type}})) {
 6758:                                             $checkedtype = ' checked="checked"';
 6759:                                             last;
 6760:                                         }
 6761:                                     }
 6762:                                 }
 6763:                             }
 6764:                         }
 6765:                         $rem = $i%($numinrow);
 6766:                         if ($rem == 0) {
 6767:                             if ($i > 0) {
 6768:                                 $datatable .= '</tr>';
 6769:                             }
 6770:                             $datatable .= '<tr>';
 6771:                         }
 6772:                         $datatable .= '<td class="LC_left_item">'.
 6773:                                       '<span class="LC_nobreak"><label>'.
 6774:                                       '<input type="checkbox" name="'.$prefix.'_'.$type.
 6775:                                       '" value="'.$value.'"'.$checkedtype.' />'.$showloc.
 6776:                                       '</label></span></td>';
 6777:                     }
 6778:                     $rem = @locations%($numinrow);
 6779:                     my $colsleft = $numinrow - $rem;
 6780:                     if ($colsleft > 1 ) {
 6781:                         $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 6782:                                       '&nbsp;</td>';
 6783:                     } elsif ($colsleft == 1) {
 6784:                         $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 6785:                     }
 6786:                     $datatable .= '</tr></table>';
 6787:                 }
 6788:                 $datatable .= '</td></tr>';
 6789:                 $itemcount ++;
 6790:             }
 6791:         }
 6792:     }
 6793:     $$rowtotal += $itemcount;
 6794:     return $datatable;
 6795: }
 6796: 
 6797: sub build_location_hashes {
 6798:     my ($intdoms,$by_ip,$by_location) = @_;
 6799:     return unless((ref($intdoms) eq 'ARRAY') && (ref($by_ip) eq 'HASH') &&
 6800:                   (ref($by_location) eq 'HASH')); 
 6801:     my %iphost = &Apache::lonnet::get_iphost();
 6802:     my $primary_id = &Apache::lonnet::domain($env{'request.role.domain'},'primary');
 6803:     my $primary_ip = &Apache::lonnet::get_host_ip($primary_id);
 6804:     if (ref($iphost{$primary_ip}) eq 'ARRAY') {
 6805:         foreach my $id (@{$iphost{$primary_ip}}) {
 6806:             my $intdom = &Apache::lonnet::internet_dom($id);
 6807:             unless(grep(/^\Q$intdom\E$/,@{$intdoms})) {
 6808:                 push(@{$intdoms},$intdom);
 6809:             }
 6810:         }
 6811:     }
 6812:     foreach my $ip (keys(%iphost)) {
 6813:         if (ref($iphost{$ip}) eq 'ARRAY') {
 6814:             foreach my $id (@{$iphost{$ip}}) {
 6815:                 my $location = &Apache::lonnet::internet_dom($id);
 6816:                 if ($location) {
 6817:                     next if (grep(/^\Q$location\E$/,@{$intdoms}));
 6818:                     if (ref($by_ip->{$ip}) eq 'ARRAY') {
 6819:                         unless(grep(/^\Q$location\E$/,@{$by_ip->{$ip}})) {
 6820:                             push(@{$by_ip->{$ip}},$location);
 6821:                         }
 6822:                     } else {
 6823:                         $by_ip->{$ip} = [$location];
 6824:                     }
 6825:                 }
 6826:             }
 6827:         }
 6828:     }
 6829:     foreach my $ip (sort(keys(%{$by_ip}))) {
 6830:         if (ref($by_ip->{$ip}) eq 'ARRAY') {
 6831:             @{$by_ip->{$ip}} = sort(@{$by_ip->{$ip}});
 6832:             my $first = $by_ip->{$ip}->[0];
 6833:             if (ref($by_location->{$first}) eq 'ARRAY') {
 6834:                 unless (grep(/^\Q$ip\E$/,@{$by_location->{$first}})) {
 6835:                     push(@{$by_location->{$first}},$ip);
 6836:                 }
 6837:             } else {
 6838:                 $by_location->{$first} = [$ip];
 6839:             }
 6840:         }
 6841:     }
 6842:     return;
 6843: }
 6844: 
 6845: sub current_offloads_to {
 6846:     my ($dom,$settings,$servers) = @_;
 6847:     my (%spareid,%otherdomconfigs);
 6848:     if (ref($servers) eq 'HASH') {
 6849:         foreach my $lonhost (sort(keys(%{$servers}))) {
 6850:             my $gotspares;
 6851:             if (ref($settings) eq 'HASH') {
 6852:                 if (ref($settings->{'spares'}) eq 'HASH') {
 6853:                     if (ref($settings->{'spares'}{$lonhost}) eq 'HASH') {
 6854:                         $spareid{$lonhost}{'primary'} = $settings->{'spares'}{$lonhost}{'primary'};
 6855:                         $spareid{$lonhost}{'default'} = $settings->{'spares'}{$lonhost}{'default'};
 6856:                         $gotspares = 1;
 6857:                     }
 6858:                 }
 6859:             }
 6860:             unless ($gotspares) {
 6861:                 my $gotspares;
 6862:                 my $serverhomeID =
 6863:                     &Apache::lonnet::get_server_homeID($servers->{$lonhost});
 6864:                 my $serverhomedom =
 6865:                     &Apache::lonnet::host_domain($serverhomeID);
 6866:                 if ($serverhomedom ne $dom) {
 6867:                     if (ref($otherdomconfigs{$serverhomedom} eq 'HASH')) {
 6868:                         if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 6869:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 6870:                                 $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 6871:                                 $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 6872:                                 $gotspares = 1;
 6873:                             }
 6874:                         }
 6875:                     } else {
 6876:                         $otherdomconfigs{$serverhomedom} =
 6877:                             &Apache::lonnet::get_dom('configuration',['usersessions'],$serverhomedom);
 6878:                         if (ref($otherdomconfigs{$serverhomedom}) eq 'HASH') {
 6879:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 6880:                                 if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 6881:                                     if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{$lonhost}) eq 'HASH') {
 6882:                                         $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 6883:                                         $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 6884:                                         $gotspares = 1;
 6885:                                     }
 6886:                                 }
 6887:                             }
 6888:                         }
 6889:                     }
 6890:                 }
 6891:             }
 6892:             unless ($gotspares) {
 6893:                 if ($lonhost eq $Apache::lonnet::perlvar{'lonHostID'}) {
 6894:                     $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 6895:                     $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 6896:                } else {
 6897:                     my $server_hostname = &Apache::lonnet::hostname($lonhost);
 6898:                     my $server_homeID = &Apache::lonnet::get_server_homeID($server_hostname);
 6899:                     if ($server_homeID eq $Apache::lonnet::perlvar{'lonHostID'}) {
 6900:                         $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 6901:                         $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 6902:                     } else {
 6903:                         my %what = (
 6904:                              spareid => 1,
 6905:                         );
 6906:                         my ($result,$returnhash) = 
 6907:                             &Apache::lonnet::get_remote_globals($lonhost,\%what);
 6908:                         if ($result eq 'ok') { 
 6909:                             if (ref($returnhash) eq 'HASH') {
 6910:                                 if (ref($returnhash->{'spareid'}) eq 'HASH') {
 6911:                                     $spareid{$lonhost}{'primary'} = $returnhash->{'spareid'}->{'primary'};
 6912:                                     $spareid{$lonhost}{'default'} = $returnhash->{'spareid'}->{'default'};
 6913:                                 }
 6914:                             }
 6915:                         }
 6916:                     }
 6917:                 }
 6918:             }
 6919:         }
 6920:     }
 6921:     return %spareid;
 6922: }
 6923: 
 6924: sub spares_row {
 6925:     my ($dom,$servers,$spareid,$serverhomes,$altids,$other_insts,
 6926:         $curroffloadnow,$curroffloadoth,$rowtotal) = @_;
 6927:     my $css_class;
 6928:     my $numinrow = 4;
 6929:     my $itemcount = 1;
 6930:     my $datatable;
 6931:     my %typetitles = &sparestype_titles();
 6932:     if ((ref($servers) eq 'HASH') && (ref($spareid) eq 'HASH') && (ref($altids) eq 'HASH')) {
 6933:         foreach my $server (sort(keys(%{$servers}))) {
 6934:             my $serverhome = &Apache::lonnet::get_server_homeID($servers->{$server});
 6935:             my ($othercontrol,$serverdom);
 6936:             if ($serverhome ne $server) {
 6937:                 $serverdom = &Apache::lonnet::host_domain($serverhome);
 6938:                 $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 6939:             } else {
 6940:                 $serverdom = &Apache::lonnet::host_domain($server);
 6941:                 if ($serverdom ne $dom) {
 6942:                     $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 6943:                 }
 6944:             }
 6945:             next unless (ref($spareid->{$server}) eq 'HASH');
 6946:             my ($checkednow,$checkedoth);
 6947:             if (ref($curroffloadnow) eq 'HASH') {
 6948:                 if ($curroffloadnow->{$server}) {
 6949:                     $checkednow = ' checked="checked"';
 6950:                 }
 6951:             }
 6952:             if (ref($curroffloadoth) eq 'HASH') {
 6953:                 if ($curroffloadoth->{$server}) {
 6954:                     $checkedoth = ' checked="checked"';
 6955:                 }
 6956:             }
 6957:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6958:             $datatable .= '<tr'.$css_class.'>
 6959:                            <td rowspan="2">
 6960:                             <span class="LC_nobreak">'.
 6961:                           &mt('[_1] when busy, offloads to:'
 6962:                               ,'<b>'.$server.'</b>').'</span><br />'.
 6963:                           '<span class="LC_nobreak">'."\n".
 6964:                           '<label><input type="checkbox" name="offloadnow" value="'.$server.'"'.$checkednow.' />'.
 6965:                           '&nbsp;'.&mt('Switch any active user on next access').'</label></span>'.
 6966:                           "\n";
 6967:             if ($other_insts) {
 6968:                 $datatable .= '<br />'.
 6969:                               '<span class="LC_nobreak">'."\n".
 6970:                           '<label><input type="checkbox" name="offloadoth" value="'.$server.'"'.$checkedoth.' />'.
 6971:                           '&nbsp;'.&mt('Switch other institutions on next access').'</label></span>'.
 6972:                           "\n";
 6973:             }
 6974:             my (%current,%canselect);
 6975:             my @choices = 
 6976:                 &possible_newspares($server,$spareid->{$server},$serverhomes,$altids);
 6977:             foreach my $type ('primary','default') {
 6978:                 if (ref($spareid->{$server}) eq 'HASH') {
 6979:                     if (ref($spareid->{$server}{$type}) eq 'ARRAY') {
 6980:                         my @spares = @{$spareid->{$server}{$type}};
 6981:                         if (@spares > 0) {
 6982:                             if ($othercontrol) {
 6983:                                 $current{$type} = join(', ',@spares);
 6984:                             } else {
 6985:                                 $current{$type} .= '<table>';
 6986:                                 my $numspares = scalar(@spares);
 6987:                                 for (my $i=0;  $i<@spares; $i++) {
 6988:                                     my $rem = $i%($numinrow);
 6989:                                     if ($rem == 0) {
 6990:                                         if ($i > 0) {
 6991:                                             $current{$type} .= '</tr>';
 6992:                                         }
 6993:                                         $current{$type} .= '<tr>';
 6994:                                     }
 6995:                                     $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;'.
 6996:                                                        $spareid->{$server}{$type}[$i].
 6997:                                                        '</label></td>'."\n";
 6998:                                 }
 6999:                                 my $rem = @spares%($numinrow);
 7000:                                 my $colsleft = $numinrow - $rem;
 7001:                                 if ($colsleft > 1 ) {
 7002:                                     $current{$type} .= '<td colspan="'.$colsleft.
 7003:                                                        '" class="LC_left_item">'.
 7004:                                                        '&nbsp;</td>';
 7005:                                 } elsif ($colsleft == 1) {
 7006:                                     $current{$type} .= '<td class="LC_left_item">&nbsp;</td>'."\n";
 7007:                                 }
 7008:                                 $current{$type} .= '</tr></table>';
 7009:                             }
 7010:                         }
 7011:                     }
 7012:                     if ($current{$type} eq '') {
 7013:                         $current{$type} = &mt('None specified');
 7014:                     }
 7015:                     if ($othercontrol) {
 7016:                         if ($type eq 'primary') {
 7017:                             $canselect{$type} = $othercontrol;
 7018:                         }
 7019:                     } else {
 7020:                         $canselect{$type} = 
 7021:                             &mt('Add new [_1]'.$type.'[_2]:','<i>','</i>').'&nbsp;'.
 7022:                             '<select name="newspare_'.$type.'_'.$server.'" '.
 7023:                             'id="newspare_'.$type.'_'.$server.'" onchange="checkNewSpares('."'$server','$type'".');">'."\n".
 7024:                             '<option value="" selected ="selected">'.&mt('Select').'</option>'."\n";
 7025:                         if (@choices > 0) {
 7026:                             foreach my $lonhost (@choices) {
 7027:                                 $canselect{$type} .= '<option value="'.$lonhost.'">'.$lonhost.'</option>'."\n";
 7028:                             }
 7029:                         }
 7030:                         $canselect{$type} .= '</select>'."\n";
 7031:                     }
 7032:                 } else {
 7033:                     $current{$type} = &mt('Could not be determined');
 7034:                     if ($type eq 'primary') {
 7035:                         $canselect{$type} =  $othercontrol;
 7036:                     }
 7037:                 }
 7038:                 if ($type eq 'default') {
 7039:                     $datatable .= '<tr'.$css_class.'>';
 7040:                 }
 7041:                 $datatable .= '<td><i>'.$typetitles{$type}.'</i></td>'."\n".
 7042:                               '<td>'.$current{$type}.'</td>'."\n".
 7043:                               '<td>'.$canselect{$type}.'</td></tr>'."\n";
 7044:             }
 7045:             $itemcount ++;
 7046:         }
 7047:     }
 7048:     $$rowtotal += $itemcount;
 7049:     return $datatable;
 7050: }
 7051: 
 7052: sub possible_newspares {
 7053:     my ($server,$currspares,$serverhomes,$altids) = @_;
 7054:     my $serverhostname = &Apache::lonnet::hostname($server);
 7055:     my %excluded;
 7056:     if ($serverhostname ne '') {
 7057:         %excluded = (
 7058:                        $serverhostname => 1,
 7059:                     );
 7060:     }
 7061:     if (ref($currspares) eq 'HASH') {
 7062:         foreach my $type (keys(%{$currspares})) {
 7063:             if (ref($currspares->{$type}) eq 'ARRAY') {
 7064:                 if (@{$currspares->{$type}} > 0) {
 7065:                     foreach my $curr (@{$currspares->{$type}}) {
 7066:                         my $hostname = &Apache::lonnet::hostname($curr);
 7067:                         $excluded{$hostname} = 1;
 7068:                     }
 7069:                 }
 7070:             }
 7071:         }
 7072:     }
 7073:     my @choices;
 7074:     if ((ref($serverhomes) eq 'HASH') && (ref($altids) eq 'HASH')) {
 7075:         if (keys(%{$serverhomes}) > 1) {
 7076:             foreach my $name (sort(keys(%{$serverhomes}))) {
 7077:                 unless ($excluded{$name}) {
 7078:                     if (exists($altids->{$serverhomes->{$name}})) {
 7079:                         push(@choices,$altids->{$serverhomes->{$name}});
 7080:                     } else {
 7081:                         push(@choices,$serverhomes->{$name});
 7082:                     }
 7083:                 }
 7084:             }
 7085:         }
 7086:     }
 7087:     return sort(@choices);
 7088: }
 7089: 
 7090: sub print_loadbalancing {
 7091:     my ($dom,$settings,$rowtotal) = @_;
 7092:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
 7093:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
 7094:     my $numinrow = 1;
 7095:     my $datatable;
 7096:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 7097:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
 7098:     if (ref($settings) eq 'HASH') {
 7099:         %existing = %{$settings};
 7100:     }
 7101:     if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
 7102:         &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
 7103:                                   \%currtargets,\%currrules,\%currcookies);
 7104:     } else {
 7105:         return;
 7106:     }
 7107:     my ($othertitle,$usertypes,$types) =
 7108:         &Apache::loncommon::sorted_inst_types($dom);
 7109:     my $rownum = 8;
 7110:     if (ref($types) eq 'ARRAY') {
 7111:         $rownum += scalar(@{$types});
 7112:     }
 7113:     my @css_class = ('LC_odd_row','LC_even_row');
 7114:     my $balnum = 0;
 7115:     my $islast;
 7116:     my (@toshow,$disabledtext);
 7117:     if (keys(%currbalancer) > 0) {
 7118:         @toshow = sort(keys(%currbalancer));
 7119:         if (scalar(@toshow) < scalar(keys(%servers)) + 1) {
 7120:             push(@toshow,'');
 7121:         }
 7122:     } else {
 7123:         @toshow = ('');
 7124:         $disabledtext = &mt('No existing load balancer');
 7125:     }
 7126:     foreach my $lonhost (@toshow) {
 7127:         if ($balnum == scalar(@toshow)-1) {
 7128:             $islast = 1;
 7129:         } else {
 7130:             $islast = 0;
 7131:         }
 7132:         my $cssidx = $balnum%2;
 7133:         my $targets_div_style = 'display: none';
 7134:         my $disabled_div_style = 'display: block';
 7135:         my $homedom_div_style = 'display: none';
 7136:         $datatable .= '<tr class="'.$css_class[$cssidx].'">'.
 7137:                       '<td rowspan="'.$rownum.'" valign="top">'.
 7138:                       '<p>';
 7139:         if ($lonhost eq '') {
 7140:             $datatable .= '<span class="LC_nobreak">';
 7141:             if (keys(%currbalancer) > 0) {
 7142:                 $datatable .= &mt('Add balancer:');
 7143:             } else {
 7144:                 $datatable .= &mt('Enable balancer:');
 7145:             }
 7146:             $datatable .= '&nbsp;'.
 7147:                           '<select name="loadbalancing_lonhost_'.$balnum.'"'.
 7148:                           ' id="loadbalancing_lonhost_'.$balnum.'"'.
 7149:                           ' onchange="toggleTargets('."'$balnum'".');">'."\n".
 7150:                           '<option value="" selected="selected">'.&mt('None').
 7151:                           '</option>'."\n";
 7152:             foreach my $server (sort(keys(%servers))) {
 7153:                 next if ($currbalancer{$server});
 7154:                 $datatable .= '<option value="'.$server.'">'.$server.'</option>'."\n";
 7155:             }
 7156:             $datatable .=
 7157:                 '</select>'."\n".
 7158:                 '<input type="hidden" name="loadbalancing_prevlonhost_'.$balnum.'" id="loadbalancing_prevlonhost_'.$balnum.'" value="" />&nbsp;</span>'."\n";
 7159:         } else {
 7160:             $datatable .= '<i>'.$lonhost.'</i><br /><span class="LC_nobreak">'.
 7161:                           '<label><input type="checkbox" name="loadbalancing_delete" value="'.$balnum.'" id="loadbalancing_delete_'.$balnum.'" onclick="javascript:balancerDeleteChange('."'$balnum'".');" />&nbsp;'.
 7162:                            &mt('Stop balancing').'</label>'.
 7163:                            '<input type="hidden" name="loadbalancing_lonhost_'.$balnum.'" value="'.$lonhost.'" id="loadbalancing_lonhost_'.$balnum.'" /></span>';
 7164:             $targets_div_style = 'display: block';
 7165:             $disabled_div_style = 'display: none';
 7166:             if ($dom eq &Apache::lonnet::host_domain($lonhost)) {
 7167:                 $homedom_div_style = 'display: block';
 7168:             }
 7169:         }
 7170:         $datatable .= '</p></td><td rowspan="'.$rownum.'" valign="top">'.
 7171:                   '<div id="loadbalancing_disabled_'.$balnum.'" style="'.
 7172:                   $disabled_div_style.'">'.$disabledtext.'</div>'."\n".
 7173:                   '<div id="loadbalancing_targets_'.$balnum.'" style="'.$targets_div_style.'">'.&mt('Offloads to:').'<br />';
 7174:         my ($numspares,@spares) = &count_servers($lonhost,%servers);
 7175:         my @sparestypes = ('primary','default');
 7176:         my %typetitles = &sparestype_titles();
 7177:         my %hostherechecked = (
 7178:                                   no => ' checked="checked"',
 7179:                               );
 7180:         my %balcookiechecked = (
 7181:                                   no => ' checked="checked"',
 7182:                                );
 7183:         foreach my $sparetype (@sparestypes) {
 7184:             my $targettable;
 7185:             for (my $i=0; $i<$numspares; $i++) {
 7186:                 my $checked;
 7187:                 if (ref($currtargets{$lonhost}) eq 'HASH') {
 7188:                     if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 7189:                         if (grep(/^\Q$spares[$i]\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 7190:                             $checked = ' checked="checked"';
 7191:                         }
 7192:                     }
 7193:                 }
 7194:                 my ($chkboxval,$disabled);
 7195:                 if (($lonhost ne '') && (exists($servers{$lonhost}))) {
 7196:                     $chkboxval = $spares[$i];
 7197:                 }
 7198:                 if (exists($currbalancer{$spares[$i]})) {
 7199:                     $disabled = ' disabled="disabled"';
 7200:                 }
 7201:                 $targettable .=
 7202:                     '<td><span class="LC_nobreak"><label>'.
 7203:                     '<input type="checkbox" name="loadbalancing_target_'.$balnum.'_'.$sparetype.'"'.
 7204:                     $checked.$disabled.' value="'.$chkboxval.'" id="loadbalancing_target_'.$balnum.'_'.$sparetype.'_'.$i.'" onclick="checkOffloads('."this,'$balnum','$sparetype'".');" /><span id="loadbalancing_targettxt_'.$balnum.'_'.$sparetype.'_'.$i.'">&nbsp;'.$chkboxval.
 7205:                     '</span></label></span></td>';
 7206:                 my $rem = $i%($numinrow);
 7207:                 if ($rem == 0) {
 7208:                     if (($i > 0) && ($i < $numspares-1)) {
 7209:                         $targettable .= '</tr>';
 7210:                     }
 7211:                     if ($i < $numspares-1) {
 7212:                         $targettable .= '<tr>';
 7213:                     }
 7214:                 }
 7215:             }
 7216:             if ($targettable ne '') {
 7217:                 my $rem = $numspares%($numinrow);
 7218:                 my $colsleft = $numinrow - $rem;
 7219:                 if ($colsleft > 1 ) {
 7220:                     $targettable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 7221:                                     '&nbsp;</td>';
 7222:                 } elsif ($colsleft == 1) {
 7223:                     $targettable .= '<td class="LC_left_item">&nbsp;</td>';
 7224:                 }
 7225:                 $datatable .=  '<i>'.$typetitles{$sparetype}.'</i><br />'.
 7226:                                '<table><tr>'.$targettable.'</tr></table><br />';
 7227:             }
 7228:             $hostherechecked{$sparetype} = '';
 7229:             if (ref($currtargets{$lonhost}) eq 'HASH') {
 7230:                 if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 7231:                     if (grep(/^\Q$lonhost\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 7232:                         $hostherechecked{$sparetype} = ' checked="checked"';
 7233:                         $hostherechecked{'no'} = '';
 7234:                     }
 7235:                 }
 7236:             }
 7237:         }
 7238:         if ($currcookies{$lonhost}) {
 7239:             %balcookiechecked = (
 7240:                                     yes => ' checked="checked"',
 7241:                                 );
 7242:         }
 7243:         $datatable .= &mt('Hosting on balancer itself').'<br />'.
 7244:                       '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" value="no"'.
 7245:                       $hostherechecked{'no'}.' />'.&mt('No').'</label><br />';
 7246:         foreach my $sparetype (@sparestypes) {
 7247:             $datatable .= '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" '.
 7248:                           'value="'.$sparetype.'"'.$hostherechecked{$sparetype}.' /><i>'.$typetitles{$sparetype}.
 7249:                           '</i></label><br />';
 7250:         }
 7251:         $datatable .= &mt('Use balancer cookie').'<br />'.
 7252:                       '<label><input type="radio" name="loadbalancing_cookie_'.$balnum.'" value="1"'.
 7253:                       $balcookiechecked{'yes'}.' />'.&mt('Yes').'</label><br />'.
 7254:                       '<label><input type="radio" name="loadbalancing_cookie_'.$balnum.'" value="0"'.
 7255:                       $balcookiechecked{'no'}.' />'.&mt('No').'</label><br />'.
 7256:                       '</div></td></tr>'.
 7257:                       &loadbalancing_rules($dom,$intdom,$currrules{$lonhost},
 7258:                                            $othertitle,$usertypes,$types,\%servers,
 7259:                                            \%currbalancer,$lonhost,
 7260:                                            $targets_div_style,$homedom_div_style,
 7261:                                            $css_class[$cssidx],$balnum,$islast);
 7262:         $$rowtotal += $rownum;
 7263:         $balnum ++;
 7264:     }
 7265:     $datatable .= '<input type="hidden" name="loadbalancing_total" id="loadbalancing_total" value="'.$balnum.'" />';
 7266:     return $datatable;
 7267: }
 7268: 
 7269: sub get_loadbalancers_config {
 7270:     my ($servers,$existing,$currbalancer,$currtargets,$currrules,$currcookies) = @_;
 7271:     return unless ((ref($servers) eq 'HASH') &&
 7272:                    (ref($existing) eq 'HASH') && (ref($currbalancer) eq 'HASH') &&
 7273:                    (ref($currtargets) eq 'HASH') && (ref($currrules) eq 'HASH') &&
 7274:                    (ref($currcookies) eq 'HASH'));
 7275:     if (keys(%{$existing}) > 0) {
 7276:         my $oldlonhost;
 7277:         foreach my $key (sort(keys(%{$existing}))) {
 7278:             if ($key eq 'lonhost') {
 7279:                 $oldlonhost = $existing->{'lonhost'};
 7280:                 $currbalancer->{$oldlonhost} = 1;
 7281:             } elsif ($key eq 'targets') {
 7282:                 if ($oldlonhost) {
 7283:                     $currtargets->{$oldlonhost} = $existing->{'targets'};
 7284:                 }
 7285:             } elsif ($key eq 'rules') {
 7286:                 if ($oldlonhost) {
 7287:                     $currrules->{$oldlonhost} = $existing->{'rules'};
 7288:                 }
 7289:             } elsif (ref($existing->{$key}) eq 'HASH') {
 7290:                 $currbalancer->{$key} = 1;
 7291:                 $currtargets->{$key} = $existing->{$key}{'targets'};
 7292:                 $currrules->{$key} = $existing->{$key}{'rules'};
 7293:                 if ($existing->{$key}{'cookie'}) {
 7294:                     $currcookies->{$key} = 1;
 7295:                 }
 7296:             }
 7297:         }
 7298:     } else {
 7299:         my ($balancerref,$targetsref) =
 7300:                 &Apache::lonnet::get_lonbalancer_config($servers);
 7301:         if ((ref($balancerref) eq 'HASH') && (ref($targetsref) eq 'HASH')) {
 7302:             foreach my $server (sort(keys(%{$balancerref}))) {
 7303:                 $currbalancer->{$server} = 1;
 7304:                 $currtargets->{$server} = $targetsref->{$server};
 7305:             }
 7306:         }
 7307:     }
 7308:     return;
 7309: }
 7310: 
 7311: sub loadbalancing_rules {
 7312:     my ($dom,$intdom,$currrules,$othertitle,$usertypes,$types,$servers,
 7313:         $currbalancer,$lonhost,$targets_div_style,$homedom_div_style,
 7314:         $css_class,$balnum,$islast) = @_;
 7315:     my $output;
 7316:     my $num = 0;
 7317:     my ($alltypes,$othertypes,$titles) =
 7318:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
 7319:     if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH'))  {
 7320:         foreach my $type (@{$alltypes}) {
 7321:             $num ++;
 7322:             my $current;
 7323:             if (ref($currrules) eq 'HASH') {
 7324:                 $current = $currrules->{$type};
 7325:             }
 7326:             if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 7327:                 if ($dom ne &Apache::lonnet::host_domain($lonhost)) {
 7328:                     $current = '';
 7329:                 }
 7330:             }
 7331:             $output .= &loadbalance_rule_row($type,$titles->{$type},$current,
 7332:                                              $servers,$currbalancer,$lonhost,$dom,
 7333:                                              $targets_div_style,$homedom_div_style,
 7334:                                              $css_class,$balnum,$num,$islast);
 7335:         }
 7336:     }
 7337:     return $output;
 7338: }
 7339: 
 7340: sub loadbalancing_titles {
 7341:     my ($dom,$intdom,$usertypes,$types) = @_;
 7342:     my %othertypes = (
 7343:            '_LC_adv'         => &mt('Advanced users from [_1]',$dom),
 7344:            '_LC_author'      => &mt('Users from [_1] with author role',$dom),
 7345:            '_LC_internetdom' => &mt('Users not from [_1], but from [_2]',$dom,$intdom),
 7346:            '_LC_external'    => &mt('Users not from [_1]',$intdom),
 7347:            '_LC_ipchangesso' => &mt('SSO users from [_1], with IP mismatch',$dom),
 7348:            '_LC_ipchange'    => &mt('Non-SSO users with IP mismatch'),
 7349:                      );
 7350:     my @alltypes = ('_LC_adv','_LC_author','_LC_internetdom','_LC_external','_LC_ipchangesso','_LC_ipchange');
 7351:     my @available;
 7352:     if (ref($types) eq 'ARRAY') {
 7353:         @available = @{$types};
 7354:     }
 7355:     unless (grep(/^default$/,@available)) {
 7356:         push(@available,'default');
 7357:     }
 7358:     unshift(@alltypes,@available);
 7359:     my %titles;
 7360:     foreach my $type (@alltypes) {
 7361:         if ($type =~ /^_LC_/) {
 7362:             $titles{$type} = $othertypes{$type};
 7363:         } elsif ($type eq 'default') {
 7364:             $titles{$type} = &mt('All users from [_1]',$dom);
 7365:             if (ref($types) eq 'ARRAY') {
 7366:                 if (@{$types} > 0) {
 7367:                     $titles{$type} = &mt('Other users from [_1]',$dom);
 7368:                 }
 7369:             }
 7370:         } elsif (ref($usertypes) eq 'HASH') {
 7371:             $titles{$type} = $usertypes->{$type};
 7372:         }
 7373:     }
 7374:     return (\@alltypes,\%othertypes,\%titles);
 7375: }
 7376: 
 7377: sub loadbalance_rule_row {
 7378:     my ($type,$title,$current,$servers,$currbalancer,$lonhost,$dom,
 7379:         $targets_div_style,$homedom_div_style,$css_class,$balnum,$num,$islast) = @_;
 7380:     my @rulenames;
 7381:     my %ruletitles = &offloadtype_text();
 7382:     if (($type eq '_LC_ipchangesso') || ($type eq '_LC_ipchange')) {
 7383:         @rulenames = ('balancer','offloadedto','specific');
 7384:     } else {
 7385:         @rulenames = ('default','homeserver');
 7386:         if ($type eq '_LC_external') {
 7387:             push(@rulenames,'externalbalancer');
 7388:         } else {
 7389:             push(@rulenames,'specific');
 7390:         }
 7391:         push(@rulenames,'none');
 7392:     }
 7393:     my $style = $targets_div_style;
 7394:     if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 7395:         $style = $homedom_div_style;
 7396:     }
 7397:     my $space;
 7398:     if ($islast && $num == 1) {
 7399:         $space = '<div display="inline-block">&nbsp;</div>';
 7400:     }
 7401:     my $output =
 7402:         '<tr class="'.$css_class.'" id="balanceruletr_'.$balnum.'_'.$num.'"><td valign="top">'.$space.
 7403:         '<div id="balanceruletitle_'.$balnum.'_'.$type.'" style="'.$style.'">'.$title.'</div></td>'."\n".
 7404:         '<td valaign="top">'.$space.
 7405:         '<div id="balancerule_'.$balnum.'_'.$type.'" style="'.$style.'">'."\n";
 7406:     for (my $i=0; $i<@rulenames; $i++) {
 7407:         my $rule = $rulenames[$i];
 7408:         my ($checked,$extra);
 7409:         if ($rulenames[$i] eq 'default') {
 7410:             $rule = '';
 7411:         }
 7412:         if ($rulenames[$i] eq 'specific') {
 7413:             if (ref($servers) eq 'HASH') {
 7414:                 my $default;
 7415:                 if (($current ne '') && (exists($servers->{$current}))) {
 7416:                     $checked = ' checked="checked"';
 7417:                 }
 7418:                 unless ($checked) {
 7419:                     $default = ' selected="selected"';
 7420:                 }
 7421:                 $extra =
 7422:                     ':&nbsp;<select name="loadbalancing_singleserver_'.$balnum.'_'.$type.
 7423:                     '" id="loadbalancing_singleserver_'.$balnum.'_'.$type.
 7424:                     '" onchange="singleServerToggle('."'$balnum','$type'".')">'."\n".
 7425:                     '<option value=""'.$default.'></option>'."\n";
 7426:                 foreach my $server (sort(keys(%{$servers}))) {
 7427:                     if (ref($currbalancer) eq 'HASH') {
 7428:                         next if (exists($currbalancer->{$server}));
 7429:                     }
 7430:                     my $selected;
 7431:                     if ($server eq $current) {
 7432:                         $selected = ' selected="selected"';
 7433:                     }
 7434:                     $extra .= '<option value="'.$server.'"'.$selected.'>'.$server.'</option>';
 7435:                 }
 7436:                 $extra .= '</select>';
 7437:             }
 7438:         } elsif ($rule eq $current) {
 7439:             $checked = ' checked="checked"';
 7440:         }
 7441:         $output .= '<span class="LC_nobreak"><label>'.
 7442:                    '<input type="radio" name="loadbalancing_rules_'.$balnum.'_'.$type.
 7443:                    '" id="loadbalancing_rules_'.$balnum.'_'.$type.'_'.$i.'" value="'.
 7444:                    $rule.'" onclick="balanceruleChange('."this.form,'$balnum','$type'".
 7445:                    ')"'.$checked.' />&nbsp;';
 7446:         if (($rulenames[$i] eq 'specific') && ($type =~ /^_LC_ipchange/)) {
 7447:             $output .= $ruletitles{'particular'};
 7448:         } else {
 7449:             $output .= $ruletitles{$rulenames[$i]};
 7450:         }
 7451:         $output .= '</label>'.$extra.'</span><br />'."\n";
 7452:     }
 7453:     $output .= '</div></td></tr>'."\n";
 7454:     return $output;
 7455: }
 7456: 
 7457: sub offloadtype_text {
 7458:     my %ruletitles = &Apache::lonlocal::texthash (
 7459:            'default'          => 'Offloads to default destinations',
 7460:            'homeserver'       => "Offloads to user's home server",
 7461:            'externalbalancer' => "Offloads to Load Balancer in user's domain",
 7462:            'specific'         => 'Offloads to specific server',
 7463:            'none'             => 'No offload',
 7464:            'balancer'         => 'Session hosted on Load Balancer, after re-authentication',
 7465:            'offloadedto'      => 'Session hosted on offload server, after re-authentication',
 7466:            'particular'       => 'Session hosted (after re-auth) on server:',
 7467:     );
 7468:     return %ruletitles;
 7469: }
 7470: 
 7471: sub sparestype_titles {
 7472:     my %typestitles = &Apache::lonlocal::texthash (
 7473:                           'primary' => 'primary',
 7474:                           'default' => 'default',
 7475:                       );
 7476:     return %typestitles;
 7477: }
 7478: 
 7479: sub contact_titles {
 7480:     my %titles = &Apache::lonlocal::texthash (
 7481:                    'supportemail'    => 'Support E-mail address',
 7482:                    'adminemail'      => 'Default Server Admin E-mail address',
 7483:                    'errormail'       => 'Error reports to be e-mailed to',
 7484:                    'packagesmail'    => 'Package update alerts to be e-mailed to',
 7485:                    'helpdeskmail'    => "Helpdesk requests from all users in this domain",
 7486:                    'otherdomsmail'   => 'Helpdesk requests from users in other (unconfigured) domains',
 7487:                    'lonstatusmail'   => 'E-mail from nightly status check (warnings/errors)',
 7488:                    'requestsmail'    => 'E-mail from course requests requiring approval',
 7489:                    'updatesmail'     => 'E-mail from nightly check of LON-CAPA module integrity/updates',
 7490:                    'idconflictsmail' => 'E-mail from bi-nightly check for multiple users sharing same student/employee ID',
 7491:                    'hostipmail'      => 'E-mail from nightly check of hostname/IP network changes',
 7492:                    'errorthreshold'  => 'Error count threshold for status e-mail to admin(s)',
 7493:                    'errorsysmail'    => 'Error count threshold for e-mail to developer group',
 7494:                    'errorweights'    => 'Weights used to compute error count',
 7495:                    'errorexcluded'   => 'Servers with unsent updates excluded from count',
 7496:                  );
 7497:     my %short_titles = &Apache::lonlocal::texthash (
 7498:                            adminemail   => 'Admin E-mail address',
 7499:                            supportemail => 'Support E-mail',
 7500:                        );   
 7501:     return (\%titles,\%short_titles);
 7502: }
 7503: 
 7504: sub helpform_fields {
 7505:     my %titles =  &Apache::lonlocal::texthash (
 7506:                        'username'   => 'Name',
 7507:                        'user'       => 'Username/domain',
 7508:                        'phone'      => 'Phone',
 7509:                        'cc'         => 'Cc e-mail',
 7510:                        'course'     => 'Course Details',
 7511:                        'section'    => 'Sections',
 7512:                        'screenshot' => 'File upload',
 7513:     );
 7514:     my @fields = ('username','phone','user','course','section','cc','screenshot');
 7515:     my %possoptions = (
 7516:                         username     => ['yes','no','req'],
 7517:                         phone        => ['yes','no','req'],
 7518:                         user         => ['yes','no'],
 7519:                         cc           => ['yes','no'],
 7520:                         course       => ['yes','no'],
 7521:                         section      => ['yes','no'],
 7522:                         screenshot   => ['yes','no'],
 7523:                       );
 7524:     my %fieldoptions = &Apache::lonlocal::texthash (
 7525:                          'yes'  => 'Optional',
 7526:                          'req'  => 'Required',
 7527:                          'no'   => "Not shown",
 7528:     );
 7529:     return (\@fields,\%titles,\%fieldoptions,\%possoptions);
 7530: }
 7531: 
 7532: sub tool_titles {
 7533:     my %titles = &Apache::lonlocal::texthash (
 7534:                      aboutme    => 'Personal web page',
 7535:                      blog       => 'Blog',
 7536:                      webdav     => 'WebDAV',
 7537:                      portfolio  => 'Portfolio',
 7538:                      official   => 'Official courses (with institutional codes)',
 7539:                      unofficial => 'Unofficial courses',
 7540:                      community  => 'Communities',
 7541:                      textbook   => 'Textbook courses',
 7542:                  );
 7543:     return %titles;
 7544: }
 7545: 
 7546: sub courserequest_titles {
 7547:     my %titles = &Apache::lonlocal::texthash (
 7548:                                    official   => 'Official',
 7549:                                    unofficial => 'Unofficial',
 7550:                                    community  => 'Communities',
 7551:                                    textbook   => 'Textbook',
 7552:                                    norequest  => 'Not allowed',
 7553:                                    approval   => 'Approval by Dom. Coord.',
 7554:                                    validate   => 'With validation',
 7555:                                    autolimit  => 'Numerical limit',
 7556:                                    unlimited  => '(blank for unlimited)',
 7557:                  );
 7558:     return %titles;
 7559: }
 7560: 
 7561: sub authorrequest_titles {
 7562:     my %titles = &Apache::lonlocal::texthash (
 7563:                                    norequest  => 'Not allowed',
 7564:                                    approval   => 'Approval by Dom. Coord.',
 7565:                                    automatic  => 'Automatic approval',
 7566:                  );
 7567:     return %titles;
 7568: }
 7569: 
 7570: sub courserequest_conditions {
 7571:     my %conditions = &Apache::lonlocal::texthash (
 7572:        approval    => '(Processing of request subject to approval by Domain Coordinator).',
 7573:        validate   => '(Processing of request subject to institutional validation).',
 7574:                  );
 7575:     return %conditions;
 7576: }
 7577: 
 7578: 
 7579: sub print_usercreation {
 7580:     my ($position,$dom,$settings,$rowtotal) = @_;
 7581:     my $numinrow = 4;
 7582:     my $datatable;
 7583:     if ($position eq 'top') {
 7584:         $$rowtotal ++;
 7585:         my $rowcount = 0;
 7586:         my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($dom,'username');
 7587:         if (ref($rules) eq 'HASH') {
 7588:             if (keys(%{$rules}) > 0) {
 7589:                 $datatable .= &user_formats_row('username',$settings,$rules,
 7590:                                                 $ruleorder,$numinrow,$rowcount);
 7591:                 $$rowtotal ++;
 7592:                 $rowcount ++;
 7593:             }
 7594:         }
 7595:         my ($idrules,$idruleorder) = &Apache::lonnet::inst_userrules($dom,'id');
 7596:         if (ref($idrules) eq 'HASH') {
 7597:             if (keys(%{$idrules}) > 0) {
 7598:                 $datatable .= &user_formats_row('id',$settings,$idrules,
 7599:                                                 $idruleorder,$numinrow,$rowcount);
 7600:                 $$rowtotal ++;
 7601:                 $rowcount ++;
 7602:             }
 7603:         }
 7604:         if ($rowcount == 0) {
 7605:             $datatable .= '<tr><td colspan="2">'.&mt('No format rules have been defined for usernames or IDs in this domain.').'</td></tr>';  
 7606:             $$rowtotal ++;
 7607:             $rowcount ++;
 7608:         }
 7609:     } elsif ($position eq 'middle') {
 7610:         my @creators = ('author','course','requestcrs');
 7611:         my ($rules,$ruleorder) =
 7612:             &Apache::lonnet::inst_userrules($dom,'username');
 7613:         my %lt = &usercreation_types();
 7614:         my %checked;
 7615:         if (ref($settings) eq 'HASH') {
 7616:             if (ref($settings->{'cancreate'}) eq 'HASH') {
 7617:                 foreach my $item (@creators) {
 7618:                     $checked{$item} = $settings->{'cancreate'}{$item};
 7619:                 }
 7620:             } elsif (ref($settings->{'cancreate'}) eq 'ARRAY') {
 7621:                 foreach my $item (@creators) {
 7622:                     if (grep(/^\Q$item\E$/,@{$settings->{'cancreate'}})) {
 7623:                         $checked{$item} = 'none';
 7624:                     }
 7625:                 }
 7626:             }
 7627:         }
 7628:         my $rownum = 0;
 7629:         foreach my $item (@creators) {
 7630:             $rownum ++;
 7631:             if ($checked{$item} eq '') {
 7632:                 $checked{$item} = 'any';
 7633:             }
 7634:             my $css_class;
 7635:             if ($rownum%2) {
 7636:                 $css_class = '';
 7637:             } else {
 7638:                 $css_class = ' class="LC_odd_row" ';
 7639:             }
 7640:             $datatable .= '<tr'.$css_class.'>'.
 7641:                          '<td><span class="LC_nobreak">'.$lt{$item}.
 7642:                          '</span></td><td align="right">';
 7643:             my @options = ('any');
 7644:             if (ref($rules) eq 'HASH') {
 7645:                 if (keys(%{$rules}) > 0) {
 7646:                     push(@options,('official','unofficial'));
 7647:                 }
 7648:             }
 7649:             push(@options,'none');
 7650:             foreach my $option (@options) {
 7651:                 my $type = 'radio';
 7652:                 my $check = ' ';
 7653:                 if ($checked{$item} eq $option) {
 7654:                     $check = ' checked="checked" ';
 7655:                 } 
 7656:                 $datatable .= '<span class="LC_nobreak"><label>'.
 7657:                               '<input type="'.$type.'" name="can_createuser_'.
 7658:                               $item.'" value="'.$option.'"'.$check.'/>&nbsp;'.
 7659:                               $lt{$option}.'</label>&nbsp;&nbsp;</span>';
 7660:             }
 7661:             $datatable .= '</td></tr>';
 7662:         }
 7663:     } else {
 7664:         my @contexts = ('author','course','domain');
 7665:         my @authtypes = ('int','krb4','krb5','loc');
 7666:         my %checked;
 7667:         if (ref($settings) eq 'HASH') {
 7668:             if (ref($settings->{'authtypes'}) eq 'HASH') {
 7669:                 foreach my $item (@contexts) {
 7670:                     if (ref($settings->{'authtypes'}{$item}) eq 'HASH') {
 7671:                         foreach my $auth (@authtypes) {
 7672:                             if ($settings->{'authtypes'}{$item}{$auth}) {
 7673:                                 $checked{$item}{$auth} = ' checked="checked" ';
 7674:                             }
 7675:                         }
 7676:                     }
 7677:                 }
 7678:             }
 7679:         } else {
 7680:             foreach my $item (@contexts) {
 7681:                 foreach my $auth (@authtypes) {
 7682:                     $checked{$item}{$auth} = ' checked="checked" ';
 7683:                 }
 7684:             }
 7685:         }
 7686:         my %title = &context_names();
 7687:         my %authname = &authtype_names();
 7688:         my $rownum = 0;
 7689:         my $css_class; 
 7690:         foreach my $item (@contexts) {
 7691:             if ($rownum%2) {
 7692:                 $css_class = '';
 7693:             } else {
 7694:                 $css_class = ' class="LC_odd_row" ';
 7695:             }
 7696:             $datatable .=   '<tr'.$css_class.'>'.
 7697:                             '<td>'.$title{$item}.
 7698:                             '</td><td class="LC_left_item">'.
 7699:                             '<span class="LC_nobreak">';
 7700:             foreach my $auth (@authtypes) {
 7701:                 $datatable .= '<label>'. 
 7702:                               '<input type="checkbox" name="'.$item.'_auth" '.
 7703:                               $checked{$item}{$auth}.' value="'.$auth.'" />'.
 7704:                               $authname{$auth}.'</label>&nbsp;';
 7705:             }
 7706:             $datatable .= '</span></td></tr>';
 7707:             $rownum ++;
 7708:         }
 7709:         $$rowtotal += $rownum;
 7710:     }
 7711:     return $datatable;
 7712: }
 7713: 
 7714: sub print_selfcreation {
 7715:     my ($position,$dom,$settings,$rowtotal) = @_;
 7716:     my (@selfcreate,$createsettings,$processing,$emailoptions,$emailverified,
 7717:         $emaildomain,$datatable);
 7718:     if (ref($settings) eq 'HASH') {
 7719:         if (ref($settings->{'cancreate'}) eq 'HASH') {
 7720:             $createsettings = $settings->{'cancreate'};
 7721:             if (ref($createsettings) eq 'HASH') {
 7722:                 if (ref($createsettings->{'selfcreate'}) eq 'ARRAY') {
 7723:                     @selfcreate = @{$createsettings->{'selfcreate'}};
 7724:                 } elsif ($createsettings->{'selfcreate'} ne '') {
 7725:                     if ($settings->{'cancreate'}{'selfcreate'} eq 'any') {
 7726:                         @selfcreate = ('email','login','sso');
 7727:                     } elsif ($createsettings->{'selfcreate'} ne 'none') {
 7728:                         @selfcreate = ($createsettings->{'selfcreate'});
 7729:                     }
 7730:                 }
 7731:                 if (ref($createsettings->{'selfcreateprocessing'}) eq 'HASH') {
 7732:                     $processing = $createsettings->{'selfcreateprocessing'};
 7733:                 }
 7734:                 if (ref($createsettings->{'emailoptions'}) eq 'HASH') {
 7735:                     $emailoptions = $createsettings->{'emailoptions'};
 7736:                 }
 7737:                 if (ref($createsettings->{'emailverified'}) eq 'HASH') {
 7738:                     $emailverified = $createsettings->{'emailverified'};
 7739:                 }
 7740:                 if (ref($createsettings->{'emaildomain'}) eq 'HASH') {
 7741:                     $emaildomain = $createsettings->{'emaildomain'};
 7742:                 }
 7743:             }
 7744:         }
 7745:     }
 7746:     my %radiohash;
 7747:     my $numinrow = 4;
 7748:     map { $radiohash{'cancreate_'.$_} = 1; } @selfcreate;
 7749:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 7750:     if ($position eq 'top') {
 7751:         my %choices = &Apache::lonlocal::texthash (
 7752:                                                       cancreate_login      => 'Institutional Login',
 7753:                                                       cancreate_sso        => 'Institutional Single Sign On',
 7754:                                                   );
 7755:         my @toggles = sort(keys(%choices));
 7756:         my %defaultchecked = (
 7757:                                'cancreate_login' => 'off',
 7758:                                'cancreate_sso'   => 'off',
 7759:                              );
 7760:         my ($onclick,$itemcount);
 7761:         ($datatable,$itemcount) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 7762:                                                      \%choices,$itemcount,$onclick);
 7763:         $$rowtotal += $itemcount;
 7764: 
 7765:         if (ref($usertypes) eq 'HASH') {
 7766:             if (keys(%{$usertypes}) > 0) {
 7767:                 $datatable .= &insttypes_row($createsettings,$types,$usertypes,
 7768:                                              $dom,$numinrow,$othertitle,
 7769:                                              'statustocreate',$rowtotal);
 7770:                 $$rowtotal ++;
 7771:             }
 7772:         }
 7773:         my @fields = ('lastname','firstname','middlename','permanentemail','id','inststatus');
 7774:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 7775:         $fieldtitles{'inststatus'} = &mt('Institutional status');
 7776:         my $rem;
 7777:         my $numperrow = 2;
 7778:         my $css_class = $$rowtotal%2?' class="LC_odd_row"':'';
 7779:         $datatable .= '<tr'.$css_class.'>'.
 7780:                      '<td class="LC_left_item">'.&mt('Mapping of Shibboleth environment variable names to user data fields (SSO auth)').'</td>'.
 7781:                      '<td class="LC_left_item">'."\n".
 7782:                      '<table>'."\n";
 7783:         for (my $i=0; $i<@fields; $i++) {
 7784:             $rem = $i%($numperrow);
 7785:             if ($rem == 0) {
 7786:                 if ($i > 0) {
 7787:                     $datatable .= '</tr>';
 7788:                 }
 7789:                 $datatable .= '<tr>';
 7790:             }
 7791:             my $currval;
 7792:             if (ref($createsettings) eq 'HASH') {
 7793:                 if (ref($createsettings->{'shibenv'}) eq 'HASH') {
 7794:                     $currval = $createsettings->{'shibenv'}{$fields[$i]};
 7795:                 }
 7796:             }
 7797:             $datatable .= '<td class="LC_left_item">'.
 7798:                           '<span class="LC_nobreak">'.
 7799:                           '<input type="text" name="shibenv_'.$fields[$i].'" '.
 7800:                           'value="'.$currval.'" size="10" />&nbsp;'.
 7801:                           $fieldtitles{$fields[$i]}.'</span></td>';
 7802:         }
 7803:         my $colsleft = $numperrow - $rem;
 7804:         if ($colsleft > 1 ) {
 7805:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 7806:                          '&nbsp;</td>';
 7807:         } elsif ($colsleft == 1) {
 7808:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 7809:         }
 7810:         $datatable .= '</tr></table></td></tr>';
 7811:         $$rowtotal ++;
 7812:     } elsif ($position eq 'middle') {
 7813:         my %domconf = &Apache::lonnet::get_dom('configuration',['usermodification'],$dom);
 7814:         my @posstypes;
 7815:         if (ref($types) eq 'ARRAY') {
 7816:             @posstypes = @{$types};
 7817:         }
 7818:         unless (grep(/^default$/,@posstypes)) {
 7819:             push(@posstypes,'default');
 7820:         }
 7821:         my %usertypeshash;
 7822:         if (ref($usertypes) eq 'HASH') {
 7823:             %usertypeshash = %{$usertypes};
 7824:         }
 7825:         $usertypeshash{'default'} = $othertitle;
 7826:         foreach my $status (@posstypes) {
 7827:             $datatable .= &modifiable_userdata_row('selfcreate',$status,$domconf{'usermodification'},
 7828:                                                    $numinrow,$$rowtotal,\%usertypeshash);
 7829:             $$rowtotal ++;
 7830:         }
 7831:     } else {
 7832:         my %choices = &Apache::lonlocal::texthash (
 7833:                           'cancreate_email' => 'Non-institutional username (via e-mail verification)',
 7834:                                                   );
 7835:         my @toggles = sort(keys(%choices));
 7836:         my %defaultchecked = (
 7837:                                'cancreate_email' => 'off',
 7838:                              );
 7839:         my $customclass = 'LC_selfcreate_email';
 7840:         my $classprefix = 'LC_canmodify_emailusername_';
 7841:         my $optionsprefix = 'LC_options_emailusername_';
 7842:         my $display = 'none';
 7843:         my $rowstyle = 'display:none';
 7844:         if (grep(/^\Qemail\E$/,@selfcreate)) {
 7845:             $display = 'block';
 7846:             $rowstyle = 'display:table-row';
 7847:         }
 7848:         my $onclick = "toggleRows(this.form,'cancreate_email','selfassign','$customclass','$classprefix','$optionsprefix');";
 7849:         ($datatable,$$rowtotal) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 7850:                                                      \%choices,$$rowtotal,$onclick);
 7851:         $datatable .= &print_requestmail($dom,'selfcreation',$createsettings,$rowtotal,$customclass,
 7852:                                          $rowstyle);
 7853:         $$rowtotal ++;
 7854:         $datatable .= &captcha_choice('cancreate',$createsettings,$$rowtotal,$customclass,
 7855:                                       $rowstyle);
 7856:         $$rowtotal ++;
 7857:         my (@ordered,@posstypes,%usertypeshash);
 7858:         my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
 7859:         my ($emailrules,$emailruleorder) =
 7860:             &Apache::lonnet::inst_userrules($dom,'email');
 7861:         my $primary_id = &Apache::lonnet::domain($dom,'primary');
 7862:         my $intdom = &Apache::lonnet::internet_dom($primary_id);
 7863:         if (ref($types) eq 'ARRAY') {
 7864:             @posstypes = @{$types};
 7865:         }
 7866:         if (@posstypes) {
 7867:             unless (grep(/^default$/,@posstypes)) {
 7868:                 push(@posstypes,'default');
 7869:             }
 7870:             if (ref($usertypes) eq 'HASH') {
 7871:                 %usertypeshash = %{$usertypes};
 7872:             }
 7873:             my $currassign;
 7874:             if (ref($domdefaults{'inststatusguest'}) eq 'ARRAY') {
 7875:                 $currassign = {
 7876:                                   selfassign => $domdefaults{'inststatusguest'},
 7877:                               };
 7878:                 @ordered = @{$domdefaults{'inststatusguest'}};
 7879:             } else {
 7880:                 $currassign = { selfassign => [] };
 7881:             }
 7882:             my $onclicktypes = "toggleDataRow(this.form,'selfassign','$customclass','$optionsprefix',);".
 7883:                                "toggleDataRow(this.form,'selfassign','$customclass','$classprefix',1);";
 7884:             $datatable .= &insttypes_row($currassign,$types,$usertypes,$dom,
 7885:                                          $numinrow,$othertitle,'selfassign',
 7886:                                          $rowtotal,$onclicktypes,$customclass,
 7887:                                          $rowstyle);
 7888:             $$rowtotal ++;
 7889:             $usertypeshash{'default'} = $othertitle;
 7890:             foreach my $status (@posstypes) {
 7891:                 my $css_class;
 7892:                 if ($$rowtotal%2) {
 7893:                     $css_class = 'LC_odd_row ';
 7894:                 }
 7895:                 $css_class .= $customclass;
 7896:                 my $rowid = $optionsprefix.$status;
 7897:                 my $hidden = 1;
 7898:                 my $currstyle = 'display:none';
 7899:                 if (grep(/^\Q$status\E$/,@ordered)) {
 7900:                     $currstyle = $rowstyle;
 7901:                     $hidden = 0;
 7902:                 }
 7903:                 $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
 7904:                                              $emailrules,$emailruleorder,$settings,$status,$rowid,
 7905:                                              $usertypeshash{$status},$css_class,$currstyle,$intdom);
 7906:                 unless ($hidden) {
 7907:                     $$rowtotal ++;
 7908:                 }
 7909:             }
 7910:         } else {
 7911:             my $css_class;
 7912:             if ($$rowtotal%2) {
 7913:                 $css_class = 'LC_odd_row ';
 7914:             }
 7915:             $css_class .= $customclass;
 7916:             $usertypeshash{'default'} = $othertitle;
 7917:             $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
 7918:                                          $emailrules,$emailruleorder,$settings,'default','',
 7919:                                          $othertitle,$css_class,$rowstyle,$intdom);
 7920:             $$rowtotal ++;
 7921:         }
 7922:         my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 7923:         $numinrow = 1;
 7924:         if (@posstypes) {
 7925:             foreach my $status (@posstypes) {
 7926:                 my $rowid = $classprefix.$status;
 7927:                 my $datarowstyle = 'display:none';
 7928:                 if (grep(/^\Q$status\E$/,@ordered)) {
 7929:                     $datarowstyle = $rowstyle;
 7930:                 }
 7931:                 $datatable .= &modifiable_userdata_row('cancreate','emailusername_'.$status,$settings,
 7932:                                                        $numinrow,$$rowtotal,\%usertypeshash,$infofields,
 7933:                                                        $infotitles,$rowid,$customclass,$datarowstyle);
 7934:                 unless ($datarowstyle eq 'display:none') {
 7935:                     $$rowtotal ++;
 7936:                 }
 7937:             }
 7938:         } else {
 7939:             $datatable .= &modifiable_userdata_row('cancreate','emailusername_default',$settings,
 7940:                                                    $numinrow,$$rowtotal,\%usertypeshash,$infofields,
 7941:                                                    $infotitles,'',$customclass,$rowstyle);
 7942:         }
 7943:     }
 7944:     return $datatable;
 7945: }
 7946: 
 7947: sub selfcreate_javascript {
 7948:     return <<"ENDSCRIPT";
 7949: 
 7950: <script type="text/javascript">
 7951: // <![CDATA[
 7952: 
 7953: function toggleRows(form,radio,checkbox,target,prefix,altprefix) {
 7954:     var x = document.getElementsByClassName(target);
 7955:     var insttypes = 0;
 7956:     var insttypeRegExp = new RegExp(prefix);
 7957:     if ((x.length != undefined) && (x.length > 0)) {
 7958:         if (form.elements[radio].length != undefined) {
 7959:             for (var i=0; i<form.elements[radio].length; i++) {
 7960:                 if (form.elements[radio][i].checked) {
 7961:                     if (form.elements[radio][i].value == 1) {
 7962:                         for (var j=0; j<x.length; j++) {
 7963:                             if (x[j].id == 'undefined') {
 7964:                                 x[j].style.display = 'table-row';
 7965:                             } else if (insttypeRegExp.test(x[j].id)) {
 7966:                                 insttypes ++;
 7967:                             } else {
 7968:                                 x[j].style.display = 'table-row';
 7969:                             }
 7970:                         }
 7971:                     } else {
 7972:                         for (var j=0; j<x.length; j++) {
 7973:                             x[j].style.display = 'none';
 7974:                         }
 7975:                     }
 7976:                     break;
 7977:                 }
 7978:             }
 7979:             if (insttypes > 0) {
 7980:                 toggleDataRow(form,checkbox,target,altprefix);
 7981:                 toggleDataRow(form,checkbox,target,prefix,1);
 7982:             }
 7983:         }
 7984:     }
 7985:     return;
 7986: }
 7987: 
 7988: function toggleDataRow(form,checkbox,target,prefix,docount) {
 7989:     if (form.elements[checkbox].length != undefined) {
 7990:         var count = 0;
 7991:         if (docount) {
 7992:             for (var i=0; i<form.elements[checkbox].length; i++) {
 7993:                 if (form.elements[checkbox][i].checked) {
 7994:                     count ++;
 7995:                 }
 7996:             }
 7997:         }
 7998:         for (var i=0; i<form.elements[checkbox].length; i++) {
 7999:             var type = form.elements[checkbox][i].value;
 8000:             if (document.getElementById(prefix+type)) {
 8001:                 if (form.elements[checkbox][i].checked) {
 8002:                     document.getElementById(prefix+type).style.display = 'table-row';
 8003:                     if (count % 2 == 1) {
 8004:                         document.getElementById(prefix+type).className = target+' LC_odd_row';
 8005:                     } else {
 8006:                         document.getElementById(prefix+type).className = target;
 8007:                     }
 8008:                     count ++;
 8009:                 } else {
 8010:                     document.getElementById(prefix+type).style.display = 'none';
 8011:                 }
 8012:             }
 8013:         }
 8014:     }
 8015:     return;
 8016: }
 8017: 
 8018: function toggleEmailOptions(form,radio,prefix,altprefix,status) {
 8019:     var caller = radio+'_'+status;
 8020:     if (form.elements[caller].length != undefined) {
 8021:         for (var i=0; i<form.elements[caller].length; i++) {
 8022:             if (form.elements[caller][i].checked) {
 8023:                 if (document.getElementById(altprefix+'_inst_'+status)) {
 8024:                     var curr = form.elements[caller][i].value;
 8025:                     if (prefix) {
 8026:                         document.getElementById(prefix+'_'+status).style.display = 'none';
 8027:                     }
 8028:                     document.getElementById(altprefix+'_inst_'+status).style.display = 'none';
 8029:                     document.getElementById(altprefix+'_noninst_'+status).style.display = 'none';
 8030:                     if (curr == 'custom') {
 8031:                         if (prefix) {
 8032:                             document.getElementById(prefix+'_'+status).style.display = 'inline';
 8033:                         }
 8034:                     } else if (curr == 'inst') {
 8035:                         document.getElementById(altprefix+'_inst_'+status).style.display = 'inline';
 8036:                     } else if (curr == 'noninst') {
 8037:                         document.getElementById(altprefix+'_noninst_'+status).style.display = 'inline';
 8038:                     }
 8039:                     break;
 8040:                 }
 8041:             }
 8042:         }
 8043:     }
 8044: }
 8045: 
 8046: // ]]>
 8047: </script>
 8048: 
 8049: ENDSCRIPT
 8050: }
 8051: 
 8052: sub noninst_users {
 8053:     my ($processing,$emailverified,$emailoptions,$emaildomain,$emailrules,
 8054:         $emailruleorder,$settings,$type,$rowid,$typetitle,$css_class,$rowstyle,$intdom) = @_;
 8055:     my $class = 'LC_left_item';
 8056:     if ($css_class) {
 8057:         $css_class = ' class="'.$css_class.'"';
 8058:     }
 8059:     if ($rowid) {
 8060:         $rowid = ' id="'.$rowid.'"';
 8061:     }
 8062:     if ($rowstyle) {
 8063:         $rowstyle = ' style="'.$rowstyle.'"';
 8064:     }
 8065:     my ($output,$description);
 8066:     if ($type eq 'default') {
 8067:         $description = &mt('Requests for: [_1]',$typetitle);
 8068:     } else {
 8069:         $description = &mt('Requests for: [_1] (status self-reported)',$typetitle);
 8070:     }
 8071:     $output = '<tr'.$css_class.$rowid.$rowstyle.'>'.
 8072:               "<td>$description</td>\n".
 8073:               '<td class="'.$class.'" colspan="2">'.
 8074:               '<table><tr>';
 8075:     my %headers = &Apache::lonlocal::texthash(
 8076:               approve  => 'Processing',
 8077:               email    => 'E-mail',
 8078:               username => 'Username',
 8079:     );
 8080:     foreach my $item ('approve','email','username') {
 8081:         $output .= '<th>'.$headers{$item}.'</th>';
 8082:     }
 8083:     $output .= '</tr><tr>';
 8084:     foreach my $item ('approve','email','username') {
 8085:         $output .= '<td valign="top">';
 8086:         my (%choices,@options,$hashref,$defoption,$name,$onclick,$hascustom);
 8087:         if ($item eq 'approve') {
 8088:             %choices = &Apache::lonlocal::texthash (
 8089:                                                      automatic => 'Automatically approved',
 8090:                                                      approval  => 'Queued for approval',
 8091:                                                    );
 8092:             @options = ('automatic','approval');
 8093:             $hashref = $processing;
 8094:             $defoption = 'automatic';
 8095:             $name = 'cancreate_emailprocess_'.$type;
 8096:         } elsif ($item eq 'email') {
 8097:             %choices = &Apache::lonlocal::texthash (
 8098:                                                      any     => 'Any e-mail',
 8099:                                                      inst    => 'Institutional only',
 8100:                                                      noninst => 'Non-institutional only',
 8101:                                                      custom  => 'Custom restrictions',
 8102:                                                    );
 8103:             @options = ('any','inst','noninst');
 8104:             my $showcustom;
 8105:             if (ref($emailrules) eq 'HASH') {
 8106:                 if (keys(%{$emailrules}) > 0) {
 8107:                     push(@options,'custom');
 8108:                     $showcustom = 'cancreate_emailrule';
 8109:                     if (ref($settings) eq 'HASH') {
 8110:                         if (ref($settings->{'email_rule'}) eq 'ARRAY') {
 8111:                             foreach my $rule (@{$settings->{'email_rule'}}) {
 8112:                                 if (exists($emailrules->{$rule})) {
 8113:                                     $hascustom ++;
 8114:                                 }
 8115:                             }
 8116:                         } elsif (ref($settings->{'email_rule'}) eq 'HASH') {
 8117:                             if (ref($settings->{'email_rule'}{$type}) eq 'ARRAY') {
 8118:                                 foreach my $rule (@{$settings->{'email_rule'}{$type}}) {
 8119:                                     if (exists($emailrules->{$rule})) {
 8120:                                         $hascustom ++;
 8121:                                     }
 8122:                                 }
 8123:                             }
 8124:                         }
 8125:                     }
 8126:                 }
 8127:             }
 8128:             $onclick = ' onclick="toggleEmailOptions(this.form,'."'cancreate_emailoptions','$showcustom',".
 8129:                                                      "'cancreate_emaildomain','$type'".');"';
 8130:             $hashref = $emailoptions;
 8131:             $defoption = 'any';
 8132:             $name = 'cancreate_emailoptions_'.$type;
 8133:         } elsif ($item eq 'username') {
 8134:             %choices = &Apache::lonlocal::texthash (
 8135:                                                      all    => 'Same as e-mail',
 8136:                                                      first  => 'Omit @domain',
 8137:                                                      free   => 'Free to choose',
 8138:                                                    );
 8139:             @options = ('all','first','free');
 8140:             $hashref = $emailverified;
 8141:             $defoption = 'all';
 8142:             $name = 'cancreate_usernameoptions_'.$type;
 8143:         }
 8144:         foreach my $option (@options) {
 8145:             my $checked;
 8146:             if (ref($hashref) eq 'HASH') {
 8147:                 if ($type eq '') {
 8148:                     if (!exists($hashref->{'default'})) {
 8149:                         if ($option eq $defoption) {
 8150:                             $checked = ' checked="checked"';
 8151:                         }
 8152:                     } else {
 8153:                         if ($hashref->{'default'} eq $option) {
 8154:                             $checked = ' checked="checked"';
 8155:                         }
 8156:                     }
 8157:                 } else {
 8158:                     if (!exists($hashref->{$type})) {
 8159:                         if ($option eq $defoption) {
 8160:                             $checked = ' checked="checked"';
 8161:                         }
 8162:                     } else {
 8163:                         if ($hashref->{$type} eq $option) {
 8164:                             $checked = ' checked="checked"';
 8165:                         }
 8166:                     }
 8167:                 }
 8168:             } elsif (($item eq 'email') && ($hascustom)) {
 8169:                 if ($option eq 'custom') {
 8170:                     $checked = ' checked="checked"';
 8171:                 }
 8172:             } elsif ($option eq $defoption) {
 8173:                 $checked = ' checked="checked"';
 8174:             }
 8175:             $output .= '<span class="LC_nobreak"><label>'.
 8176:                        '<input type="radio" name="'.$name.'"'.
 8177:                        $checked.' value="'.$option.'"'.$onclick.' />'.
 8178:                        $choices{$option}.'</label></span><br />';
 8179:             if ($item eq 'email') {
 8180:                 if ($option eq 'custom') {
 8181:                     my $id = 'cancreate_emailrule_'.$type;
 8182:                     my $display = 'none';
 8183:                     if ($checked) {
 8184:                         $display = 'inline';
 8185:                     }
 8186:                     my $numinrow = 2;
 8187:                     $output .= '<fieldset id="'.$id.'" style="display:'.$display.';">'.
 8188:                                '<legend>'.&mt('Disallow').'</legend><table>'.
 8189:                                &user_formats_row('email',$settings,$emailrules,
 8190:                                                  $emailruleorder,$numinrow,'',$type);
 8191:                               '</table></fieldset>';
 8192:                 } elsif (($option eq 'inst') || ($option eq 'noninst')) {
 8193:                     my %text = &Apache::lonlocal::texthash (
 8194:                                                              inst    => 'must end:',
 8195:                                                              noninst => 'cannot end:',
 8196:                                                            );
 8197:                     my $value;
 8198:                     if (ref($emaildomain) eq 'HASH') {
 8199:                         if (ref($emaildomain->{$type}) eq 'HASH') {
 8200:                             $value = $emaildomain->{$type}->{$option};
 8201:                         }
 8202:                     }
 8203:                     if ($value eq '') {
 8204:                         $value = '@'.$intdom;
 8205:                     }
 8206:                     my $condition = 'cancreate_emaildomain_'.$option.'_'.$type;
 8207:                     my $display = 'none';
 8208:                     if ($checked) {
 8209:                         $display = 'inline';
 8210:                     }
 8211:                     $output .= '<div id="'.$condition.'" style="display:'.$display.';">'.
 8212:                                '<span class="LC_domprefs_email">'.$text{$option}.'</span> '.
 8213:                                '<input type="text" name="'.$condition.'" value="'.$value.'" size="10" />'.
 8214:                                '</div>';
 8215:                 }
 8216:             }
 8217:         }
 8218:         $output .= '</td>'."\n";
 8219:     }
 8220:     $output .= "</tr></table></td></tr>\n";
 8221:     return $output;
 8222: }
 8223: 
 8224: sub captcha_choice {
 8225:     my ($context,$settings,$itemcount,$customcss,$rowstyle) = @_;
 8226:     my ($keyentry,$currpub,$currpriv,%checked,$rowname,$pubtext,$privtext,
 8227:         $vertext,$currver); 
 8228:     my %lt = &captcha_phrases();
 8229:     $keyentry = 'hidden';
 8230:     my $colspan=2;
 8231:     if ($context eq 'cancreate') {
 8232:         $rowname = &mt('CAPTCHA validation');
 8233:     } elsif ($context eq 'login') {
 8234:         $rowname =  &mt('"Contact helpdesk" CAPTCHA validation');
 8235:     } elsif ($context eq 'passwords') {
 8236:         $rowname = &mt('"Forgot Password" CAPTCHA validation');
 8237:         $colspan=1;
 8238:     }
 8239:     if (ref($settings) eq 'HASH') {
 8240:         if ($settings->{'captcha'}) {
 8241:             $checked{$settings->{'captcha'}} = ' checked="checked"';
 8242:         } else {
 8243:             $checked{'original'} = ' checked="checked"';
 8244:         }
 8245:         if ($settings->{'captcha'} eq 'recaptcha') {
 8246:             $pubtext = $lt{'pub'};
 8247:             $privtext = $lt{'priv'};
 8248:             $keyentry = 'text';
 8249:             $vertext = $lt{'ver'};
 8250:             $currver = $settings->{'recaptchaversion'};
 8251:             if ($currver ne '2') {
 8252:                 $currver = 1;
 8253:             }
 8254:         }
 8255:         if (ref($settings->{'recaptchakeys'}) eq 'HASH') {
 8256:             $currpub = $settings->{'recaptchakeys'}{'public'};
 8257:             $currpriv = $settings->{'recaptchakeys'}{'private'};
 8258:         }
 8259:     } else {
 8260:         $checked{'original'} = ' checked="checked"';
 8261:     }
 8262:     my $css_class;
 8263:     if ($itemcount%2) {
 8264:         $css_class = 'LC_odd_row';
 8265:     }
 8266:     if ($customcss) {
 8267:         $css_class .= " $customcss";
 8268:     }
 8269:     $css_class =~ s/^\s+//;
 8270:     if ($css_class) {
 8271:         $css_class = ' class="'.$css_class.'"';
 8272:     }
 8273:     if ($rowstyle) {
 8274:         $css_class .= ' style="'.$rowstyle.'"';
 8275:     }
 8276:     my $output = '<tr'.$css_class.'>'.
 8277:                  '<td class="LC_left_item">'.$rowname.'</td><td class="LC_left_item" colspan="'.$colspan.'">'."\n".
 8278:                  '<table><tr><td>'."\n";
 8279:     foreach my $option ('original','recaptcha','notused') {
 8280:         $output .= '<span class="LC_nobreak"><label><input type="radio" name="'.$context.'_captcha" value="'.
 8281:                    $option.'" '.$checked{$option}.' onchange="javascript:updateCaptcha('."this,'$context'".');" />'.
 8282:                    $lt{$option}.'</label></span>';
 8283:         unless ($option eq 'notused') {
 8284:             $output .= ('&nbsp;'x2)."\n";
 8285:         }
 8286:     }
 8287: #
 8288: # Note: If reCAPTCHA is to be used for LON-CAPA servers in a domain, a domain coordinator should visit:
 8289: # https://www.google.com/recaptcha and generate a Public and Private key. For domains with multiple
 8290: # servers a single key pair will be used for all servers, so the internet domain (e.g., yourcollege.edu)
 8291: # specified for use with the key should be broad enough to accommodate all servers in the LON-CAPA domain.
 8292: #
 8293:     $output .= '</td></tr>'."\n".
 8294:                '<tr><td class="LC_zero_height">'."\n".
 8295:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchapubtxt">'.$pubtext.'</span>&nbsp;'."\n".
 8296:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapub" name="'.$context.'_recaptchapub" value="'.
 8297:                $currpub.'" size="40" /></span><br />'."\n".
 8298:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchaprivtxt">'.$privtext.'</span>&nbsp;'."\n".
 8299:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapriv" name="'.$context.'_recaptchapriv" value="'.
 8300:                $currpriv.'" size="40" /></span><br />'.
 8301:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchavertxt">'.$vertext.'</span>&nbsp;'."\n".
 8302:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchaversion" name="'.$context.'_recaptchaversion" value="'.
 8303:                $currver.'" size="3" /></span><br />'.
 8304:                '</td></tr></table>'."\n".
 8305:                '</td></tr>';
 8306:     return $output;
 8307: }
 8308: 
 8309: sub user_formats_row {
 8310:     my ($type,$settings,$rules,$ruleorder,$numinrow,$rowcount,$status) = @_;
 8311:     my $output;
 8312:     my %text = (
 8313:                    'username' => 'new usernames',
 8314:                    'id'       => 'IDs',
 8315:                );
 8316:     unless ($type eq 'email') {
 8317:         my $css_class = $rowcount%2?' class="LC_odd_row"':'';
 8318:         $output = '<tr '.$css_class.'>'.
 8319:                   '<td><span class="LC_nobreak">'.
 8320:                   &mt("Format rules to check for $text{$type}: ").
 8321:                   '</td><td class="LC_left_item" colspan="2"><table>';
 8322:     }
 8323:     my $rem;
 8324:     if (ref($ruleorder) eq 'ARRAY') {
 8325:         for (my $i=0; $i<@{$ruleorder}; $i++) {
 8326:             if (ref($rules->{$ruleorder->[$i]}) eq 'HASH') {
 8327:                 my $rem = $i%($numinrow);
 8328:                 if ($rem == 0) {
 8329:                     if ($i > 0) {
 8330:                         $output .= '</tr>';
 8331:                     }
 8332:                     $output .= '<tr>';
 8333:                 }
 8334:                 my $check = ' ';
 8335:                 if (ref($settings) eq 'HASH') {
 8336:                     if (ref($settings->{$type.'_rule'}) eq 'ARRAY') {
 8337:                         if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}})) {
 8338:                             $check = ' checked="checked" ';
 8339:                         }
 8340:                     } elsif ((ref($settings->{$type.'_rule'}) eq 'HASH') && ($status ne '')) {
 8341:                         if (ref($settings->{$type.'_rule'}->{$status}) eq 'ARRAY') {
 8342:                             if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}->{$status}})) {
 8343:                                 $check = ' checked="checked" ';
 8344:                             }
 8345:                         }
 8346:                     }
 8347:                 }
 8348:                 my $name = $type.'_rule';
 8349:                 if ($type eq 'email') {
 8350:                     $name .= '_'.$status;
 8351:                 }
 8352:                 $output .= '<td class="LC_left_item">'.
 8353:                            '<span class="LC_nobreak"><label>'.
 8354:                            '<input type="checkbox" name="'.$name.'" '.
 8355:                            'value="'.$ruleorder->[$i].'"'.$check.'/>'.
 8356:                            $rules->{$ruleorder->[$i]}{'name'}.'</label></span></td>';
 8357:             }
 8358:         }
 8359:         $rem = @{$ruleorder}%($numinrow);
 8360:     }
 8361:     my $colsleft;
 8362:     if ($rem) {
 8363:         $colsleft = $numinrow - $rem;
 8364:     }
 8365:     if ($colsleft > 1 ) {
 8366:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 8367:                    '&nbsp;</td>';
 8368:     } elsif ($colsleft == 1) {
 8369:         $output .= '<td class="LC_left_item">&nbsp;</td>';
 8370:     }
 8371:     $output .= '</tr></table>';
 8372:     unless ($type eq 'email') {
 8373:         $output .= '</td></tr>';
 8374:     }
 8375:     return $output;
 8376: }
 8377: 
 8378: sub usercreation_types {
 8379:     my %lt = &Apache::lonlocal::texthash (
 8380:                     author     => 'When adding a co-author',
 8381:                     course     => 'When adding a user to a course',
 8382:                     requestcrs => 'When requesting a course',
 8383:                     any        => 'Any',
 8384:                     official   => 'Institutional only ',
 8385:                     unofficial => 'Non-institutional only',
 8386:                     none       => 'None',
 8387:     );
 8388:     return %lt;
 8389: }
 8390: 
 8391: sub selfcreation_types {
 8392:     my %lt = &Apache::lonlocal::texthash (
 8393:                     selfcreate => 'User creates own account',
 8394:                     any        => 'Any',
 8395:                     official   => 'Institutional only ',
 8396:                     unofficial => 'Non-institutional only',
 8397:                     email      => 'E-mail address',
 8398:                     login      => 'Institutional Login',
 8399:                     sso        => 'SSO',
 8400:              );
 8401: }
 8402: 
 8403: sub authtype_names {
 8404:     my %lt = &Apache::lonlocal::texthash(
 8405:                       int    => 'Internal',
 8406:                       krb4   => 'Kerberos 4',
 8407:                       krb5   => 'Kerberos 5',
 8408:                       loc    => 'Local',
 8409:                   );
 8410:     return %lt;
 8411: }
 8412: 
 8413: sub context_names {
 8414:     my %context_title = &Apache::lonlocal::texthash(
 8415:        author => 'Creating users when an Author',
 8416:        course => 'Creating users when in a course',
 8417:        domain => 'Creating users when a Domain Coordinator',
 8418:     );
 8419:     return %context_title;
 8420: }
 8421: 
 8422: sub print_usermodification {
 8423:     my ($position,$dom,$settings,$rowtotal) = @_;
 8424:     my $numinrow = 4;
 8425:     my ($context,$datatable,$rowcount);
 8426:     if ($position eq 'top') {
 8427:         $rowcount = 0;
 8428:         $context = 'author'; 
 8429:         foreach my $role ('ca','aa') {
 8430:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
 8431:                                                    $numinrow,$rowcount);
 8432:             $$rowtotal ++;
 8433:             $rowcount ++;
 8434:         }
 8435:     } elsif ($position eq 'bottom') {
 8436:         $context = 'course';
 8437:         $rowcount = 0;
 8438:         foreach my $role ('st','ep','ta','in','cr') {
 8439:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
 8440:                                                    $numinrow,$rowcount);
 8441:             $$rowtotal ++;
 8442:             $rowcount ++;
 8443:         }
 8444:     }
 8445:     return $datatable;
 8446: }
 8447: 
 8448: sub print_defaults {
 8449:     my ($position,$dom,$settings,$rowtotal) = @_;
 8450:     my $rownum = 0;
 8451:     my ($datatable,$css_class,$titles);
 8452:     unless ($position eq 'bottom') {
 8453:         $titles = &defaults_titles($dom);
 8454:     }
 8455:     if ($position eq 'top') {
 8456:         my @items = ('auth_def','auth_arg_def','lang_def','timezone_def',
 8457:                      'datelocale_def','portal_def');
 8458:         my %defaults;
 8459:         if (ref($settings) eq 'HASH') {
 8460:             %defaults = %{$settings};
 8461:         } else {
 8462:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
 8463:             foreach my $item (@items) {
 8464:                 $defaults{$item} = $domdefaults{$item};
 8465:             }
 8466:         }
 8467:         foreach my $item (@items) {
 8468:             if ($rownum%2) {
 8469:                 $css_class = '';
 8470:             } else {
 8471:                 $css_class = ' class="LC_odd_row" ';
 8472:             }
 8473:             $datatable .= '<tr'.$css_class.'>'.
 8474:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
 8475:                           '</span></td><td class="LC_right_item" colspan="3">';
 8476:             if ($item eq 'auth_def') {
 8477:                 my @authtypes = ('internal','krb4','krb5','localauth');
 8478:                 my %shortauth = (
 8479:                                  internal => 'int',
 8480:                                  krb4 => 'krb4',
 8481:                                  krb5 => 'krb5',
 8482:                                  localauth  => 'loc'
 8483:                                 );
 8484:                 my %authnames = &authtype_names();
 8485:                 foreach my $auth (@authtypes) {
 8486:                     my $checked = ' ';
 8487:                     if ($defaults{$item} eq $auth) {
 8488:                         $checked = ' checked="checked" ';
 8489:                     }
 8490:                     $datatable .= '<label><input type="radio" name="'.$item.
 8491:                                   '" value="'.$auth.'"'.$checked.'/>'.
 8492:                                   $authnames{$shortauth{$auth}}.'</label>&nbsp;&nbsp;';
 8493:                 }
 8494:             } elsif ($item eq 'timezone_def') {
 8495:                 my $includeempty = 1;
 8496:                 $datatable .= &Apache::loncommon::select_timezone($item,$defaults{$item},undef,$includeempty);
 8497:             } elsif ($item eq 'datelocale_def') {
 8498:                 my $includeempty = 1;
 8499:                 $datatable .= &Apache::loncommon::select_datelocale($item,$defaults{$item},undef,$includeempty);
 8500:             } elsif ($item eq 'lang_def') {
 8501:                 my $includeempty = 1;
 8502:                 $datatable .= &Apache::loncommon::select_language($item,$defaults{$item},$includeempty);
 8503:             } else {
 8504:                 my $size;
 8505:                 if ($item eq 'portal_def') {
 8506:                     $size = ' size="25"';
 8507:                 }
 8508:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
 8509:                               $defaults{$item}.'"'.$size.' />';
 8510:             }
 8511:             $datatable .= '</td></tr>';
 8512:             $rownum ++;
 8513:         }
 8514:     } else {
 8515:         my %defaults;
 8516:         if (ref($settings) eq 'HASH') {
 8517:             if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
 8518:                 my $maxnum = @{$settings->{'inststatusorder'}};
 8519:                 for (my $i=0; $i<$maxnum; $i++) {
 8520:                     $css_class = $rownum%2?' class="LC_odd_row"':'';
 8521:                     my $item = $settings->{'inststatusorder'}->[$i];
 8522:                     my $title = $settings->{'inststatustypes'}->{$item};
 8523:                     my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'$item'".');"';
 8524:                     $datatable .= '<tr'.$css_class.'>'.
 8525:                                   '<td><span class="LC_nobreak">'.
 8526:                                   '<select name="inststatus_pos_'.$item.'"'.$chgstr.'>';
 8527:                     for (my $k=0; $k<=$maxnum; $k++) {
 8528:                         my $vpos = $k+1;
 8529:                         my $selstr;
 8530:                         if ($k == $i) {
 8531:                             $selstr = ' selected="selected" ';
 8532:                         }
 8533:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 8534:                     }
 8535:                     $datatable .= '</select>&nbsp;'.&mt('Internal ID:').'&nbsp;<b>'.$item.'</b>&nbsp;'.
 8536:                                   '<input type="checkbox" name="inststatus_delete" value="'.$item.'" />'.
 8537:                                   &mt('delete').'</span></td>'.
 8538:                                   '<td class="LC_left_item"><span class="LC_nobreak">'.&mt('Name displayed').':'.
 8539:                                   '<input type="text" size="20" name="inststatus_title_'.$item.'" value="'.$title.'" />'.
 8540:                                   '</span></td></tr>';
 8541:                 }
 8542:                 $css_class = $rownum%2?' class="LC_odd_row"':'';
 8543:                 my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'addinststatus_pos'".');"';
 8544:                 $datatable .= '<tr '.$css_class.'>'.
 8545:                               '<td><span class="LC_nobreak"><select name="addinststatus_pos"'.$chgstr.'>';
 8546:                 for (my $k=0; $k<=$maxnum; $k++) {
 8547:                     my $vpos = $k+1;
 8548:                     my $selstr;
 8549:                     if ($k == $maxnum) {
 8550:                         $selstr = ' selected="selected" ';
 8551:                     }
 8552:                     $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 8553:                 }
 8554:                 $datatable .= '</select>&nbsp;'.&mt('Internal ID:').
 8555:                               '<input type="text" size="10" name="addinststatus" value="" />'.
 8556:                               '&nbsp;'.&mt('(new)').
 8557:                               '</span></td><td class="LC_left_item"><span class="LC_nobreak">'.
 8558:                               &mt('Name displayed').':'.
 8559:                               '<input type="text" size="20" name="addinststatus_title" value="" /></span></td>'.
 8560:                               '</tr>'."\n";
 8561:                 $rownum ++;
 8562:             }
 8563:         }
 8564:     }
 8565:     $$rowtotal += $rownum;
 8566:     return $datatable;
 8567: }
 8568: 
 8569: sub get_languages_hash {
 8570:     my %langchoices;
 8571:     foreach my $id (&Apache::loncommon::languageids()) {
 8572:         my $code = &Apache::loncommon::supportedlanguagecode($id);
 8573:         if ($code ne '') {
 8574:             $langchoices{$code} =  &Apache::loncommon::plainlanguagedescription($id);
 8575:         }
 8576:     }
 8577:     return %langchoices;
 8578: }
 8579: 
 8580: sub defaults_titles {
 8581:     my ($dom) = @_;
 8582:     my %titles = &Apache::lonlocal::texthash (
 8583:                    'auth_def'      => 'Default authentication type',
 8584:                    'auth_arg_def'  => 'Default authentication argument',
 8585:                    'lang_def'      => 'Default language',
 8586:                    'timezone_def'  => 'Default timezone',
 8587:                    'datelocale_def' => 'Default locale for dates',
 8588:                    'portal_def'     => 'Portal/Default URL',
 8589:                    'intauth_cost'   => 'Encryption cost for bcrypt (positive integer)',
 8590:                    'intauth_check'  => 'Check bcrypt cost if authenticated',
 8591:                    'intauth_switch' => 'Existing crypt-based switched to bcrypt on authentication',
 8592:                  );
 8593:     if ($dom) {
 8594:         my $uprimary_id = &Apache::lonnet::domain($dom,'primary');
 8595:         my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 8596:         my $protocol = $Apache::lonnet::protocol{$uprimary_id};
 8597:         $protocol = 'http' if ($protocol ne 'https');
 8598:         if ($uint_dom) {
 8599:             $titles{'portal_def'} .= ' '.&mt('(for example: [_1])',$protocol.'://loncapa.'.
 8600:                                          $uint_dom);
 8601:         }
 8602:     }
 8603:     return (\%titles);
 8604: }
 8605: 
 8606: sub print_scantron {
 8607:     my ($r,$position,$dom,$confname,$settings,$rowtotal) = @_;
 8608:     if ($position eq 'top') {
 8609:         return &print_scantronformat($r,$dom,$confname,$settings,\$rowtotal);
 8610:     } else {
 8611:         return &print_scantronconfig($dom,$settings,\$rowtotal);
 8612:     }
 8613: }
 8614: 
 8615: sub scantron_javascript {
 8616:     return <<"ENDSCRIPT";
 8617: 
 8618: <script type="text/javascript">
 8619: // <![CDATA[
 8620: 
 8621: function toggleScantron(form) {
 8622:     var csvfieldset = new Array();
 8623:     if (document.getElementById('scantroncsv_cols')) {
 8624:         csvfieldset.push(document.getElementById('scantroncsv_cols'));
 8625:     }
 8626:     if (document.getElementById('scantroncsv_options')) {
 8627:         csvfieldset.push(document.getElementById('scantroncsv_options'));
 8628:     }
 8629:     if (csvfieldset.length) {
 8630:         if (document.getElementById('scantronconfcsv')) {
 8631:             var scantroncsv = document.getElementById('scantronconfcsv');
 8632:             if (scantroncsv.checked) {
 8633:                 for (var i=0; i<csvfieldset.length; i++) {
 8634:                     csvfieldset[i].style.display = 'block';
 8635:                 }
 8636:             } else {
 8637:                 for (var i=0; i<csvfieldset.length; i++) {
 8638:                     csvfieldset[i].style.display = 'none';
 8639:                 }
 8640:                 var csvselects = document.getElementsByClassName('scantronconfig_csv');
 8641:                 if (csvselects.length) {
 8642:                     for (var j=0; j<csvselects.length; j++) {
 8643:                         csvselects[j].selectedIndex = 0;
 8644:                     }
 8645:                 }
 8646:             }
 8647:         }
 8648:     }
 8649:     return;
 8650: }
 8651: // ]]>
 8652: </script>
 8653: 
 8654: ENDSCRIPT
 8655: 
 8656: }
 8657: 
 8658: sub print_scantronformat {
 8659:     my ($r,$dom,$confname,$settings,$rowtotal) = @_;
 8660:     my $itemcount = 1;
 8661:     my ($datatable,$css_class,$scantronurl,$is_custom,%error,%scantronurls,
 8662:         %confhash);
 8663:     my $switchserver = &check_switchserver($dom,$confname);
 8664:     my %lt = &Apache::lonlocal::texthash (
 8665:                 default => 'Default bubblesheet format file error',
 8666:                 custom  => 'Custom bubblesheet format file error',
 8667:              );
 8668:     my %scantronfiles = (
 8669:         default => 'default.tab',
 8670:         custom => 'custom.tab',
 8671:     );
 8672:     foreach my $key (keys(%scantronfiles)) {
 8673:         $scantronurls{$key} = '/res/'.$dom.'/'.$confname.'/scantron/'
 8674:                               .$scantronfiles{$key};
 8675:     }
 8676:     my @defaultinfo = &Apache::lonnet::stat_file($scantronurls{'default'});
 8677:     if ((!@defaultinfo) || ($defaultinfo[0] eq 'no_such_dir')) {
 8678:         if (!$switchserver) {
 8679:             my $servadm = $r->dir_config('lonAdmEMail');
 8680:             my ($configuserok,$author_ok) = &config_check($dom,$confname,$servadm);
 8681:             if ($configuserok eq 'ok') {
 8682:                 if ($author_ok eq 'ok') {
 8683:                     my %legacyfile = (
 8684:  default => $Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab',
 8685:  custom  => $Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab',
 8686:                     );
 8687:                     my %md5chk;
 8688:                     foreach my $type (keys(%legacyfile)) {
 8689:                         ($md5chk{$type}) = split(/ /,`md5sum $legacyfile{$type}`);
 8690:                         chomp($md5chk{$type});
 8691:                     }
 8692:                     if ($md5chk{'default'} ne $md5chk{'custom'}) {
 8693:                         foreach my $type (keys(%legacyfile)) {
 8694:                             ($scantronurls{$type},my $error) =
 8695:                                 &legacy_scantronformat($r,$dom,$confname,
 8696:                                                  $type,$legacyfile{$type},
 8697:                                                  $scantronurls{$type},
 8698:                                                  $scantronfiles{$type});
 8699:                             if ($error ne '') {
 8700:                                 $error{$type} = $error;
 8701:                             }
 8702:                         }
 8703:                         if (keys(%error) == 0) {
 8704:                             $is_custom = 1;
 8705:                             $confhash{'scantron'}{'scantronformat'} =
 8706:                                 $scantronurls{'custom'};
 8707:                             my $putresult =
 8708:                                 &Apache::lonnet::put_dom('configuration',
 8709:                                                          \%confhash,$dom);
 8710:                             if ($putresult ne 'ok') {
 8711:                                 $error{'custom'} =
 8712:                                     '<span class="LC_error">'.
 8713:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
 8714:                             }
 8715:                         }
 8716:                     } else {
 8717:                         ($scantronurls{'default'},my $error) =
 8718:                             &legacy_scantronformat($r,$dom,$confname,
 8719:                                           'default',$legacyfile{'default'},
 8720:                                           $scantronurls{'default'},
 8721:                                           $scantronfiles{'default'});
 8722:                         if ($error eq '') {
 8723:                             $confhash{'scantron'}{'scantronformat'} = ''; 
 8724:                             my $putresult =
 8725:                                 &Apache::lonnet::put_dom('configuration',
 8726:                                                          \%confhash,$dom);
 8727:                             if ($putresult ne 'ok') {
 8728:                                 $error{'default'} =
 8729:                                     '<span class="LC_error">'.
 8730:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
 8731:                             }
 8732:                         } else {
 8733:                             $error{'default'} = $error;
 8734:                         }
 8735:                     }
 8736:                 }
 8737:             }
 8738:         } else {
 8739:             $error{'default'} = &mt("Unable to copy default bubblesheet formatfile to domain's RES space: [_1]",$switchserver);
 8740:         }
 8741:     }
 8742:     if (ref($settings) eq 'HASH') {
 8743:         if ($settings->{'scantronformat'} eq "/res/$dom/$confname/scantron/custom.tab") {
 8744:             my @info = &Apache::lonnet::stat_file($settings->{'scantronformat'});
 8745:             if ((!@info) || ($info[0] eq 'no_such_dir')) {
 8746:                 $scantronurl = '';
 8747:             } else {
 8748:                 $scantronurl = $settings->{'scantronformat'};
 8749:             }
 8750:             $is_custom = 1;
 8751:         } else {
 8752:             $scantronurl = $scantronurls{'default'};
 8753:         }
 8754:     } else {
 8755:         if ($is_custom) {
 8756:             $scantronurl = $scantronurls{'custom'};
 8757:         } else {
 8758:             $scantronurl = $scantronurls{'default'};
 8759:         }
 8760:     }
 8761:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8762:     $datatable .= '<tr'.$css_class.'>';
 8763:     if (!$is_custom) {
 8764:         $datatable .= '<td>'.&mt('Default in use:').'<br />'.
 8765:                       '<span class="LC_nobreak">';
 8766:         if ($scantronurl) {
 8767:             $datatable .= &Apache::loncommon::modal_link($scantronurl,&mt('Default bubblesheet format file'),600,500,
 8768:                                                          undef,undef,undef,undef,'background-color:#ffffff');
 8769:         } else {
 8770:             $datatable = &mt('File unavailable for display');
 8771:         }
 8772:         $datatable .= '</span></td>';
 8773:         if (keys(%error) == 0) { 
 8774:             $datatable .= '<td valign="bottom">';
 8775:             if (!$switchserver) {
 8776:                 $datatable .= &mt('Upload:').'<br />';
 8777:             }
 8778:         } else {
 8779:             my $errorstr;
 8780:             foreach my $key (sort(keys(%error))) {
 8781:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
 8782:             }
 8783:             $datatable .= '<td>'.$errorstr;
 8784:         }
 8785:     } else {
 8786:         if (keys(%error) > 0) {
 8787:             my $errorstr;
 8788:             foreach my $key (sort(keys(%error))) {
 8789:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
 8790:             } 
 8791:             $datatable .= '<td>'.$errorstr.'</td><td>&nbsp;';
 8792:         } elsif ($scantronurl) {
 8793:             my $link =  &Apache::loncommon::modal_link($scantronurl,&mt('Custom bubblesheet format file'),600,500,
 8794:                                                        undef,undef,undef,undef,'background-color:#ffffff');
 8795:             $datatable .= '<td><span class="LC_nobreak">'.
 8796:                           $link.
 8797:                           '<label><input type="checkbox" name="scantronformat_del"'.
 8798:                           ' value="1" />'.&mt('Delete?').'</label></span></td>'.
 8799:                           '<td><span class="LC_nobreak">&nbsp;'.
 8800:                           &mt('Replace:').'</span><br />';
 8801:         }
 8802:     }
 8803:     if (keys(%error) == 0) {
 8804:         if ($switchserver) {
 8805:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 8806:         } else {
 8807:             $datatable .='<span class="LC_nobreak">&nbsp;'.
 8808:                          '<input type="file" name="scantronformat" /></span>';
 8809:         }
 8810:     }
 8811:     $datatable .= '</td></tr>';
 8812:     $$rowtotal ++;
 8813:     return $datatable;
 8814: }
 8815: 
 8816: sub legacy_scantronformat {
 8817:     my ($r,$dom,$confname,$file,$legacyfile,$newurl,$newfile) = @_;
 8818:     my ($url,$error);
 8819:     my @statinfo = &Apache::lonnet::stat_file($newurl);
 8820:     if ((!@statinfo) || ($statinfo[0] eq 'no_such_dir')) {
 8821:         (my $result,$url) =
 8822:             &publishlogo($r,'copy',$legacyfile,$dom,$confname,'scantron',
 8823:                          '','',$newfile);
 8824:         if ($result ne 'ok') {
 8825:             $error = &mt("An error occurred publishing the [_1] bubblesheet format file in RES space. Error was: [_2].",$newfile,$result);
 8826:         }
 8827:     }
 8828:     return ($url,$error);
 8829: }
 8830: 
 8831: sub print_scantronconfig {
 8832:     my ($dom,$settings,$rowtotal) = @_;
 8833:     my $itemcount = 2;
 8834:     my $is_checked = ' checked="checked"';
 8835:     my %optionson = (
 8836:                      hdr => ' checked="checked"',
 8837:                      pad => ' checked="checked"',
 8838:                      rem => ' checked="checked"',
 8839:                     );
 8840:     my %optionsoff = (
 8841:                       hdr => '',
 8842:                       pad => '',
 8843:                       rem => '',
 8844:                      );
 8845:     my $currcsvsty = 'none';
 8846:     my ($datatable,%csvfields,%checked,%onclick,%csvoptions);
 8847:     my @fields = &scantroncsv_fields();
 8848:     my %titles = &scantronconfig_titles();
 8849:     if (ref($settings) eq 'HASH') {
 8850:         if (ref($settings->{config}) eq 'HASH') {
 8851:             if ($settings->{config}->{dat}) {
 8852:                 $checked{'dat'} = $is_checked;
 8853:             }
 8854:             if (ref($settings->{config}->{csv}) eq 'HASH') {
 8855:                 if (ref($settings->{config}->{csv}->{fields}) eq 'HASH') {
 8856:                     %csvfields = %{$settings->{config}->{csv}->{fields}};
 8857:                     if (keys(%csvfields) > 0) {
 8858:                         $checked{'csv'} = $is_checked;
 8859:                         $currcsvsty = 'block';
 8860:                     }
 8861:                 }
 8862:                 if (ref($settings->{config}->{csv}->{options}) eq 'HASH') {
 8863:                     %csvoptions = %{$settings->{config}->{csv}->{options}};
 8864:                     foreach my $option (keys(%optionson)) {
 8865:                         unless ($csvoptions{$option}) {
 8866:                             $optionsoff{$option} = $optionson{$option};
 8867:                             $optionson{$option} = '';
 8868:                         }
 8869:                     }
 8870:                 }
 8871:             }
 8872:         } else {
 8873:             $checked{'dat'} = $is_checked;
 8874:         }
 8875:     } else {
 8876:         $checked{'dat'} = $is_checked;
 8877:     }
 8878:     $onclick{'csv'} = ' onclick="toggleScantron(this.form);"';
 8879:     my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
 8880:     $datatable = '<tr '.$css_class.'><td>'.&mt('Supported formats').'</td>'.
 8881:                  '<td class="LC_left_item" valign="top"><span class="LC_nobreak">';
 8882:     foreach my $item ('dat','csv') {
 8883:         my $id;
 8884:         if ($item eq 'csv') {
 8885:             $id = 'id="scantronconfcsv" ';
 8886:         }
 8887:         $datatable .= '<label><input type="checkbox" name="scantronconfig" '.$id.'value="'.$item.'"'.$checked{$item}.$onclick{$item}.' />'.
 8888:                       $titles{$item}.'</label>'.('&nbsp;'x3);
 8889:         if ($item eq 'csv') {
 8890:             $datatable .= '<fieldset style="display:'.$currcsvsty.'" id="scantroncsv_cols">'.
 8891:                           '<legend>'.&mt('CSV Column Mapping').'</legend>'.
 8892:                           '<table><tr><th>'.&mt('Field').'</th><th>'.&mt('Location').'</th></tr>'."\n";
 8893:             foreach my $col (@fields) {
 8894:                 my $selnone;
 8895:                 if ($csvfields{$col} eq '') {
 8896:                     $selnone = ' selected="selected"';
 8897:                 }
 8898:                 $datatable .= '<tr><td>'.$titles{$col}.'</td>'.
 8899:                               '<td><select name="scantronconfig_csv_'.$col.'" class="scantronconfig_csv">'.
 8900:                               '<option value=""'.$selnone.'></option>';
 8901:                 for (my $i=0; $i<20; $i++) {
 8902:                     my $shown = $i+1;
 8903:                     my $sel;
 8904:                     unless ($selnone) {
 8905:                         if (exists($csvfields{$col})) {
 8906:                             if ($csvfields{$col} == $i) {
 8907:                                 $sel = ' selected="selected"';
 8908:                             }
 8909:                         }
 8910:                     }
 8911:                     $datatable .= '<option value="'.$i.'"'.$sel.'>'.$shown.'</option>';
 8912:                 }
 8913:                 $datatable .= '</select></td></tr>';
 8914:            }
 8915:            $datatable .= '</table></fieldset>'.
 8916:                          '<fieldset style="display:'.$currcsvsty.'" id="scantroncsv_options">'.
 8917:                          '<legend>'.&mt('CSV Options').'</legend>';
 8918:            foreach my $option ('hdr','pad','rem') {
 8919:                $datatable .= '<span class="LC_nobreak">'.$titles{$option}.':'.
 8920:                          '<label><input type="radio" name="scantroncsv_'.$option.'" value="1"'.$optionson{$option}.' />'.
 8921:                          &mt('Yes').'</label>'.('&nbsp;'x2)."\n".
 8922:                          '<label><input type="radio" name="scantroncsv_'.$option.'" value="0"'.$optionsoff{$option}.' />'.&mt('No').'</label></span><br />';
 8923:            }
 8924:            $datatable .= '</fieldset>';
 8925:            $itemcount ++;
 8926:         }
 8927:     }
 8928:     $datatable .= '</td></tr>';
 8929:     $$rowtotal ++;
 8930:     return $datatable;
 8931: }
 8932: 
 8933: sub scantronconfig_titles {
 8934:     return &Apache::lonlocal::texthash(
 8935:                                           dat => 'Standard format (.dat)',
 8936:                                           csv => 'Comma separated values (.csv)',
 8937:                                           hdr => 'Remove first line in file (contains column titles)',
 8938:                                           pad => 'Prepend 0s to PaperID',
 8939:                                           rem => 'Remove leading spaces (except Question Response columns)',
 8940:                                           CODE => 'CODE',
 8941:                                           ID   => 'Student ID',
 8942:                                           PaperID => 'Paper ID',
 8943:                                           FirstName => 'First Name',
 8944:                                           LastName => 'Last Name',
 8945:                                           FirstQuestion => 'First Question Response',
 8946:                                           Section => 'Section',
 8947:     );
 8948: }
 8949: 
 8950: sub scantroncsv_fields {
 8951:     return ('PaperID','LastName','FirstName','ID','Section','CODE','FirstQuestion');
 8952: }
 8953: 
 8954: sub print_coursecategories {
 8955:     my ($position,$dom,$hdritem,$settings,$rowtotal) = @_;
 8956:     my $datatable;
 8957:     if ($position eq 'top') {
 8958:         my (%checked);
 8959:         my @catitems = ('unauth','auth');
 8960:         my @cattypes = ('std','domonly','codesrch','none');
 8961:         $checked{'unauth'} = 'std';
 8962:         $checked{'auth'} = 'std';
 8963:         if (ref($settings) eq 'HASH') {
 8964:             foreach my $type (@cattypes) {
 8965:                 if ($type eq $settings->{'unauth'}) {
 8966:                     $checked{'unauth'} = $type;
 8967:                 }
 8968:                 if ($type eq $settings->{'auth'}) {
 8969:                     $checked{'auth'} = $type;
 8970:                 }
 8971:             }
 8972:         }
 8973:         my %lt = &Apache::lonlocal::texthash (
 8974:                                                unauth   => 'Catalog type for unauthenticated users',
 8975:                                                auth     => 'Catalog type for authenticated users',
 8976:                                                none     => 'No catalog',
 8977:                                                std      => 'Standard catalog',
 8978:                                                domonly  => 'Domain-only catalog',
 8979:                                                codesrch => "Code search form",
 8980:                                              );
 8981:        my $itemcount = 0;
 8982:        foreach my $item (@catitems) {
 8983:            my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
 8984:            $datatable .= '<tr '.$css_class.'>'.
 8985:                          '<td>'.$lt{$item}.'</td>'.
 8986:                          '<td class="LC_right_item"><span class="LC_nobreak">';
 8987:            foreach my $type (@cattypes) {
 8988:                my $ischecked;
 8989:                if ($checked{$item} eq $type) {
 8990:                    $ischecked=' checked="checked"';
 8991:                }
 8992:                $datatable .= '<label>'.
 8993:                              '<input type="radio" name="coursecat_'.$item.'" value="'.$type.'"'.$ischecked.
 8994:                              ' />'.$lt{$type}.'</label>&nbsp;';
 8995:            }
 8996:            $datatable .= '</span></td></tr>';
 8997:            $itemcount ++;
 8998:         }
 8999:         $$rowtotal += $itemcount;
 9000:     } elsif ($position eq 'middle') {
 9001:         my $toggle_cats_crs = ' ';
 9002:         my $toggle_cats_dom = ' checked="checked" ';
 9003:         my $can_cat_crs = ' ';
 9004:         my $can_cat_dom = ' checked="checked" ';
 9005:         my $toggle_catscomm_comm = ' ';
 9006:         my $toggle_catscomm_dom = ' checked="checked" ';
 9007:         my $can_catcomm_comm = ' ';
 9008:         my $can_catcomm_dom = ' checked="checked" ';
 9009: 
 9010:         if (ref($settings) eq 'HASH') {
 9011:             if ($settings->{'togglecats'} eq 'crs') {
 9012:                 $toggle_cats_crs = $toggle_cats_dom;
 9013:                 $toggle_cats_dom = ' ';
 9014:             }
 9015:             if ($settings->{'categorize'} eq 'crs') {
 9016:                 $can_cat_crs = $can_cat_dom;
 9017:                 $can_cat_dom = ' ';
 9018:             }
 9019:             if ($settings->{'togglecatscomm'} eq 'comm') {
 9020:                 $toggle_catscomm_comm = $toggle_catscomm_dom;
 9021:                 $toggle_catscomm_dom = ' ';
 9022:             }
 9023:             if ($settings->{'categorizecomm'} eq 'comm') {
 9024:                 $can_catcomm_comm = $can_catcomm_dom;
 9025:                 $can_catcomm_dom = ' ';
 9026:             }
 9027:         }
 9028:         my %title = &Apache::lonlocal::texthash (
 9029:                      togglecats     => 'Show/Hide a course in catalog',
 9030:                      togglecatscomm => 'Show/Hide a community in catalog',
 9031:                      categorize     => 'Assign a category to a course',
 9032:                      categorizecomm => 'Assign a category to a community',
 9033:                     );
 9034:         my %level = &Apache::lonlocal::texthash (
 9035:                      dom  => 'Set in Domain',
 9036:                      crs  => 'Set in Course',
 9037:                      comm => 'Set in Community',
 9038:                     );
 9039:         $datatable = '<tr class="LC_odd_row">'.
 9040:                   '<td>'.$title{'togglecats'}.'</td>'.
 9041:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 9042:                   '<input type="radio" name="togglecats"'.
 9043:                   $toggle_cats_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 9044:                   '<label><input type="radio" name="togglecats"'.
 9045:                   $toggle_cats_crs.' value="crs" />'.$level{'crs'}.'</label></span></td>'.
 9046:                   '</tr><tr>'.
 9047:                   '<td>'.$title{'categorize'}.'</td>'.
 9048:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 9049:                   '<label><input type="radio" name="categorize"'.
 9050:                   $can_cat_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 9051:                   '<label><input type="radio" name="categorize"'.
 9052:                   $can_cat_crs.'value="crs" />'.$level{'crs'}.'</label></span></td>'.
 9053:                   '</tr><tr class="LC_odd_row">'.
 9054:                   '<td>'.$title{'togglecatscomm'}.'</td>'.
 9055:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 9056:                   '<input type="radio" name="togglecatscomm"'.
 9057:                   $toggle_catscomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 9058:                   '<label><input type="radio" name="togglecatscomm"'.
 9059:                   $toggle_catscomm_comm.' value="comm" />'.$level{'comm'}.'</label></span></td>'.
 9060:                   '</tr><tr>'.
 9061:                   '<td>'.$title{'categorizecomm'}.'</td>'.
 9062:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 9063:                   '<label><input type="radio" name="categorizecomm"'.
 9064:                   $can_catcomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 9065:                   '<label><input type="radio" name="categorizecomm"'.
 9066:                   $can_catcomm_comm.'value="comm" />'.$level{'comm'}.'</label></span></td>'.
 9067:                   '</tr>';
 9068:         $$rowtotal += 4;
 9069:     } else {
 9070:         my $css_class;
 9071:         my $itemcount = 1;
 9072:         my $cathash; 
 9073:         if (ref($settings) eq 'HASH') {
 9074:             $cathash = $settings->{'cats'};
 9075:         }
 9076:         if (ref($cathash) eq 'HASH') {
 9077:             my (@cats,@trails,%allitems,%idx,@jsarray);
 9078:             &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,
 9079:                                                    \%allitems,\%idx,\@jsarray);
 9080:             my $maxdepth = scalar(@cats);
 9081:             my $colattrib = '';
 9082:             if ($maxdepth > 2) {
 9083:                 $colattrib = ' colspan="2" ';
 9084:             }
 9085:             my @path;
 9086:             if (@cats > 0) {
 9087:                 if (ref($cats[0]) eq 'ARRAY') {
 9088:                     my $numtop = @{$cats[0]};
 9089:                     my $maxnum = $numtop;
 9090:                     my %default_names = (
 9091:                           instcode    => &mt('Official courses'),
 9092:                           communities => &mt('Communities'),
 9093:                     );
 9094: 
 9095:                     if ((!grep(/^instcode$/,@{$cats[0]})) || 
 9096:                         ($cathash->{'instcode::0'} eq '') ||
 9097:                         (!grep(/^communities$/,@{$cats[0]})) || 
 9098:                         ($cathash->{'communities::0'} eq '')) {
 9099:                         $maxnum ++;
 9100:                     }
 9101:                     my $lastidx;
 9102:                     for (my $i=0; $i<$numtop; $i++) {
 9103:                         my $parent = $cats[0][$i];
 9104:                         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9105:                         my $item = &escape($parent).'::0';
 9106:                         my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$item','$idx{$item}'".');"';
 9107:                         $lastidx = $idx{$item};
 9108:                         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 9109:                                       .'<select name="'.$item.'"'.$chgstr.'>';
 9110:                         for (my $k=0; $k<=$maxnum; $k++) {
 9111:                             my $vpos = $k+1;
 9112:                             my $selstr;
 9113:                             if ($k == $i) {
 9114:                                 $selstr = ' selected="selected" ';
 9115:                             }
 9116:                             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 9117:                         }
 9118:                         $datatable .= '</select></span></td><td>';
 9119:                         if ($parent eq 'instcode' || $parent eq 'communities') {
 9120:                             $datatable .=  '<span class="LC_nobreak">'
 9121:                                            .$default_names{$parent}.'</span>';
 9122:                             if ($parent eq 'instcode') {
 9123:                                 $datatable .= '<br /><span class="LC_nobreak">('
 9124:                                               .&mt('with institutional codes')
 9125:                                               .')</span></td><td'.$colattrib.'>';
 9126:                             } else {
 9127:                                 $datatable .= '<table><tr><td>';
 9128:                             }
 9129:                             $datatable .= '<span class="LC_nobreak">'
 9130:                                           .'<label><input type="radio" name="'
 9131:                                           .$parent.'" value="1" checked="checked" />'
 9132:                                           .&mt('Display').'</label>';
 9133:                             if ($parent eq 'instcode') {
 9134:                                 $datatable .= '&nbsp;';
 9135:                             } else {
 9136:                                 $datatable .= '</span></td></tr><tr><td>'
 9137:                                               .'<span class="LC_nobreak">';
 9138:                             }
 9139:                             $datatable .= '<label><input type="radio" name="'
 9140:                                           .$parent.'" value="0" />'
 9141:                                           .&mt('Do not display').'</label></span>';
 9142:                             if ($parent eq 'communities') {
 9143:                                 $datatable .= '</td></tr></table>';
 9144:                             }
 9145:                             $datatable .= '</td>';
 9146:                         } else {
 9147:                             $datatable .= $parent
 9148:                                           .'&nbsp;<span class="LC_nobreak"><label>'
 9149:                                           .'<input type="checkbox" name="deletecategory" '
 9150:                                           .'value="'.$item.'" />'.&mt('Delete').'</label></span></td>';
 9151:                         }
 9152:                         my $depth = 1;
 9153:                         push(@path,$parent);
 9154:                         $datatable .= &build_category_rows($itemcount,\@cats,$depth,$parent,\@path,\%idx);
 9155:                         pop(@path);
 9156:                         $datatable .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
 9157:                         $itemcount ++;
 9158:                     }
 9159:                     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9160:                     my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','$lastidx'".');"';
 9161:                     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="addcategory_pos"'.$chgstr.'>';
 9162:                     for (my $k=0; $k<=$maxnum; $k++) {
 9163:                         my $vpos = $k+1;
 9164:                         my $selstr;
 9165:                         if ($k == $numtop) {
 9166:                             $selstr = ' selected="selected" ';
 9167:                         }
 9168:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 9169:                     }
 9170:                     $datatable .= '</select></span></td><td colspan="2">'.&mt('Add category:').'&nbsp;'
 9171:                                   .'<input type="text" size="20" name="addcategory_name" value="" /></td>'
 9172:                                   .'</tr>'."\n";
 9173:                     $itemcount ++;
 9174:                     foreach my $default ('instcode','communities') {
 9175:                         if ((!grep(/^\Q$default\E$/,@{$cats[0]})) || ($cathash->{$default.'::0'} eq '')) {
 9176:                             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9177:                             my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','$lastidx'".');"';
 9178:                             $datatable .= '<tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr><tr '.$css_class.'><td>'.
 9179:                                           '<span class="LC_nobreak"><select name="'.$default.'_pos"'.$chgstr.'>';
 9180:                             for (my $k=0; $k<=$maxnum; $k++) {
 9181:                                 my $vpos = $k+1;
 9182:                                 my $selstr;
 9183:                                 if ($k == $maxnum) {
 9184:                                     $selstr = ' selected="selected" ';
 9185:                                 }
 9186:                                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 9187:                             }
 9188:                             $datatable .= '</select></span></td>'.
 9189:                                           '<td><span class="LC_nobreak">'.
 9190:                                           $default_names{$default}.'</span>';
 9191:                             if ($default eq 'instcode') {
 9192:                                 $datatable .= '<br /><span class="LC_nobreak">(' 
 9193:                                               .&mt('with institutional codes').')</span>';
 9194:                             }
 9195:                             $datatable .= '</td>'
 9196:                                           .'<td><span class="LC_nobreak"><label><input type="radio" name="'.$default.'" value="1" />'
 9197:                                           .&mt('Display').'</label>&nbsp;'
 9198:                                           .'<label><input type="radio" name="'.$default.'" value="0" checked="checked"/>'
 9199:                                           .&mt('Do not display').'</label></span></td></tr>';
 9200:                         }
 9201:                     }
 9202:                 }
 9203:             } else {
 9204:                 $datatable .= &initialize_categories($itemcount);
 9205:             }
 9206:         } else {
 9207:             $datatable .= '<tr><td class="LC_right_item">'.$hdritem->{'header'}->[1]->{'col2'}.'</td></tr>'
 9208:                           .&initialize_categories($itemcount);
 9209:         }
 9210:         $$rowtotal += $itemcount;
 9211:     }
 9212:     return $datatable;
 9213: }
 9214: 
 9215: sub print_serverstatuses {
 9216:     my ($dom,$settings,$rowtotal) = @_;
 9217:     my $datatable;
 9218:     my @pages = &serverstatus_pages();
 9219:     my (%namedaccess,%machineaccess);
 9220:     foreach my $type (@pages) {
 9221:         $namedaccess{$type} = '';
 9222:         $machineaccess{$type}= '';
 9223:     }
 9224:     if (ref($settings) eq 'HASH') {
 9225:         foreach my $type (@pages) {
 9226:             if (exists($settings->{$type})) {
 9227:                 if (ref($settings->{$type}) eq 'HASH') {
 9228:                     foreach my $key (keys(%{$settings->{$type}})) {
 9229:                         if ($key eq 'namedusers') {
 9230:                             $namedaccess{$type} = $settings->{$type}->{$key};
 9231:                         } elsif ($key eq 'machines') {
 9232:                             $machineaccess{$type} = $settings->{$type}->{$key};
 9233:                         }
 9234:                     }
 9235:                 }
 9236:             }
 9237:         }
 9238:     }
 9239:     my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
 9240:     my $rownum = 0;
 9241:     my $css_class;
 9242:     foreach my $type (@pages) {
 9243:         $rownum ++;
 9244:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 9245:         $datatable .= '<tr'.$css_class.'>'.
 9246:                       '<td><span class="LC_nobreak">'.
 9247:                       $titles->{$type}.'</span></td>'.
 9248:                       '<td class="LC_left_item">'.
 9249:                       '<input type="text" name="'.$type.'_namedusers" '.
 9250:                       'value="'.$namedaccess{$type}.'" size="30" /></td>'.
 9251:                       '<td class="LC_right_item">'.
 9252:                       '<span class="LC_nobreak">'.
 9253:                       '<input type="text" name="'.$type.'_machines" '.
 9254:                       'value="'.$machineaccess{$type}.'" size="10" />'.
 9255:                       '</span></td></tr>'."\n";
 9256:     }
 9257:     $$rowtotal += $rownum;
 9258:     return $datatable;
 9259: }
 9260: 
 9261: sub serverstatus_pages {
 9262:     return ('userstatus','lonstatus','loncron','server-status','codeversions',
 9263:             'checksums','clusterstatus','metadata_keywords','metadata_harvest',
 9264:             'takeoffline','takeonline','showenv','toggledebug','ping','domconf',
 9265:             'uniquecodes','diskusage','coursecatalog');
 9266: }
 9267: 
 9268: sub defaults_javascript {
 9269:     my ($settings) = @_;
 9270:     return unless (ref($settings) eq 'HASH');
 9271:     if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
 9272:         my $maxnum = scalar(@{$settings->{'inststatusorder'}});
 9273:         if ($maxnum eq '') {
 9274:             $maxnum = 0;
 9275:         }
 9276:         $maxnum ++;
 9277:         my $jstext = '    var inststatuses = Array('."'".join("','",@{$settings->{'inststatusorder'}})."'".');';  
 9278:         return <<"ENDSCRIPT";
 9279: <script type="text/javascript">
 9280: // <![CDATA[
 9281: function reorderTypes(form,caller) {
 9282:     var changedVal;
 9283: $jstext 
 9284:     var newpos = 'addinststatus_pos';
 9285:     var current = new Array;
 9286:     var maxh = $maxnum;
 9287:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 9288:     var oldVal;
 9289:     if (caller == newpos) {
 9290:         changedVal = newitemVal;
 9291:     } else {
 9292:         var curritem = 'inststatus_pos_'+caller;
 9293:         changedVal = form.elements[curritem].options[form.elements[curritem].selectedIndex].value;
 9294:         current[newitemVal] = newpos;
 9295:     }
 9296:     for (var i=0; i<inststatuses.length; i++) {
 9297:         if (inststatuses[i] != caller) {
 9298:             var elementName = 'inststatus_pos_'+inststatuses[i];
 9299:             if (form.elements[elementName]) {
 9300:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 9301:                 current[currVal] = elementName;
 9302:             }
 9303:         }
 9304:     }
 9305:     for (var j=0; j<maxh; j++) {
 9306:         if (current[j] == undefined) {
 9307:             oldVal = j;
 9308:         }
 9309:     }
 9310:     if (oldVal < changedVal) {
 9311:         for (var k=oldVal+1; k<=changedVal ; k++) {
 9312:            var elementName = current[k];
 9313:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 9314:         }
 9315:     } else {
 9316:         for (var k=changedVal; k<oldVal; k++) {
 9317:             var elementName = current[k];
 9318:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 9319:         }
 9320:     }
 9321:     return;
 9322: }
 9323: 
 9324: // ]]>
 9325: </script>
 9326: 
 9327: ENDSCRIPT
 9328:     }
 9329: }
 9330: 
 9331: sub passwords_javascript {
 9332:     my ($prefix) = @_;
 9333:     my %intalert;
 9334:     if ($prefix eq 'passwords') {
 9335:         %intalert = &Apache::lonlocal::texthash (
 9336:             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.',
 9337:             authcost => 'Warning: bcrypt encryption cost for internal authentication must be an integer.',
 9338:             passmin => 'Warning: minimum password length must be a positive integer greater than 6.',
 9339:             passmax => 'Warning: maximum password length must be a positive integer (or blank).',
 9340:             passnum => 'Warning: number of previous passwords to save must be a positive integer (or blank).',
 9341:         );
 9342:     } elsif ($prefix eq 'secrets') {
 9343:         %intalert = &Apache::lonlocal::texthash (
 9344:             passmin => 'Warning: minimum secret length must be a positive integer greater than 6.',
 9345:             passmax => 'Warning: maximum secret length must be a positive integer (or blank).',
 9346:         );
 9347:     }
 9348:     &js_escape(\%intalert);
 9349:     my $defmin = $Apache::lonnet::passwdmin;
 9350:     my $intauthjs;
 9351:     if ($prefix eq 'passwords') { $intauthjs = <<"ENDSCRIPT";
 9352: 
 9353: function warnIntAuth(field) {
 9354:     if (field.name == 'intauth_check') {
 9355:         if (field.value == '2') {
 9356:             alert('$intalert{authcheck}');
 9357:         }
 9358:     }
 9359:     if (field.name == 'intauth_cost') {
 9360:         field.value.replace(/\s/g,'');
 9361:         if (field.value != '') {
 9362:             var regexdigit=/^\\d+\$/;
 9363:             if (!regexdigit.test(field.value)) {
 9364:                 alert('$intalert{authcost}');
 9365:             }
 9366:         }
 9367:     }
 9368:     return;
 9369: }
 9370: 
 9371: ENDSCRIPT
 9372: 
 9373:      }
 9374: 
 9375:      $intauthjs .= <<"ENDSCRIPT";
 9376: 
 9377: function warnInt$prefix(field) {
 9378:     field.value.replace(/^\s+/,'');
 9379:     field.value.replace(/\s+\$/,'');
 9380:     var regexdigit=/^\\d+\$/;
 9381:     if (field.name == '${prefix}_min') {
 9382:         if (field.value == '') {
 9383:             alert('$intalert{passmin}');
 9384:             field.value = '$defmin';
 9385:         } else {
 9386:             if (!regexdigit.test(field.value)) {
 9387:                 alert('$intalert{passmin}');
 9388:                 field.value = '$defmin';
 9389:             }
 9390:             var minval = parseInt(field.value,10);
 9391:             if (minval < $defmin) {
 9392:                 alert('$intalert{passmin}');
 9393:                 field.value = '$defmin';
 9394:             }
 9395:         }
 9396:     } else {
 9397:         if (field.value == '0') {
 9398:             field.value = '';
 9399:         }
 9400:         if (field.value != '') {
 9401:             if (!regexdigit.test(field.value)) {
 9402:                 if (field.name == '${prefix}_max') {
 9403:                     alert('$intalert{passmax}');
 9404:                 } else {
 9405:                     if (field.name == '${prefix}_numsaved') {
 9406:                         alert('$intalert{passnum}');
 9407:                     }
 9408:                 }
 9409:                 field.value = '';
 9410:             }
 9411:         }
 9412:     }
 9413:     return;
 9414: }
 9415: 
 9416: ENDSCRIPT
 9417:     return &Apache::lonhtmlcommon::scripttag($intauthjs);
 9418: }
 9419: 
 9420: sub coursecategories_javascript {
 9421:     my ($settings) = @_;
 9422:     my ($output,$jstext,$cathash);
 9423:     if (ref($settings) eq 'HASH') {
 9424:         $cathash = $settings->{'cats'};
 9425:     }
 9426:     if (ref($cathash) eq 'HASH') {
 9427:         my (@cats,@jsarray,%idx);
 9428:         &Apache::loncommon::gather_categories($cathash,\@cats,\%idx,\@jsarray);
 9429:         if (@jsarray > 0) {
 9430:             $jstext = '    var categories = Array('.scalar(@jsarray).');'."\n";
 9431:             for (my $i=0; $i<@jsarray; $i++) {
 9432:                 if (ref($jsarray[$i]) eq 'ARRAY') {
 9433:                     my $catstr = join('","',@{$jsarray[$i]});
 9434:                     $jstext .= '    categories['.$i.'] = Array("'.$catstr.'");'."\n";
 9435:                 }
 9436:             }
 9437:         }
 9438:     } else {
 9439:         $jstext  = '    var categories = Array(1);'."\n".
 9440:                    '    categories[0] = Array("instcode_pos");'."\n"; 
 9441:     }
 9442:     my $instcode_reserved = &mt('The name: [_1] is a reserved category.','"instcode"');
 9443:     my $communities_reserved = &mt('The name: [_1] is a reserved category.','"communities"');
 9444:     my $choose_again = "\n".&mt('Please use a different name for the new top level category.'); 
 9445:     &js_escape(\$instcode_reserved);
 9446:     &js_escape(\$communities_reserved);
 9447:     &js_escape(\$choose_again);
 9448:     $output = <<"ENDSCRIPT";
 9449: <script type="text/javascript">
 9450: // <![CDATA[
 9451: function reorderCats(form,parent,item,idx) {
 9452:     var changedVal;
 9453: $jstext
 9454:     var newpos = 'addcategory_pos';
 9455:     if (parent == '') {
 9456:         var has_instcode = 0;
 9457:         var maxtop = categories[idx].length;
 9458:         for (var j=0; j<maxtop; j++) {
 9459:             if (categories[idx][j] == 'instcode::0') {
 9460:                 has_instcode == 1;
 9461:             }
 9462:         }
 9463:         if (has_instcode == 0) {
 9464:             categories[idx][maxtop] = 'instcode_pos';
 9465:         }
 9466:     } else {
 9467:         newpos += '_'+parent;
 9468:     }
 9469:     var maxh = 1 + categories[idx].length;
 9470:     var current = new Array;
 9471:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 9472:     if (item == newpos) {
 9473:         changedVal = newitemVal;
 9474:     } else {
 9475:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 9476:         current[newitemVal] = newpos;
 9477:     }
 9478:     for (var i=0; i<categories[idx].length; i++) {
 9479:         var elementName = categories[idx][i];
 9480:         if (elementName != item) {
 9481:             if (form.elements[elementName]) {
 9482:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 9483:                 current[currVal] = elementName;
 9484:             }
 9485:         }
 9486:     }
 9487:     var oldVal;
 9488:     for (var j=0; j<maxh; j++) {
 9489:         if (current[j] == undefined) {
 9490:             oldVal = j;
 9491:         }
 9492:     }
 9493:     if (oldVal < changedVal) {
 9494:         for (var k=oldVal+1; k<=changedVal ; k++) {
 9495:            var elementName = current[k];
 9496:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 9497:         }
 9498:     } else {
 9499:         for (var k=changedVal; k<oldVal; k++) {
 9500:             var elementName = current[k];
 9501:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 9502:         }
 9503:     }
 9504:     return;
 9505: }
 9506: 
 9507: function categoryCheck(form) {
 9508:     if (form.elements['addcategory_name'].value == 'instcode') {
 9509:         alert('$instcode_reserved\\n$choose_again');
 9510:         return false;
 9511:     }
 9512:     if (form.elements['addcategory_name'].value == 'communities') {
 9513:         alert('$communities_reserved\\n$choose_again');
 9514:         return false;
 9515:     }
 9516:     return true;
 9517: }
 9518: 
 9519: // ]]>
 9520: </script>
 9521: 
 9522: ENDSCRIPT
 9523:     return $output;
 9524: }
 9525: 
 9526: sub initialize_categories {
 9527:     my ($itemcount) = @_;
 9528:     my ($datatable,$css_class,$chgstr);
 9529:     my %default_names = &Apache::lonlocal::texthash (
 9530:                       instcode    => 'Official courses (with institutional codes)',
 9531:                       communities => 'Communities',
 9532:                         );
 9533:     my $select0 = ' selected="selected"';
 9534:     my $select1 = '';
 9535:     foreach my $default ('instcode','communities') {
 9536:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9537:         $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','0'".');"';
 9538:         if ($default eq 'communities') {
 9539:             $select1 = $select0;
 9540:             $select0 = '';
 9541:         }
 9542:         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 9543:                      .'<select name="'.$default.'_pos">'
 9544:                      .'<option value="0"'.$select0.'>1</option>'
 9545:                      .'<option value="1"'.$select1.'>2</option>'
 9546:                      .'<option value="2">3</option></select>&nbsp;'
 9547:                      .$default_names{$default}
 9548:                      .'</span></td><td><span class="LC_nobreak">'
 9549:                      .'<label><input type="radio" name="'.$default.'" value="1" checked="checked" />'
 9550:                      .&mt('Display').'</label>&nbsp;<label>'
 9551:                      .'<input type="radio" name="'.$default.'" value="0" />'.&mt('Do not display')
 9552:                  .'</label></span></td></tr>';
 9553:         $itemcount ++;
 9554:     }
 9555:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9556:     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','0'".');"';
 9557:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 9558:                   .'<select name="addcategory_pos"'.$chgstr.'>'
 9559:                   .'<option value="0">1</option>'
 9560:                   .'<option value="1">2</option>'
 9561:                   .'<option value="2" selected="selected">3</option></select>&nbsp;'
 9562:                   .&mt('Add category').'</span></td><td><span class="LC_nobreak">'.&mt('Name:')
 9563:                   .'&nbsp;<input type="text" size="20" name="addcategory_name" value="" /></span>'
 9564:                   .'</td></tr>';
 9565:     return $datatable;
 9566: }
 9567: 
 9568: sub build_category_rows {
 9569:     my ($itemcount,$cats,$depth,$parent,$path,$idx) = @_;
 9570:     my ($text,$name,$item,$chgstr);
 9571:     if (ref($cats) eq 'ARRAY') {
 9572:         my $maxdepth = scalar(@{$cats});
 9573:         if (ref($cats->[$depth]) eq 'HASH') {
 9574:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
 9575:                 my $numchildren = @{$cats->[$depth]{$parent}};
 9576:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9577:                 $text .= '<td><table class="LC_data_table">';
 9578:                 my ($idxnum,$parent_name,$parent_item);
 9579:                 my $higher = $depth - 1;
 9580:                 if ($higher == 0) {
 9581:                     $parent_name = &escape($parent).'::'.$higher;
 9582:                 } else {
 9583:                     if (ref($path) eq 'ARRAY') {
 9584:                         $parent_name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
 9585:                     }
 9586:                 }
 9587:                 $parent_item = 'addcategory_pos_'.$parent_name;
 9588:                 for (my $j=0; $j<=$numchildren; $j++) {
 9589:                     if ($j < $numchildren) {
 9590:                         $name = $cats->[$depth]{$parent}[$j];
 9591:                         $item = &escape($name).':'.&escape($parent).':'.$depth;
 9592:                         $idxnum = $idx->{$item};
 9593:                     } else {
 9594:                         $name = $parent_name;
 9595:                         $item = $parent_item;
 9596:                     }
 9597:                     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'$parent_name','$item','$idxnum'".');"';
 9598:                     $text .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="'.$item.'"'.$chgstr.'>';
 9599:                     for (my $i=0; $i<=$numchildren; $i++) {
 9600:                         my $vpos = $i+1;
 9601:                         my $selstr;
 9602:                         if ($j == $i) {
 9603:                             $selstr = ' selected="selected" ';
 9604:                         }
 9605:                         $text .= '<option value="'.$i.'"'.$selstr.'>'.$vpos.'</option>';
 9606:                     }
 9607:                     $text .= '</select>&nbsp;';
 9608:                     if ($j < $numchildren) {
 9609:                         my $deeper = $depth+1;
 9610:                         $text .= $name.'&nbsp;'
 9611:                                  .'<label><input type="checkbox" name="deletecategory" value="'
 9612:                                  .$item.'" />'.&mt('Delete').'</label></span></td><td>';
 9613:                         if(ref($path) eq 'ARRAY') {
 9614:                             push(@{$path},$name);
 9615:                             $text .= &build_category_rows($itemcount,$cats,$deeper,$name,$path,$idx);
 9616:                             pop(@{$path});
 9617:                         }
 9618:                     } else {
 9619:                         $text .= &mt('Add subcategory:').'&nbsp;</span><input type="text" size="20" name="addcategory_name_';
 9620:                         if ($j == $numchildren) {
 9621:                             $text .= $name;
 9622:                         } else {
 9623:                             $text .= $item;
 9624:                         }
 9625:                         $text .= '" value="" />';
 9626:                     }
 9627:                     $text .= '</td></tr>';
 9628:                 }
 9629:                 $text .= '</table></td>';
 9630:             } else {
 9631:                 my $higher = $depth-1;
 9632:                 if ($higher == 0) {
 9633:                     $name = &escape($parent).'::'.$higher;
 9634:                 } else {
 9635:                     if (ref($path) eq 'ARRAY') {
 9636:                         $name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
 9637:                     }
 9638:                 }
 9639:                 my $colspan;
 9640:                 if ($parent ne 'instcode') {
 9641:                     $colspan = $maxdepth - $depth - 1;
 9642:                     $text .= '<td colspan="'.$colspan.'">'.&mt('Add subcategory:').'<input type="text" size="20" name="subcat_'.$name.'" value="" /></td>';
 9643:                 }
 9644:             }
 9645:         }
 9646:     }
 9647:     return $text;
 9648: }
 9649: 
 9650: sub modifiable_userdata_row {
 9651:     my ($context,$item,$settings,$numinrow,$rowcount,$usertypes,$fieldsref,$titlesref,
 9652:         $rowid,$customcss,$rowstyle) = @_;
 9653:     my ($role,$rolename,$statustype);
 9654:     $role = $item;
 9655:     if ($context eq 'cancreate') {
 9656:         if ($item =~ /^(emailusername)_(.+)$/) {
 9657:             $role = $1;
 9658:             $statustype = $2;
 9659:             if (ref($usertypes) eq 'HASH') {
 9660:                 if ($usertypes->{$statustype}) {
 9661:                     $rolename = &mt('Data provided by [_1]',$usertypes->{$statustype});
 9662:                 } else {
 9663:                     $rolename = &mt('Data provided by user');
 9664:                 }
 9665:             }
 9666:         }
 9667:     } elsif ($context eq 'selfcreate') {
 9668:         if (ref($usertypes) eq 'HASH') {
 9669:             $rolename = $usertypes->{$role};
 9670:         } else {
 9671:             $rolename = $role;
 9672:         }
 9673:     } else {
 9674:         if ($role eq 'cr') {
 9675:             $rolename = &mt('Custom role');
 9676:         } else {
 9677:             $rolename = &Apache::lonnet::plaintext($role);
 9678:         }
 9679:     }
 9680:     my (@fields,%fieldtitles);
 9681:     if (ref($fieldsref) eq 'ARRAY') {
 9682:         @fields = @{$fieldsref};
 9683:     } else {
 9684:         @fields = ('lastname','firstname','middlename','generation',
 9685:                    'permanentemail','id');
 9686:     }
 9687:     if ((ref($titlesref) eq 'HASH')) {
 9688:         %fieldtitles = %{$titlesref};
 9689:     } else {
 9690:         %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 9691:     }
 9692:     my $output;
 9693:     my $css_class;
 9694:     if ($rowcount%2) {
 9695:         $css_class = 'LC_odd_row';
 9696:     }
 9697:     if ($customcss) {
 9698:         $css_class .= " $customcss";
 9699:     }
 9700:     $css_class =~ s/^\s+//;
 9701:     if ($css_class) {
 9702:         $css_class = ' class="'.$css_class.'"';
 9703:     }
 9704:     if ($rowstyle) {
 9705:         $css_class .= ' style="'.$rowstyle.'"';
 9706:     }
 9707:     if ($rowid) {
 9708:         $rowid = ' id="'.$rowid.'"';
 9709:     }
 9710: 
 9711:     $output = '<tr '.$css_class.$rowid.'>'.
 9712:               '<td><span class="LC_nobreak">'.$rolename.'</span></td>'.
 9713:               '<td class="LC_left_item" colspan="2"><table>';
 9714:     my $rem;
 9715:     my %checks;
 9716:     if (ref($settings) eq 'HASH') {
 9717:         if (ref($settings->{$context}) eq 'HASH') {
 9718:             if (ref($settings->{$context}->{$role}) eq 'HASH') {
 9719:                 my $hashref = $settings->{$context}->{$role};
 9720:                 if ($role eq 'emailusername') {
 9721:                     if ($statustype) {
 9722:                         if (ref($settings->{$context}->{$role}->{$statustype}) eq 'HASH') {
 9723:                             $hashref = $settings->{$context}->{$role}->{$statustype};
 9724:                             if (ref($hashref) eq 'HASH') { 
 9725:                                 foreach my $field (@fields) {
 9726:                                     if ($hashref->{$field}) {
 9727:                                         $checks{$field} = $hashref->{$field};
 9728:                                     }
 9729:                                 }
 9730:                             }
 9731:                         }
 9732:                     }
 9733:                 } else {
 9734:                     if (ref($hashref) eq 'HASH') {
 9735:                         foreach my $field (@fields) {
 9736:                             if ($hashref->{$field}) {
 9737:                                 $checks{$field} = ' checked="checked" ';
 9738:                             }
 9739:                         }
 9740:                     }
 9741:                 }
 9742:             }
 9743:         }
 9744:     }
 9745: 
 9746:     my $total = scalar(@fields);
 9747:     for (my $i=0; $i<$total; $i++) {
 9748:         $rem = $i%($numinrow);
 9749:         if ($rem == 0) {
 9750:             if ($i > 0) {
 9751:                 $output .= '</tr>';
 9752:             }
 9753:             $output .= '<tr>';
 9754:         }
 9755:         my $check = ' ';
 9756:         unless ($role eq 'emailusername') {
 9757:             if (exists($checks{$fields[$i]})) {
 9758:                 $check = $checks{$fields[$i]};
 9759:             } else {
 9760:                 if ($role eq 'st') {
 9761:                     if (ref($settings) ne 'HASH') {
 9762:                         $check = ' checked="checked" '; 
 9763:                     }
 9764:                 }
 9765:             }
 9766:         }
 9767:         $output .= '<td class="LC_left_item">'.
 9768:                    '<span class="LC_nobreak">';
 9769:         if ($role eq 'emailusername') {
 9770:             unless ($checks{$fields[$i]} =~ /^(required|optional)$/) {
 9771:                 $checks{$fields[$i]} = 'omit';
 9772:             }
 9773:             foreach my $option ('required','optional','omit') {
 9774:                 my $checked='';
 9775:                 if ($checks{$fields[$i]} eq $option) {
 9776:                     $checked='checked="checked" ';
 9777:                 }
 9778:                 $output .= '<label>'.
 9779:                            '<input type="radio" name="canmodify_'.$item.'_'.$fields[$i].'" value="'.$option.'" '.$checked.'/>'.
 9780:                            &mt($option).'</label>'.('&nbsp;' x2);
 9781:             }
 9782:             $output .= '<i>'.$fieldtitles{$fields[$i]}.'</i>';
 9783:         } else {
 9784:             $output .= '<label>'.
 9785:                        '<input type="checkbox" name="canmodify_'.$role.'" '.
 9786:                        'value="'.$fields[$i].'"'.$check.'/>'.$fieldtitles{$fields[$i]}.
 9787:                        '</label>';
 9788:         }
 9789:         $output .= '</span></td>';
 9790:     }
 9791:     $rem = $total%$numinrow;
 9792:     my $colsleft;
 9793:     if ($rem) {
 9794:         $colsleft = $numinrow - $rem;
 9795:     }
 9796:     if ($colsleft > 1) {
 9797:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 9798:                    '&nbsp;</td>';
 9799:     } elsif ($colsleft == 1) {
 9800:         $output .= '<td class="LC_left_item">&nbsp;</td>';
 9801:     }
 9802:     $output .= '</tr></table></td></tr>';
 9803:     return $output;
 9804: }
 9805: 
 9806: sub insttypes_row {
 9807:     my ($settings,$types,$usertypes,$dom,$numinrow,$othertitle,$context,$rowtotal,$onclick,
 9808:         $customcss,$rowstyle) = @_;
 9809:     my %lt = &Apache::lonlocal::texthash (
 9810:                       cansearch => 'Users allowed to search',
 9811:                       statustocreate => 'Institutional affiliation(s) able to create own account (login/SSO)',
 9812:                       lockablenames => 'User preference to lock name',
 9813:                       selfassign    => 'Self-reportable affiliations',
 9814:                       overrides     => "Override domain's helpdesk settings based on requester's affiliation",
 9815:              );
 9816:     my $showdom;
 9817:     if ($context eq 'cansearch') {
 9818:         $showdom = ' ('.$dom.')';
 9819:     }
 9820:     my $class = 'LC_left_item';
 9821:     if ($context eq 'statustocreate') {
 9822:         $class = 'LC_right_item';
 9823:     }
 9824:     my $css_class;
 9825:     if ($$rowtotal%2) {
 9826:         $css_class = 'LC_odd_row';
 9827:     }
 9828:     if ($customcss) {
 9829:         $css_class .= ' '.$customcss;
 9830:     }
 9831:     $css_class =~ s/^\s+//;
 9832:     if ($css_class) {
 9833:         $css_class = ' class="'.$css_class.'"';
 9834:     }
 9835:     if ($rowstyle) {
 9836:         $css_class .= ' style="'.$rowstyle.'"';
 9837:     }
 9838:     if ($onclick) {
 9839:         $onclick = 'onclick="'.$onclick.'" ';
 9840:     }
 9841:     my $output = '<tr'.$css_class.'>'.
 9842:                  '<td>'.$lt{$context}.$showdom.
 9843:                  '</td><td class="'.$class.'" colspan="2"><table>';
 9844:     my $rem;
 9845:     if (ref($types) eq 'ARRAY') {
 9846:         for (my $i=0; $i<@{$types}; $i++) {
 9847:             if (defined($usertypes->{$types->[$i]})) {
 9848:                 my $rem = $i%($numinrow);
 9849:                 if ($rem == 0) {
 9850:                     if ($i > 0) {
 9851:                         $output .= '</tr>';
 9852:                     }
 9853:                     $output .= '<tr>';
 9854:                 }
 9855:                 my $check = ' ';
 9856:                 if (ref($settings) eq 'HASH') {
 9857:                     if (ref($settings->{$context}) eq 'ARRAY') {
 9858:                         if (grep(/^\Q$types->[$i]\E$/,@{$settings->{$context}})) {
 9859:                             $check = ' checked="checked" ';
 9860:                         }
 9861:                     } elsif (ref($settings->{$context}) eq 'HASH') {
 9862:                         if (ref($settings->{$context}->{$types->[$i]}) eq 'HASH') {
 9863:                             $check = ' checked="checked" ';
 9864:                         }
 9865:                     } elsif ($context eq 'statustocreate') {
 9866:                         $check = ' checked="checked" ';
 9867:                     }
 9868:                 }
 9869:                 $output .= '<td class="LC_left_item">'.
 9870:                            '<span class="LC_nobreak"><label>'.
 9871:                            '<input type="checkbox" name="'.$context.'" '.
 9872:                            'value="'.$types->[$i].'"'.$check.$onclick.'/>'.
 9873:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 9874:             }
 9875:         }
 9876:         $rem = @{$types}%($numinrow);
 9877:     }
 9878:     my $colsleft = $numinrow - $rem;
 9879:     if ($context eq 'overrides') {
 9880:         if ($colsleft > 1) {
 9881:             $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 9882:         } else {
 9883:             $output .= '<td class="LC_left_item">';
 9884:         }
 9885:         $output .= '&nbsp;';
 9886:     } else {
 9887:         if ($rem == 0) {
 9888:             $output .= '<tr>';
 9889:         }
 9890:         if ($colsleft > 1) {
 9891:             $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 9892:         } else {
 9893:             $output .= '<td class="LC_left_item">';
 9894:         }
 9895:         my $defcheck = ' ';
 9896:         if (ref($settings) eq 'HASH') {  
 9897:             if (ref($settings->{$context}) eq 'ARRAY') {
 9898:                 if (grep(/^default$/,@{$settings->{$context}})) {
 9899:                     $defcheck = ' checked="checked" ';
 9900:                 }
 9901:             } elsif ($context eq 'statustocreate') {
 9902:                 $defcheck = ' checked="checked" ';
 9903:             }
 9904:         }
 9905:         $output .= '<span class="LC_nobreak"><label>'.
 9906:                    '<input type="checkbox" name="'.$context.'" '.
 9907:                    'value="default"'.$defcheck.$onclick.' />'.
 9908:                    $othertitle.'</label></span>';
 9909:     }
 9910:     $output .= '</td></tr></table></td></tr>';
 9911:     return $output;
 9912: }
 9913: 
 9914: sub sorted_searchtitles {
 9915:     my %searchtitles = &Apache::lonlocal::texthash(
 9916:                          'uname' => 'username',
 9917:                          'lastname' => 'last name',
 9918:                          'lastfirst' => 'last name, first name',
 9919:                      );
 9920:     my @titleorder = ('uname','lastname','lastfirst');
 9921:     return (\%searchtitles,\@titleorder);
 9922: }
 9923: 
 9924: sub sorted_searchtypes {
 9925:     my %srchtypes_desc = (
 9926:                            exact    => 'is exact match',
 9927:                            contains => 'contains ..',
 9928:                            begins   => 'begins with ..',
 9929:                          );
 9930:     my @srchtypeorder = ('exact','begins','contains');
 9931:     return (\%srchtypes_desc,\@srchtypeorder);
 9932: }
 9933: 
 9934: sub usertype_update_row {
 9935:     my ($settings,$usertypes,$fieldtitles,$fields,$types,$rownums) = @_;
 9936:     my $datatable;
 9937:     my $numinrow = 4;
 9938:     foreach my $type (@{$types}) {
 9939:         if (defined($usertypes->{$type})) {
 9940:             $$rownums ++;
 9941:             my $css_class = $$rownums%2?' class="LC_odd_row"':'';
 9942:             $datatable .= '<tr'.$css_class.'><td>'.$usertypes->{$type}.
 9943:                           '</td><td class="LC_left_item"><table>';
 9944:             for (my $i=0; $i<@{$fields}; $i++) {
 9945:                 my $rem = $i%($numinrow);
 9946:                 if ($rem == 0) {
 9947:                     if ($i > 0) {
 9948:                         $datatable .= '</tr>';
 9949:                     }
 9950:                     $datatable .= '<tr>';
 9951:                 }
 9952:                 my $check = ' ';
 9953:                 if (ref($settings) eq 'HASH') {
 9954:                     if (ref($settings->{'fields'}) eq 'HASH') {
 9955:                         if (ref($settings->{'fields'}{$type}) eq 'ARRAY') {
 9956:                             if (grep(/^\Q$fields->[$i]\E$/,@{$settings->{'fields'}{$type}})) {
 9957:                                 $check = ' checked="checked" ';
 9958:                             }
 9959:                         }
 9960:                     }
 9961:                 }
 9962: 
 9963:                 if ($i == @{$fields}-1) {
 9964:                     my $colsleft = $numinrow - $rem;
 9965:                     if ($colsleft > 1) {
 9966:                         $datatable .= '<td colspan="'.$colsleft.'">';
 9967:                     } else {
 9968:                         $datatable .= '<td>';
 9969:                     }
 9970:                 } else {
 9971:                     $datatable .= '<td>';
 9972:                 }
 9973:                 $datatable .= '<span class="LC_nobreak"><label>'.
 9974:                               '<input type="checkbox" name="updateable_'.$type.
 9975:                               '_'.$fields->[$i].'" value="1"'.$check.'/>'.
 9976:                               $fieldtitles->{$fields->[$i]}.'</label></span></td>';
 9977:             }
 9978:             $datatable .= '</tr></table></td></tr>';
 9979:         }
 9980:     }
 9981:     return $datatable;
 9982: }
 9983: 
 9984: sub modify_login {
 9985:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
 9986:     my ($resulttext,$errors,$colchgtext,%changes,%colchanges,%newfile,%newurl,
 9987:         %curr_loginvia,%loginhash,@currlangs,@newlangs,$addedfile,%title,@offon,
 9988:         %currsaml,%saml,%samltext,%samlimg,%samlalt,%samlurl,%samltitle,%samlnotsso);
 9989:     %title = ( coursecatalog => 'Display course catalog',
 9990:                adminmail => 'Display administrator E-mail address',
 9991:                helpdesk  => 'Display "Contact Helpdesk" link',
 9992:                newuser => 'Link for visitors to create a user account',
 9993:                loginheader => 'Log-in box header',
 9994:                saml => 'Dual SSO and non-SSO login');
 9995:     @offon = ('off','on');
 9996:     if (ref($domconfig{login}) eq 'HASH') {
 9997:         if (ref($domconfig{login}{loginvia}) eq 'HASH') {
 9998:             foreach my $lonhost (keys(%{$domconfig{login}{loginvia}})) {
 9999:                 $curr_loginvia{$lonhost} = $domconfig{login}{loginvia}{$lonhost};
10000:             }
10001:         }
10002:         if (ref($domconfig{login}{'saml'}) eq 'HASH') {
10003:             foreach my $lonhost (keys(%{$domconfig{login}{'saml'}})) {
10004:                 if (ref($domconfig{login}{'saml'}{$lonhost}) eq 'HASH') {
10005:                     $currsaml{$lonhost} = $domconfig{login}{'saml'}{$lonhost};
10006:                     $saml{$lonhost} = 1;
10007:                     $samltext{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'text'};
10008:                     $samlurl{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'url'};
10009:                     $samlalt{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'alt'};
10010:                     $samlimg{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'img'};
10011:                     $samltitle{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'title'};
10012:                     $samlnotsso{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'notsso'};
10013:                 }
10014:             }
10015:         }
10016:     }
10017:     ($errors,%colchanges) = &modify_colors($r,$dom,$confname,['login'],
10018:                                            \%domconfig,\%loginhash);
10019:     my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
10020:     foreach my $item (@toggles) {
10021:         $loginhash{login}{$item} = $env{'form.'.$item};
10022:     }
10023:     $loginhash{login}{loginheader} = $env{'form.loginheader'};
10024:     if (ref($colchanges{'login'}) eq 'HASH') {  
10025:         $colchgtext = &display_colorchgs($dom,\%colchanges,['login'],
10026:                                          \%loginhash);
10027:     }
10028: 
10029:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
10030:     my %domservers = &Apache::lonnet::get_servers($dom);
10031:     my @loginvia_attribs = ('serverpath','custompath','exempt');
10032:     if (keys(%servers) > 1) {
10033:         foreach my $lonhost (keys(%servers)) {
10034:             next if ($env{'form.'.$lonhost.'_server'} eq $lonhost);
10035:             if (ref($curr_loginvia{$lonhost}) eq 'HASH') {
10036:                 if ($env{'form.'.$lonhost.'_server'} eq $curr_loginvia{$lonhost}{'server'}) {
10037:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $curr_loginvia{$lonhost}{'server'};
10038:                 } elsif ($curr_loginvia{$lonhost}{'server'} ne '') {
10039:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
10040:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
10041:                         $changes{'loginvia'}{$lonhost} = 1;
10042:                     } else {
10043:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = '';
10044:                         $changes{'loginvia'}{$lonhost} = 1;
10045:                     }
10046:                 } else {
10047:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
10048:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
10049:                         $changes{'loginvia'}{$lonhost} = 1;
10050:                     }
10051:                 }
10052:                 if ($loginhash{login}{loginvia}{$lonhost}{'server'} eq '') {
10053:                     foreach my $item (@loginvia_attribs) {
10054:                         $loginhash{login}{loginvia}{$lonhost}{$item} = '';
10055:                     }
10056:                 } else {
10057:                     foreach my $item (@loginvia_attribs) {
10058:                         my $new = $env{'form.'.$lonhost.'_'.$item};
10059:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
10060:                             $env{'form.'.$lonhost.'_custompath'} =~ s/\s+//g;
10061:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
10062:                                 $new = '/';
10063:                             }
10064:                         }
10065:                         if (($item eq 'custompath') && 
10066:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
10067:                             $new = '';
10068:                         }
10069:                         if ($new ne $curr_loginvia{$lonhost}{$item}) {
10070:                             $changes{'loginvia'}{$lonhost} = 1;
10071:                         }
10072:                         if ($item eq 'exempt') {
10073:                             $new = &check_exempt_addresses($new);
10074:                         }
10075:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
10076:                     }
10077:                 }
10078:             } else {
10079:                 if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
10080:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
10081:                     $changes{'loginvia'}{$lonhost} = 1;
10082:                     foreach my $item (@loginvia_attribs) {
10083:                         my $new = $env{'form.'.$lonhost.'_'.$item};
10084:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
10085:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
10086:                                 $new = '/';
10087:                             }
10088:                         }
10089:                         if (($item eq 'custompath') && 
10090:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
10091:                             $new = '';
10092:                         }
10093:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
10094:                     }
10095:                 }
10096:             }
10097:         }
10098:     }
10099: 
10100:     my $servadm = $r->dir_config('lonAdmEMail');
10101:     my %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
10102:     if (ref($domconfig{'login'}) eq 'HASH') {
10103:         if (ref($domconfig{'login'}{'helpurl'}) eq 'HASH') {
10104:             foreach my $lang (sort(keys(%{$domconfig{'login'}{'helpurl'}}))) {
10105:                 if ($lang eq 'nolang') {
10106:                     push(@currlangs,$lang);
10107:                 } elsif (defined($langchoices{$lang})) {
10108:                     push(@currlangs,$lang);
10109:                 } else {
10110:                     next;
10111:                 }
10112:             }
10113:         }
10114:     }
10115:     my @delurls = &Apache::loncommon::get_env_multiple('form.loginhelpurl_del');
10116:     if (@currlangs > 0) {
10117:         foreach my $lang (@currlangs) {
10118:             if (grep(/^\Q$lang\E$/,@delurls)) {
10119:                 $changes{'helpurl'}{$lang} = 1;
10120:             } elsif ($env{'form.loginhelpurl_'.$lang.'.filename'}) {
10121:                 $changes{'helpurl'}{$lang} = 1;
10122:                 $newfile{$lang} = $env{'form.loginhelpurl_'.$lang.'.filename'};
10123:                 push(@newlangs,$lang);
10124:             } else {
10125:                 $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
10126:             }
10127:         }
10128:     }
10129:     unless (grep(/^nolang$/,@currlangs)) {
10130:         if ($env{'form.loginhelpurl_nolang.filename'}) {
10131:             $changes{'helpurl'}{'nolang'} = 1;
10132:             $newfile{'nolang'} = $env{'form.loginhelpurl_nolang.filename'};
10133:             push(@newlangs,'nolang');
10134:         }
10135:     }
10136:     if ($env{'form.loginhelpurl_add_lang'}) {
10137:         if ((defined($langchoices{$env{'form.loginhelpurl_add_lang'}})) &&
10138:             ($env{'form.loginhelpurl_add_file.filename'})) {
10139:             $newfile{$env{'form.loginhelpurl_add_lang'}} = $env{'form.loginhelpurl_add_file.filename'};
10140:             $addedfile = $env{'form.loginhelpurl_add_lang'};
10141:         }
10142:     }
10143:     if ((@newlangs > 0) || ($addedfile)) {
10144:         my $error;
10145:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
10146:         if ($configuserok eq 'ok') {
10147:             if ($switchserver) {
10148:                 $error = &mt("Upload of custom help file is not permitted to this server: [_1]",$switchserver);
10149:             } elsif ($author_ok eq 'ok') {
10150:                 my @allnew = @newlangs;
10151:                 if ($addedfile ne '') {
10152:                     push(@allnew,$addedfile);
10153:                 }
10154:                 foreach my $lang (@allnew) {
10155:                     my $formelem = 'loginhelpurl_'.$lang;
10156:                     if ($lang eq $env{'form.loginhelpurl_add_lang'}) {
10157:                         $formelem = 'loginhelpurl_add_file';
10158:                     }
10159:                     (my $result,$newurl{$lang}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
10160:                                                                "help/$lang",'','',$newfile{$lang});
10161:                     if ($result eq 'ok') {
10162:                         $loginhash{'login'}{'helpurl'}{$lang} = $newurl{$lang};
10163:                         $changes{'helpurl'}{$lang} = 1;
10164:                     } else {
10165:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$newfile{$lang},$result);
10166:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
10167:                         if ((grep(/^\Q$lang\E$/,@currlangs)) &&
10168:                             (!grep(/^\Q$lang\E$/,@delurls))) {
10169:                             $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
10170:                         }
10171:                     }
10172:                 }
10173:             } else {
10174:                 $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);
10175:             }
10176:         } else {
10177:             $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);
10178:         }
10179:         if ($error) {
10180:             &Apache::lonnet::logthis($error);
10181:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
10182:         }
10183:     }
10184: 
10185:     my (%currheadtagurls,%currexempt,@newhosts,%newheadtagurls,%possexempt);
10186:     if (ref($domconfig{'login'}) eq 'HASH') {
10187:         if (ref($domconfig{'login'}{'headtag'}) eq 'HASH') {
10188:             foreach my $lonhost (keys(%{$domconfig{'login'}{'headtag'}})) {
10189:                 if ($domservers{$lonhost}) {
10190:                     if (ref($domconfig{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
10191:                         $currheadtagurls{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'url'};
10192:                         $currexempt{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'exempt'};
10193:                     }
10194:                 }
10195:             }
10196:         }
10197:     }
10198:     my @delheadtagurls = &Apache::loncommon::get_env_multiple('form.loginheadtag_del');
10199:     foreach my $lonhost (sort(keys(%domservers))) {
10200:         if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
10201:             $changes{'headtag'}{$lonhost} = 1;
10202:         } else {
10203:             if ($env{'form.loginheadtagexempt_'.$lonhost}) {
10204:                 $possexempt{$lonhost} = &check_exempt_addresses($env{'form.loginheadtagexempt_'.$lonhost});
10205:             }
10206:             if ($env{'form.loginheadtag_'.$lonhost.'.filename'}) {
10207:                 push(@newhosts,$lonhost);
10208:             } elsif ($currheadtagurls{$lonhost}) {
10209:                 $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $currheadtagurls{$lonhost};
10210:                 if ($currexempt{$lonhost}) {
10211:                     if ((!exists($possexempt{$lonhost})) || ($possexempt{$lonhost} ne $currexempt{$lonhost})) {
10212:                         $changes{'headtag'}{$lonhost} = 1;
10213:                     }
10214:                 } elsif ($possexempt{$lonhost}) {
10215:                     $changes{'headtag'}{$lonhost} = 1;
10216:                 }
10217:                 if ($possexempt{$lonhost}) {
10218:                     $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
10219:                 }
10220:             }
10221:         }
10222:     }
10223:     if (@newhosts) {
10224:         my $error;
10225:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
10226:         if ($configuserok eq 'ok') {
10227:             if ($switchserver) {
10228:                 $error = &mt("Upload of custom markup is not permitted to this server: [_1]",$switchserver);
10229:             } elsif ($author_ok eq 'ok') {
10230:                 foreach my $lonhost (@newhosts) {
10231:                     my $formelem = 'loginheadtag_'.$lonhost;
10232:                     (my $result,$newheadtagurls{$lonhost}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
10233:                                                                           "login/headtag/$lonhost",'','',
10234:                                                                           $env{'form.loginheadtag_'.$lonhost.'.filename'});
10235:                     if ($result eq 'ok') {
10236:                         $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $newheadtagurls{$lonhost};
10237:                         $changes{'headtag'}{$lonhost} = 1;
10238:                         if ($possexempt{$lonhost}) {
10239:                             $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
10240:                         }
10241:                     } else {
10242:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",
10243:                                            $newheadtagurls{$lonhost},$result);
10244:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
10245:                         if ((grep(/^\Q$lonhost\E$/,keys(%currheadtagurls))) &&
10246:                             (!grep(/^\Q$lonhost\E$/,@delheadtagurls))) {
10247:                             $loginhash{'login'}{'headtag'}{$lonhost} = $currheadtagurls{$lonhost};
10248:                         }
10249:                     }
10250:                 }
10251:             } else {
10252:                 $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);
10253:             }
10254:         } else {
10255:             $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);
10256:         }
10257:         if ($error) {
10258:             &Apache::lonnet::logthis($error);
10259:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
10260:         }
10261:     }
10262:     my @delsamlimg = &Apache::loncommon::get_env_multiple('form.saml_img_del');
10263:     my @newsamlimgs;
10264:     foreach my $lonhost (keys(%domservers)) {
10265:         if ($env{'form.saml_'.$lonhost}) {
10266:             if ($env{'form.saml_img_'.$lonhost.'.filename'}) {
10267:                 push(@newsamlimgs,$lonhost);
10268:             }
10269:             foreach my $item ('text','alt','url','title','notsso') {
10270:                 $env{'form.saml_'.$item.'_'.$lonhost} =~ s/^\s+|\s+$//g;
10271:             }
10272:             if ($saml{$lonhost}) {
10273:                 if (grep(/^\Q$lonhost\E$/,@delsamlimg)) {
10274: #FIXME Need to obsolete published image
10275:                     delete($currsaml{$lonhost}{'img'});
10276:                     $changes{'saml'}{$lonhost} = 1;
10277:                 }
10278:                 if ($env{'form.saml_alt_'.$lonhost} ne $samlalt{$lonhost}) {
10279:                     $changes{'saml'}{$lonhost} = 1;
10280:                 }
10281:                 if ($env{'form.saml_text_'.$lonhost} ne $samltext{$lonhost}) {
10282:                     $changes{'saml'}{$lonhost} = 1;
10283:                 }
10284:                 if ($env{'form.saml_url_'.$lonhost} ne $samlurl{$lonhost}) {
10285:                     $changes{'saml'}{$lonhost} = 1;
10286:                 }
10287:                 if ($env{'form.saml_title_'.$lonhost} ne $samltitle{$lonhost}) {
10288:                     $changes{'saml'}{$lonhost} = 1;
10289:                 }
10290:                 if ($env{'form.saml_notsso_'.$lonhost} ne $samlnotsso{$lonhost}) {
10291:                     $changes{'saml'}{$lonhost} = 1;
10292:                 }
10293:             } else {
10294:                 $changes{'saml'}{$lonhost} = 1;
10295:             }
10296:             foreach my $item ('text','alt','url','title','notsso') {
10297:                 $currsaml{$lonhost}{$item} = $env{'form.saml_'.$item.'_'.$lonhost};
10298:             }
10299:         } else {
10300:             if ($saml{$lonhost}) {
10301:                 $changes{'saml'}{$lonhost} = 1;
10302:                 delete($currsaml{$lonhost});
10303:             }
10304:         }
10305:     }
10306:     foreach my $posshost (keys(%currsaml)) {
10307:         unless (exists($domservers{$posshost})) {
10308:             delete($currsaml{$posshost});
10309:         }
10310:     }
10311:     %{$loginhash{'login'}{'saml'}} = %currsaml;
10312:     if (@newsamlimgs) {
10313:         my $error;
10314:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
10315:         if ($configuserok eq 'ok') {
10316:             if ($switchserver) {
10317:                 $error = &mt("Upload of SSO Button Image is not permitted to this server: [_1].",$switchserver);
10318:             } elsif ($author_ok eq 'ok') {
10319:                 foreach my $lonhost (@newsamlimgs) {
10320:                     my $formelem = 'saml_img_'.$lonhost;
10321:                     my ($result,$imgurl) = &publishlogo($r,'upload',$formelem,$dom,$confname,
10322:                                                         "login/saml/$lonhost",'','',
10323:                                                         $env{'form.saml_img_'.$lonhost.'.filename'});
10324:                     if ($result eq 'ok') {
10325:                         $currsaml{$lonhost}{'img'} = $imgurl;
10326:                         $loginhash{'login'}{'saml'}{$lonhost}{'img'} = $imgurl;
10327:                         $changes{'saml'}{$lonhost} = 1;
10328:                     } else {
10329:                         my $puberror = &mt("Upload of SSO button image failed for [_1] because an error occurred publishing the file in RES space. Error was: [_2].",
10330:                                            $lonhost,$result);
10331:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
10332:                     }
10333:                 }
10334:             } else {
10335:                 $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);
10336:             }
10337:         } else {
10338:             $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);
10339:         }
10340:         if ($error) {
10341:             &Apache::lonnet::logthis($error);
10342:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
10343:         }
10344:     }
10345:     &process_captcha('login',\%changes,$loginhash{'login'},$domconfig{'login'});
10346: 
10347:     my $defaulthelpfile = '/adm/loginproblems.html';
10348:     my $defaulttext = &mt('Default in use');
10349: 
10350:     my $putresult = &Apache::lonnet::put_dom('configuration',\%loginhash,
10351:                                              $dom);
10352:     if ($putresult eq 'ok') {
10353:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
10354:         my %defaultchecked = (
10355:                     'coursecatalog' => 'on',
10356:                     'helpdesk'      => 'on',
10357:                     'adminmail'     => 'off',
10358:                     'newuser'       => 'off',
10359:         );
10360:         if (ref($domconfig{'login'}) eq 'HASH') {
10361:             foreach my $item (@toggles) {
10362:                 if ($defaultchecked{$item} eq 'on') { 
10363:                     if (($domconfig{'login'}{$item} eq '0') &&
10364:                         ($env{'form.'.$item} eq '1')) {
10365:                         $changes{$item} = 1;
10366:                     } elsif (($domconfig{'login'}{$item} eq '' ||
10367:                               $domconfig{'login'}{$item} eq '1') &&
10368:                              ($env{'form.'.$item} eq '0')) {
10369:                         $changes{$item} = 1;
10370:                     }
10371:                 } elsif ($defaultchecked{$item} eq 'off') {
10372:                     if (($domconfig{'login'}{$item} eq '1') &&
10373:                         ($env{'form.'.$item} eq '0')) {
10374:                         $changes{$item} = 1;
10375:                     } elsif (($domconfig{'login'}{$item} eq '' ||
10376:                               $domconfig{'login'}{$item} eq '0') &&
10377:                              ($env{'form.'.$item} eq '1')) {
10378:                         $changes{$item} = 1;
10379:                     }
10380:                 }
10381:             }
10382:         }
10383:         if (keys(%changes) > 0 || $colchgtext) {
10384:             &Apache::loncommon::devalidate_domconfig_cache($dom);
10385:             if (exists($changes{'saml'})) {
10386:                 my $hostid_in_use;
10387:                 my @hosts = &Apache::lonnet::current_machine_ids();
10388:                 if (@hosts > 1) {
10389:                     foreach my $hostid (@hosts) {
10390:                         if (&Apache::lonnet::host_domain($hostid) eq $dom) {
10391:                             $hostid_in_use = $hostid;
10392:                             last;
10393:                         }
10394:                     }
10395:                 } else {
10396:                     $hostid_in_use = $r->dir_config('lonHostID');
10397:                 }
10398:                 if (($hostid_in_use) &&
10399:                     (&Apache::lonnet::host_domain($hostid_in_use) eq $dom)) {
10400:                     &Apache::lonnet::devalidate_cache_new('samllanding',$hostid_in_use);
10401:                 }
10402:                 if (ref($lastactref) eq 'HASH') {
10403:                     if (ref($changes{'saml'}) eq 'HASH') {
10404:                         my %updates;
10405:                         map { $updates{$_} = 1; } keys(%{$changes{'saml'}});
10406:                         $lastactref->{'samllanding'} = \%updates;
10407:                     }
10408:                 }
10409:             }
10410:             if (ref($lastactref) eq 'HASH') {
10411:                 $lastactref->{'domainconfig'} = 1;
10412:             }
10413:             $resulttext = &mt('Changes made:').'<ul>';
10414:             foreach my $item (sort(keys(%changes))) {
10415:                 if ($item eq 'loginvia') {
10416:                     if (ref($changes{$item}) eq 'HASH') {
10417:                         $resulttext .= '<li>'.&mt('Log-in page availability:').'<ul>';
10418:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
10419:                             if (defined($servers{$loginhash{login}{loginvia}{$lonhost}{'server'}})) {
10420:                                 if (ref($loginhash{login}{loginvia}{$lonhost}) eq 'HASH') {
10421:                                     my $protocol = $Apache::lonnet::protocol{$env{'form.'.$lonhost.'_server'}};
10422:                                     $protocol = 'http' if ($protocol ne 'https');
10423:                                     my $target = $protocol.'://'.$servers{$env{'form.'.$lonhost.'_server'}};
10424: 
10425:                                     if ($loginhash{login}{loginvia}{$lonhost}{'serverpath'} eq 'custom') {
10426:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'custompath'};
10427:                                     } else {
10428:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'serverpath'}; 
10429:                                     }
10430:                                     $resulttext .= '<li>'.&mt('Server: [_1] log-in page redirects to [_2].',$servers{$lonhost},'<a href="'.$target.'">'.$target.'</a>');
10431:                                     if ($loginhash{login}{loginvia}{$lonhost}{'exempt'} ne '') {
10432:                                         $resulttext .= '&nbsp;'.&mt('No redirection for clients from following IPs:').'&nbsp;'.$loginhash{login}{loginvia}{$lonhost}{'exempt'};
10433:                                     }
10434:                                     $resulttext .= '</li>';
10435:                                 } else {
10436:                                     $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$lonhost).'</li>';
10437:                                 }
10438:                             } else {
10439:                                 $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$servers{$lonhost}).'</li>';
10440:                             }
10441:                         }
10442:                         $resulttext .= '</ul></li>';
10443:                     }
10444:                 } elsif ($item eq 'helpurl') {
10445:                     if (ref($changes{$item}) eq 'HASH') {
10446:                         foreach my $lang (sort(keys(%{$changes{$item}}))) {
10447:                             if (grep(/^\Q$lang\E$/,@delurls)) {
10448:                                 my ($chg,$link);
10449:                                 $link = &Apache::loncommon::modal_link($defaulthelpfile,$defaulttext,600,500);
10450:                                 if ($lang eq 'nolang') {
10451:                                     $chg = &mt('custom log-in help file removed for no preferred language; [_1]',$link);
10452:                                 } else {
10453:                                     $chg = &mt('custom log-in help file removed for specific language: [_1]; [_2]',$langchoices{$lang},$link);
10454:                                 }
10455:                                 $resulttext .= '<li>'.$chg.'</li>';
10456:                             } else {
10457:                                 my $chg;
10458:                                 if ($lang eq 'nolang') {
10459:                                     $chg = &mt('custom log-in help file for no preferred language');
10460:                                 } else {
10461:                                     $chg = &mt('custom log-in help file for specific language: [_1]',$langchoices{$lang});
10462:                                 }
10463:                                 $resulttext .= '<li>'.&Apache::loncommon::modal_link(
10464:                                                       $loginhash{'login'}{'helpurl'}{$lang}.
10465:                                                       '?inhibitmenu=yes',$chg,600,500).
10466:                                                '</li>';
10467:                             }
10468:                         }
10469:                     }
10470:                 } elsif ($item eq 'headtag') {
10471:                     if (ref($changes{$item}) eq 'HASH') {
10472:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
10473:                             if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
10474:                                 $resulttext .= '<li>'.&mt('custom markup file removed for [_1]',$domservers{$lonhost}).'</li>';
10475:                             } elsif (ref($loginhash{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
10476:                                 $resulttext .= '<li><a href="'.
10477:                                                "javascript:void(open('$loginhash{'login'}{'headtag'}{$lonhost}{'url'}?inhibitmenu=yes','Custom_HeadTag',
10478:                                                'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
10479:                                                '">'.&mt('custom markup').'</a> '.&mt('(for [_1])',$servers{$lonhost}).' ';
10480:                                 if ($possexempt{$lonhost}) {
10481:                                     $resulttext .= &mt('not included for client IP(s): [_1]',$possexempt{$lonhost});
10482:                                 } else {
10483:                                     $resulttext .= &mt('included for any client IP');
10484:                                 }
10485:                                 $resulttext .= '</li>';
10486:                             }
10487:                         }
10488:                     }
10489:                 } elsif ($item eq 'saml') {
10490:                     if (ref($changes{$item}) eq 'HASH') {
10491:                         my %notlt = (
10492:                                        text   => 'Text for log-in by SSO',
10493:                                        img    => 'SSO button image',
10494:                                        alt    => 'Alt text for button image',
10495:                                        url    => 'SSO URL',
10496:                                        title  => 'Tooltip for SSO link',
10497:                                        notsso => 'Text for non-SSO log-in',
10498:                                     );
10499:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
10500:                             if (ref($currsaml{$lonhost}) eq 'HASH') {
10501:                                 $resulttext .= '<li>'.&mt("$title{$item} in use for [_1]","<b>$lonhost</b>").
10502:                                                '<ul>';
10503:                                 foreach my $key ('text','img','alt','url','title','notsso') {
10504:                                     if ($currsaml{$lonhost}{$key} eq '') {
10505:                                         $resulttext .= '<li>'.&mt("$notlt{$key} not in use").'</li>';
10506:                                     } else {
10507:                                         my $value = "'$currsaml{$lonhost}{$key}'";
10508:                                         if ($key eq 'img') {
10509:                                             $value = '<img src="'.$currsaml{$lonhost}{$key}.'" />';
10510:                                         }
10511:                                         $resulttext .= '<li>'.&mt("$notlt{$key} set to: [_1]",
10512:                                                                   $value).'</li>';
10513:                                     }
10514:                                 }
10515:                                 $resulttext .= '</ul></li>';
10516:                             } else {
10517:                                 $resulttext .= '<li>'.&mt("$title{$item} not in use for [_1]",$lonhost).'</li>';
10518:                             }
10519:                         }
10520:                     }
10521:                 } elsif ($item eq 'captcha') {
10522:                     if (ref($loginhash{'login'}) eq 'HASH') {
10523:                         my $chgtxt;
10524:                         if ($loginhash{'login'}{$item} eq 'notused') {
10525:                             $chgtxt .= &mt('No CAPTCHA validation in use for helpdesk form.');
10526:                         } else {
10527:                             my %captchas = &captcha_phrases();
10528:                             if ($captchas{$loginhash{'login'}{$item}}) {
10529:                                 $chgtxt .= &mt("Validation for helpdesk form set to $captchas{$loginhash{'login'}{$item}}.");
10530:                             } else {
10531:                                 $chgtxt .= &mt('Validation for helpdesk form set to unknown type.');
10532:                             }
10533:                         }
10534:                         $resulttext .= '<li>'.$chgtxt.'</li>';
10535:                     }
10536:                 } elsif ($item eq 'recaptchakeys') {
10537:                     if (ref($loginhash{'login'}) eq 'HASH') {
10538:                         my ($privkey,$pubkey);
10539:                         if (ref($loginhash{'login'}{$item}) eq 'HASH') {
10540:                             $pubkey = $loginhash{'login'}{$item}{'public'};
10541:                             $privkey = $loginhash{'login'}{$item}{'private'};
10542:                         }
10543:                         my $chgtxt .= &mt('ReCAPTCHA keys changes').'<ul>';
10544:                         if (!$pubkey) {
10545:                             $chgtxt .= '<li>'.&mt('Public key deleted').'</li>';
10546:                         } else {
10547:                             $chgtxt .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
10548:                         }
10549:                         if (!$privkey) {
10550:                             $chgtxt .= '<li>'.&mt('Private key deleted').'</li>';
10551:                         } else {
10552:                             $chgtxt .= '<li>'.&mt('Private key set to [_1]',$privkey).'</li>';
10553:                         }
10554:                         $chgtxt .= '</ul>';
10555:                         $resulttext .= '<li>'.$chgtxt.'</li>';
10556:                     }
10557:                 } elsif ($item eq 'recaptchaversion') {
10558:                     if (ref($loginhash{'login'}) eq 'HASH') {
10559:                         if ($loginhash{'login'}{'captcha'} eq 'recaptcha') {
10560:                             $resulttext .= '<li>'.&mt('ReCAPTCHA for helpdesk form set to version [_1]',$loginhash{'login'}{'recaptchaversion'}).
10561:                                            '</li>';
10562:                         }
10563:                     }
10564:                 } else {
10565:                     $resulttext .= '<li>'.&mt("$title{$item} set to $offon[$env{'form.'.$item}]").'</li>';
10566:                 }
10567:             }
10568:             $resulttext .= $colchgtext.'</ul>';
10569:         } else {
10570:             $resulttext = &mt('No changes made to log-in page settings');
10571:         }
10572:     } else {
10573:         $resulttext = '<span class="LC_error">'.
10574: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
10575:     }
10576:     if ($errors) {
10577:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
10578:                        $errors.'</ul>';
10579:     }
10580:     return $resulttext;
10581: }
10582: 
10583: sub check_exempt_addresses {
10584:     my ($iplist) = @_;
10585:     $iplist =~ s/^\s+//;
10586:     $iplist =~ s/\s+$//;
10587:     my @poss_ips = split(/\s*[,:]\s*/,$iplist);
10588:     my (@okips,$new);
10589:     foreach my $ip (@poss_ips) {
10590:         if ($ip =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) {
10591:             if (($1 <= 255) && ($2 <= 255) && ($3 <= 255) && ($4 <= 255)) {
10592:                 push(@okips,$ip);
10593:             }
10594:         }
10595:     }
10596:     if (@okips > 0) {
10597:         $new = join(',',@okips);
10598:     } else {
10599:         $new = '';
10600:     }
10601:     return $new;
10602: }
10603: 
10604: sub color_font_choices {
10605:     my %choices =
10606:         &Apache::lonlocal::texthash (
10607:             img => "Header",
10608:             bgs => "Background colors",
10609:             links => "Link colors",
10610:             images => "Images",
10611:             font => "Font color",
10612:             fontmenu => "Font menu",
10613:             pgbg => "Page",
10614:             tabbg => "Header",
10615:             sidebg => "Border",
10616:             link => "Link",
10617:             alink => "Active link",
10618:             vlink => "Visited link",
10619:         );
10620:     return %choices;
10621: }
10622: 
10623: sub modify_ipaccess {
10624:     my ($dom,$lastactref,%domconfig) = @_;
10625:     my (@allpos,%changes,%confhash,$errors,$resulttext);
10626:     my (@items,%deletions,%itemids,@warnings);
10627:     my ($typeorder,$types) = &commblocktype_text();
10628:     if ($env{'form.ipaccess_add'}) {
10629:         my $name = $env{'form.ipaccess_name_add'};
10630:         my ($newid,$error) = &get_ipaccess_id($dom,$name);
10631:         if ($newid) {
10632:             $itemids{'add'} = $newid;
10633:             push(@items,'add');
10634:             $changes{$newid} = 1;
10635:         } else {
10636:             $error = &mt('Failed to acquire unique ID for new IP access control item');
10637:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
10638:         }
10639:     }
10640:     if (ref($domconfig{'ipaccess'}) eq 'HASH') {
10641:         my @todelete = &Apache::loncommon::get_env_multiple('form.ipaccess_del');
10642:         if (@todelete) {
10643:             map { $deletions{$_} = 1; } @todelete;
10644:         }
10645:         my $maxnum = $env{'form.ipaccess_maxnum'};
10646:         for (my $i=0; $i<$maxnum; $i++) {
10647:             my $itemid = $env{'form.ipaccess_id_'.$i};
10648:             $itemid =~ s/\D+//g;
10649:             if (ref($domconfig{'ipaccess'}{$itemid}) eq 'HASH') {
10650:                 if ($deletions{$itemid}) {
10651:                     $changes{$itemid} = $domconfig{'ipaccess'}{$itemid}{'name'};
10652:                 } else {
10653:                     push(@items,$i);
10654:                     $itemids{$i} = $itemid;
10655:                 }
10656:             }
10657:         }
10658:     }
10659:     foreach my $idx (@items) {
10660:         my $itemid = $itemids{$idx};
10661:         next unless ($itemid);
10662:         my %current;
10663:         unless ($idx eq 'add') {
10664:             if (ref($domconfig{'ipaccess'}{$itemid}) eq 'HASH') {
10665:                 %current = %{$domconfig{'ipaccess'}{$itemid}};
10666:             }
10667:         }
10668:         my $position = $env{'form.ipaccess_pos_'.$itemid};
10669:         $position =~ s/\D+//g;
10670:         if ($position ne '') {
10671:             $allpos[$position] = $itemid;
10672:         }
10673:         my $name = $env{'form.ipaccess_name_'.$idx};
10674:         $name =~ s/^\s+|\s+$//g;
10675:         $confhash{$itemid}{'name'} = $name;
10676:         my $possrange = $env{'form.ipaccess_range_'.$idx};
10677:         $possrange =~ s/^\s+|\s+$//g;
10678:         unless ($possrange eq '') {
10679:             $possrange =~ s/[\r\n]+/\s/g;
10680:             $possrange =~ s/\s*-\s*/-/g;
10681:             $possrange =~ s/\s+/,/g;
10682:             $possrange =~ s/,+/,/g;
10683:             if ($possrange ne '') {
10684:                 my (@ok,$count);
10685:                 $count = 0;
10686:                 foreach my $poss (split(/\,/,$possrange)) {
10687:                     $count ++;
10688:                     $poss = &validate_ip_pattern($poss);
10689:                     if ($poss ne '') {
10690:                         push(@ok,$poss);
10691:                     }
10692:                 }
10693:                 my $diff = $count - scalar(@ok);
10694:                 if ($diff) {
10695:                     $errors .= '<li><span class="LC_error">'.
10696:                                &mt('[quant,_1,IP] invalid and excluded from saved value for IP range(s) for [_2]',
10697:                                    $diff,$name).
10698:                                '</span></li>';
10699:                 }
10700:                 if (@ok) {
10701:                     my @cidr_list;
10702:                     foreach my $item (@ok) {
10703:                         @cidr_list = &Net::CIDR::cidradd($item,@cidr_list);
10704:                     }
10705:                     $confhash{$itemid}{'ip'} = join(',',@cidr_list);
10706:                 }
10707:             }
10708:         }
10709:         foreach my $field ('name','ip') {
10710:             unless (($idx eq 'add') || ($changes{$itemid})) {
10711:                 if ($current{$field} ne $confhash{$itemid}{$field}) {
10712:                     $changes{$itemid} = 1;
10713:                     last;
10714:                 }
10715:             }
10716:         }
10717:         $confhash{$itemid}{'commblocks'} = {};
10718: 
10719:         my %commblocks;
10720:         map { $commblocks{$_} = 1; } &Apache::loncommon::get_env_multiple('form.ipaccess_block_'.$idx);
10721:         foreach my $type (@{$typeorder}) {
10722:             if ($commblocks{$type}) {
10723:                 $confhash{$itemid}{'commblocks'}{$type} = 'on';
10724:             }
10725:             unless (($idx eq 'add') || ($changes{$itemid})) {
10726:                 if (ref($current{'commblocks'}) eq 'HASH') {
10727:                     if ($confhash{$itemid}{'commblocks'}{$type} ne $current{'commblocks'}{$type}) {
10728:                         $changes{$itemid} = 1;
10729:                     }
10730:                 } elsif ($confhash{$itemid}{'commblocks'}{$type}) {
10731:                     $changes{$itemid} = 1;
10732:                 }
10733:             }
10734:         }
10735:         $confhash{$itemid}{'courses'} = {};
10736:         my %crsdeletions;
10737:         my @delcrs = &Apache::loncommon::get_env_multiple('form.ipaccess_course_delete_'.$idx);
10738:         if (@delcrs) {
10739:             map { $crsdeletions{$_} = 1; } @delcrs;
10740:         }
10741:         if (ref($current{'courses'}) eq 'HASH') {
10742:             foreach my $cid (sort(keys(%{$current{'courses'}}))) {
10743:                 if ($crsdeletions{$cid}) {
10744:                     $changes{$itemid} = 1;
10745:                 } else {
10746:                     $confhash{$itemid}{'courses'}{$cid} = 1;
10747:                 }
10748:             }
10749:         }
10750:         $env{'form.ipaccess_cnum_'.$idx} =~ s/^\s+|\s+$//g;
10751:         $env{'form.ipaccess_cdom_'.$idx} =~ s/^\s+|\s+$//g;
10752:         if (($env{'form.ipaccess_cnum_'.$idx} =~ /^$match_courseid$/) &&
10753:             ($env{'form.ipaccess_cdom_'.$idx} =~ /^$match_domain$/)) {
10754:             if (&Apache::lonnet::homeserver($env{'form.ipaccess_cnum_'.$idx},
10755:                                             $env{'form.ipaccess_cdom_'.$idx}) eq 'no_host') {
10756:                 $errors .= '<li><span class="LC_error">'.
10757:                            &mt('Invalid courseID [_1] omitted from list of allowed courses',
10758:                                $env{'form.ipaccess_cdom_'.$idx}.'_'.$env{'form.ipaccess_cnum_'.$idx}).
10759:                            '</span></li>';
10760:             } else {
10761:                 $confhash{$itemid}{'courses'}{$env{'form.ipaccess_cdom_'.$idx}.'_'.$env{'form.ipaccess_cnum_'.$idx}} = 1;
10762:                 $changes{$itemid} = 1;
10763:             }
10764:         }
10765:     }
10766:     if (@allpos > 0) {
10767:         my $idx = 0;
10768:         foreach my $itemid (@allpos) {
10769:             if ($itemid ne '') {
10770:                 $confhash{$itemid}{'order'} = $idx;
10771:                 unless ($changes{$itemid}) {
10772:                     if (ref($domconfig{'ipaccess'}) eq 'HASH') {
10773:                         if (ref($domconfig{'ipaccess'}{$itemid}) eq 'HASH') {
10774:                             if ($domconfig{'ipaccess'}{$itemid}{'order'} ne $idx) {
10775:                                 $changes{$itemid} = 1;
10776:                             }
10777:                         }
10778:                     }
10779:                 }
10780:                 $idx ++;
10781:             }
10782:         }
10783:     }
10784:     if (keys(%changes)) {
10785:         my %defaultshash = (
10786:                               ipaccess => \%confhash,
10787:                            );
10788:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
10789:                                                  $dom);
10790:         if ($putresult eq 'ok') {
10791:             my $cachetime = 1800;
10792:             &Apache::lonnet::do_cache_new('ipaccess',$dom,\%confhash,$cachetime);
10793:             if (ref($lastactref) eq 'HASH') {
10794:                 $lastactref->{'ipaccess'} = 1;
10795:             }
10796:             $resulttext = &mt('Changes made:').'<ul>';
10797:             my %bynum;
10798:             foreach my $itemid (sort(keys(%changes))) {
10799:                 if (ref($confhash{$itemid}) eq 'HASH') {
10800:                     my $position = $confhash{$itemid}{'order'};
10801:                     if ($position =~ /^\d+$/) {
10802:                         $bynum{$position} = $itemid;
10803:                     }
10804:                 }
10805:             }
10806:             if (keys(%deletions)) {
10807:                 foreach my $itemid (sort { $a <=> $b } keys(%deletions)) {
10808:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
10809:                 }
10810:             }
10811:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
10812:                 my $itemid = $bynum{$pos};
10813:                 if (ref($confhash{$itemid}) eq 'HASH') {
10814:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'name'}.'</b><ul>';
10815:                     my $position = $pos + 1;
10816:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
10817:                     if ($confhash{$itemid}{'ip'} eq '') {
10818:                         $resulttext .= '<li>'.&mt('No IP Range(s) set').'</li>';
10819:                     } else {
10820:                         $resulttext .= '<li>'.&mt('IP Range(s): [_1]',$confhash{$itemid}{'ip'}).'</li>';
10821:                     }
10822:                     if (keys(%{$confhash{$itemid}{'commblocks'}})) {
10823:                         $resulttext .= '<li>'.&mt('Functionality Blocked: [_1]',
10824:                                                   join(', ', map { $types->{$_}; } sort(keys(%{$confhash{$itemid}{'commblocks'}})))).
10825:                                        '</li>';
10826:                     } else {
10827:                         $resulttext .= '<li>'.&mt('No functionality blocked').'</li>';
10828:                     }
10829:                     if (keys(%{$confhash{$itemid}{'courses'}})) {
10830:                         my @courses;
10831:                         foreach my $cid (sort(keys(%{$confhash{$itemid}{'courses'}}))) {
10832:                             my %courseinfo = &Apache::lonnet::coursedescription($cid,{'one_time' => 1});
10833:                             push(@courses,$courseinfo{'description'}.' ('.$cid.')');
10834:                         }
10835:                         $resulttext .= '<li>'.&mt('Courses/Communities allowed').':<ul><li>'.
10836:                                              join('</li><li>',@courses).'</li></ul>';
10837:                     } else {
10838:                         $resulttext .= '<li>'.&mt('No courses allowed').'</li>';
10839:                     }
10840:                     $resulttext .= '</ul></li>';
10841:                 }
10842:             }
10843:             $resulttext .= '</ul>';
10844:         } else {
10845:             $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
10846:         }
10847:     } else {
10848:         $resulttext = &mt('No changes made');
10849:     }
10850:     if ($errors) {
10851:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
10852:                        $errors.'</ul></p>';
10853:     }
10854:     return $resulttext;
10855: }
10856: 
10857: sub get_ipaccess_id {
10858:     my ($domain,$location) = @_;
10859:     # get lock on ipaccess db
10860:     my $lockhash = {
10861:                       lock => $env{'user.name'}.
10862:                               ':'.$env{'user.domain'},
10863:                    };
10864:     my $tries = 0;
10865:     my $gotlock = &Apache::lonnet::newput_dom('ipaccess',$lockhash,$domain);
10866:     my ($id,$error);
10867: 
10868:     while (($gotlock ne 'ok') && ($tries<10)) {
10869:         $tries ++;
10870:         sleep (0.1);
10871:         $gotlock = &Apache::lonnet::newput_dom('ipaccess',$lockhash,$domain);
10872:     }
10873:     if ($gotlock eq 'ok') {
10874:         my %currids = &Apache::lonnet::dump_dom('ipaccess',$domain);
10875:         if ($currids{'lock'}) {
10876:             delete($currids{'lock'});
10877:             if (keys(%currids)) {
10878:                 my @curr = sort { $a <=> $b } keys(%currids);
10879:                 if ($curr[-1] =~ /^\d+$/) {
10880:                     $id = 1 + $curr[-1];
10881:                 }
10882:             } else {
10883:                 $id = 1;
10884:             }
10885:             if ($id) {
10886:                 unless (&Apache::lonnet::newput_dom('ipaccess',{ $id => $location },$domain) eq 'ok') {
10887:                     $error = 'nostore';
10888:                 }
10889:             } else {
10890:                 $error = 'nonumber';
10891:             }
10892:         }
10893:         my $dellockoutcome = &Apache::lonnet::del_dom('ipaccess',['lock'],$domain);
10894:     } else {
10895:         $error = 'nolock';
10896:     }
10897:     return ($id,$error);
10898: }
10899: 
10900: sub modify_rolecolors {
10901:     my ($r,$dom,$confname,$roles,$lastactref,%domconfig) = @_;
10902:     my ($resulttext,%rolehash);
10903:     $rolehash{'rolecolors'} = {};
10904:     if (ref($domconfig{'rolecolors'}) ne 'HASH') {
10905:         if ($domconfig{'rolecolors'} eq '') {
10906:             $domconfig{'rolecolors'} = {};
10907:         }
10908:     }
10909:     my ($errors,%changes) = &modify_colors($r,$dom,$confname,$roles,
10910:                          $domconfig{'rolecolors'},$rolehash{'rolecolors'});
10911:     my $putresult = &Apache::lonnet::put_dom('configuration',\%rolehash,
10912:                                              $dom);
10913:     if ($putresult eq 'ok') {
10914:         if (keys(%changes) > 0) {
10915:             &Apache::loncommon::devalidate_domconfig_cache($dom);
10916:             if (ref($lastactref) eq 'HASH') {
10917:                 $lastactref->{'domainconfig'} = 1;
10918:             }
10919:             $resulttext = &display_colorchgs($dom,\%changes,$roles,
10920:                                              $rolehash{'rolecolors'});
10921:         } else {
10922:             $resulttext = &mt('No changes made to default color schemes');
10923:         }
10924:     } else {
10925:         $resulttext = '<span class="LC_error">'.
10926: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
10927:     }
10928:     if ($errors) {
10929:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
10930:                        $errors.'</ul>';
10931:     }
10932:     return $resulttext;
10933: }
10934: 
10935: sub modify_colors {
10936:     my ($r,$dom,$confname,$roles,$domconfig,$confhash) = @_;
10937:     my (%changes,%choices);
10938:     my @bgs;
10939:     my @links = ('link','alink','vlink');
10940:     my @logintext;
10941:     my @images;
10942:     my $servadm = $r->dir_config('lonAdmEMail');
10943:     my $errors;
10944:     my %defaults;
10945:     foreach my $role (@{$roles}) {
10946:         if ($role eq 'login') {
10947:             %choices = &login_choices();
10948:             @logintext = ('textcol','bgcol');
10949:         } else {
10950:             %choices = &color_font_choices();
10951:         }
10952:         if ($role eq 'login') {
10953:             @images = ('img','logo','domlogo','login');
10954:             @bgs = ('pgbg','mainbg','sidebg');
10955:         } else {
10956:             @images = ('img');
10957:             @bgs = ('pgbg','tabbg','sidebg');
10958:         }
10959:         my %defaults = &role_defaults($role,\@bgs,\@links,\@images,\@logintext);
10960:         unless ($env{'form.'.$role.'_font'} eq $defaults{'font'}) {
10961:             $confhash->{$role}{'font'} = $env{'form.'.$role.'_font'};
10962:         }
10963:         if ($role eq 'login') {
10964:             foreach my $item (@logintext) {
10965:                 $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
10966:                 if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
10967:                     $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
10968:                 }
10969:                 unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'logintext'}{$item})) {
10970:                     $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
10971:                 }
10972:             }
10973:         } else {
10974:             $env{'form.'.$role.'_fontmenu'} = lc($env{'form.'.$role.'_fontmenu'});
10975:             if ($env{'form.'.$role.'_fontmenu'} =~ /^\w+/) {
10976:                 $env{'form.'.$role.'_fontmenu'} = '#'.$env{'form.'.$role.'_fontmenu'};
10977:             }
10978:             unless($env{'form.'.$role.'_fontmenu'} eq lc($defaults{'fontmenu'})) {
10979:                 $confhash->{$role}{'fontmenu'} = $env{'form.'.$role.'_fontmenu'};
10980:             }
10981:         }
10982:         foreach my $item (@bgs) {
10983:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
10984:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
10985:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
10986:             }
10987:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'bgs'}{$item})) {
10988:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
10989:             }
10990:         }
10991:         foreach my $item (@links) {
10992:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
10993:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
10994:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
10995:             }
10996:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'links'}{$item})) {
10997:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
10998:             }
10999:         }
11000:         my ($configuserok,$author_ok,$switchserver) = 
11001:             &config_check($dom,$confname,$servadm);
11002:         my ($width,$height) = &thumb_dimensions();
11003:         if (ref($domconfig->{$role}) ne 'HASH') {
11004:             $domconfig->{$role} = {};
11005:         }
11006:         foreach my $img (@images) {
11007:             if ($role eq 'login') {
11008:                 if (($img eq 'img') || ($img eq 'logo')) {  
11009:                     if (defined($env{'form.login_showlogo_'.$img})) {
11010:                         $confhash->{$role}{'showlogo'}{$img} = 1;
11011:                     } else { 
11012:                         $confhash->{$role}{'showlogo'}{$img} = 0;
11013:                     }
11014:                 }
11015:                 if ($env{'form.login_alt_'.$img} ne '') {
11016:                     $confhash->{$role}{'alttext'}{$img} = $env{'form.login_alt_'.$img};
11017:                 }
11018:             }
11019: 	    if ( ! $env{'form.'.$role.'_'.$img.'.filename'} 
11020: 		 && !defined($domconfig->{$role}{$img})
11021: 		 && !$env{'form.'.$role.'_del_'.$img}
11022: 		 && $env{'form.'.$role.'_import_'.$img}) {
11023: 		# import the old configured image from the .tab setting
11024: 		# if they haven't provided a new one 
11025: 		$domconfig->{$role}{$img} = 
11026: 		    $env{'form.'.$role.'_import_'.$img};
11027: 	    }
11028:             if ($env{'form.'.$role.'_'.$img.'.filename'} ne '') {
11029:                 my $error;
11030:                 if ($configuserok eq 'ok') {
11031:                     if ($switchserver) {
11032:                         $error = &mt("Upload of [_1] image for $role page(s) is not permitted to this server: [_2]",$choices{$img},$switchserver);
11033:                     } else {
11034:                         if ($author_ok eq 'ok') {
11035:                             my ($result,$logourl) = 
11036:                                 &publishlogo($r,'upload',$role.'_'.$img,
11037:                                            $dom,$confname,$img,$width,$height);
11038:                             if ($result eq 'ok') {
11039:                                 $confhash->{$role}{$img} = $logourl;
11040:                                 $changes{$role}{'images'}{$img} = 1;
11041:                             } else {
11042:                                 $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);
11043:                             }
11044:                         } else {
11045:                             $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);
11046:                         }
11047:                     }
11048:                 } else {
11049:                     $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);
11050:                 }
11051:                 if ($error) {
11052:                     &Apache::lonnet::logthis($error);
11053:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
11054:                 }
11055:             } elsif ($domconfig->{$role}{$img} ne '') {
11056:                 if ($domconfig->{$role}{$img} !~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
11057:                     my $error;
11058:                     if ($configuserok eq 'ok') {
11059: # is confname an author?
11060:                         if ($switchserver eq '') {
11061:                             if ($author_ok eq 'ok') {
11062:                                 my ($result,$logourl) = 
11063:                                &publishlogo($r,'copy',$domconfig->{$role}{$img},
11064:                                             $dom,$confname,$img,$width,$height);
11065:                                 if ($result eq 'ok') {
11066:                                     $confhash->{$role}{$img} = $logourl;
11067: 				    $changes{$role}{'images'}{$img} = 1;
11068:                                 }
11069:                             }
11070:                         }
11071:                     }
11072:                 }
11073:             }
11074:         }
11075:         if (ref($domconfig) eq 'HASH') {
11076:             if (ref($domconfig->{$role}) eq 'HASH') {
11077:                 foreach my $img (@images) {
11078:                     if ($domconfig->{$role}{$img} ne '') {
11079:                         if ($env{'form.'.$role.'_del_'.$img}) {
11080:                             $confhash->{$role}{$img} = '';
11081:                             $changes{$role}{'images'}{$img} = 1;
11082:                         } else {
11083:                             if ($confhash->{$role}{$img} eq '') {
11084:                                 $confhash->{$role}{$img} = $domconfig->{$role}{$img};
11085:                             }
11086:                         }
11087:                     } else {
11088:                         if ($env{'form.'.$role.'_del_'.$img}) {
11089:                             $confhash->{$role}{$img} = '';
11090:                             $changes{$role}{'images'}{$img} = 1;
11091:                         } 
11092:                     }
11093:                     if ($role eq 'login') {
11094:                         if (($img eq 'logo') || ($img eq 'img')) {
11095:                             if (ref($domconfig->{'login'}{'showlogo'}) eq 'HASH') {
11096:                                 if ($confhash->{$role}{'showlogo'}{$img} ne 
11097:                                     $domconfig->{$role}{'showlogo'}{$img}) {
11098:                                     $changes{$role}{'showlogo'}{$img} = 1; 
11099:                                 }
11100:                             } else {
11101:                                 if ($confhash->{$role}{'showlogo'}{$img} == 0) {
11102:                                     $changes{$role}{'showlogo'}{$img} = 1;
11103:                                 }
11104:                             }
11105:                         }
11106:                         if ($img ne 'login') {
11107:                             if (ref($domconfig->{$role}{'alttext'}) eq 'HASH') {
11108:                                 if ($confhash->{$role}{'alttext'}{$img} ne
11109:                                     $domconfig->{$role}{'alttext'}{$img}) {
11110:                                     $changes{$role}{'alttext'}{$img} = 1;
11111:                                 }
11112:                             } else {
11113:                                 if ($confhash->{$role}{'alttext'}{$img} ne '') {
11114:                                     $changes{$role}{'alttext'}{$img} = 1;
11115:                                 }
11116:                             }
11117:                         }
11118:                     }
11119:                 }
11120:                 if ($domconfig->{$role}{'font'} ne '') {
11121:                     if ($confhash->{$role}{'font'} ne $domconfig->{$role}{'font'}) {
11122:                         $changes{$role}{'font'} = 1;
11123:                     }
11124:                 } else {
11125:                     if ($confhash->{$role}{'font'}) {
11126:                         $changes{$role}{'font'} = 1;
11127:                     }
11128:                 }
11129:                 if ($role ne 'login') {
11130:                     if ($domconfig->{$role}{'fontmenu'} ne '') {
11131:                         if ($confhash->{$role}{'fontmenu'} ne $domconfig->{$role}{'fontmenu'}) {
11132:                             $changes{$role}{'fontmenu'} = 1;
11133:                         }
11134:                     } else {
11135:                         if ($confhash->{$role}{'fontmenu'}) {
11136:                             $changes{$role}{'fontmenu'} = 1;
11137:                         }
11138:                     }
11139:                 }
11140:                 foreach my $item (@bgs) {
11141:                     if ($domconfig->{$role}{$item} ne '') {
11142:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
11143:                             $changes{$role}{'bgs'}{$item} = 1;
11144:                         } 
11145:                     } else {
11146:                         if ($confhash->{$role}{$item}) {
11147:                             $changes{$role}{'bgs'}{$item} = 1;
11148:                         }
11149:                     }
11150:                 }
11151:                 foreach my $item (@links) {
11152:                     if ($domconfig->{$role}{$item} ne '') {
11153:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
11154:                             $changes{$role}{'links'}{$item} = 1;
11155:                         }
11156:                     } else {
11157:                         if ($confhash->{$role}{$item}) {
11158:                             $changes{$role}{'links'}{$item} = 1;
11159:                         }
11160:                     }
11161:                 }
11162:                 foreach my $item (@logintext) {
11163:                     if ($domconfig->{$role}{$item} ne '') {
11164:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
11165:                             $changes{$role}{'logintext'}{$item} = 1;
11166:                         }
11167:                     } else {
11168:                         if ($confhash->{$role}{$item}) {
11169:                             $changes{$role}{'logintext'}{$item} = 1;
11170:                         }
11171:                     }
11172:                 }
11173:             } else {
11174:                 &default_change_checker($role,\@images,\@links,\@bgs,
11175:                                         \@logintext,$confhash,\%changes); 
11176:             }
11177:         } else {
11178:             &default_change_checker($role,\@images,\@links,\@bgs,
11179:                                     \@logintext,$confhash,\%changes); 
11180:         }
11181:     }
11182:     return ($errors,%changes);
11183: }
11184: 
11185: sub config_check {
11186:     my ($dom,$confname,$servadm) = @_;
11187:     my ($configuserok,$author_ok,$switchserver,%currroles);
11188:     my $uhome = &Apache::lonnet::homeserver($confname,$dom,1);
11189:     ($configuserok,%currroles) = &check_configuser($uhome,$dom,
11190:                                                    $confname,$servadm);
11191:     if ($configuserok eq 'ok') {
11192:         $switchserver = &check_switchserver($dom,$confname);
11193:         if ($switchserver eq '') {
11194:             $author_ok = &check_authorstatus($dom,$confname,%currroles);
11195:         }
11196:     }
11197:     return ($configuserok,$author_ok,$switchserver);
11198: }
11199: 
11200: sub default_change_checker {
11201:     my ($role,$images,$links,$bgs,$logintext,$confhash,$changes) = @_;
11202:     foreach my $item (@{$links}) {
11203:         if ($confhash->{$role}{$item}) {
11204:             $changes->{$role}{'links'}{$item} = 1;
11205:         }
11206:     }
11207:     foreach my $item (@{$bgs}) {
11208:         if ($confhash->{$role}{$item}) {
11209:             $changes->{$role}{'bgs'}{$item} = 1;
11210:         }
11211:     }
11212:     foreach my $item (@{$logintext}) {
11213:         if ($confhash->{$role}{$item}) {
11214:             $changes->{$role}{'logintext'}{$item} = 1;
11215:         }
11216:     }
11217:     foreach my $img (@{$images}) {
11218:         if ($env{'form.'.$role.'_del_'.$img}) {
11219:             $confhash->{$role}{$img} = '';
11220:             $changes->{$role}{'images'}{$img} = 1;
11221:         }
11222:         if ($role eq 'login') {
11223:             if ($confhash->{$role}{'showlogo'}{$img} == 0) {
11224:                 $changes->{$role}{'showlogo'}{$img} = 1;
11225:             }
11226:             if (ref($confhash->{$role}{'alttext'}) eq 'HASH') {
11227:                 if ($confhash->{$role}{'alttext'}{$img} ne '') {
11228:                     $changes->{$role}{'alttext'}{$img} = 1;
11229:                 }
11230:             }
11231:         }
11232:     }
11233:     if ($confhash->{$role}{'font'}) {
11234:         $changes->{$role}{'font'} = 1;
11235:     }
11236: }
11237: 
11238: sub display_colorchgs {
11239:     my ($dom,$changes,$roles,$confhash) = @_;
11240:     my (%choices,$resulttext);
11241:     if (!grep(/^login$/,@{$roles})) {
11242:         $resulttext = &mt('Changes made:').'<br />';
11243:     }
11244:     foreach my $role (@{$roles}) {
11245:         if ($role eq 'login') {
11246:             %choices = &login_choices();
11247:         } else {
11248:             %choices = &color_font_choices();
11249:         }
11250:         if (ref($changes->{$role}) eq 'HASH') {
11251:             if ($role ne 'login') {
11252:                 $resulttext .= '<h4>'.&mt($role).'</h4>';
11253:             }
11254:             foreach my $key (sort(keys(%{$changes->{$role}}))) {
11255:                 if ($role ne 'login') {
11256:                     $resulttext .= '<ul>';
11257:                 }
11258:                 if (ref($changes->{$role}{$key}) eq 'HASH') {
11259:                     if ($role ne 'login') {
11260:                         $resulttext .= '<li>'.&mt($choices{$key}).':<ul>';
11261:                     }
11262:                     foreach my $item (sort(keys(%{$changes->{$role}{$key}}))) {
11263:                         if (($role eq 'login') && ($key eq 'showlogo')) {
11264:                             if ($confhash->{$role}{$key}{$item}) {
11265:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to be displayed").'</li>';
11266:                             } else {
11267:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to not be displayed").'</li>';
11268:                             }
11269:                         } elsif (($role eq 'login') && ($key eq 'alttext')) {
11270:                             if ($confhash->{$role}{$key}{$item} ne '') {
11271:                                 $resulttext .= '<li>'.&mt("$choices{$key} for $choices{$item} set to [_1].",
11272:                                                $confhash->{$role}{$key}{$item}).'</li>';
11273:                             } else {
11274:                                 $resulttext .= '<li>'.&mt("$choices{$key} for $choices{$item} deleted.").'</li>';
11275:                             }
11276:                         } elsif ($confhash->{$role}{$item} eq '') {
11277:                             $resulttext .= '<li>'.&mt("$choices{$item} set to default").'</li>';
11278:                         } else {
11279:                             my $newitem = $confhash->{$role}{$item};
11280:                             if ($key eq 'images') {
11281:                                 $newitem = '<img src="'.$confhash->{$role}{$item}.'" alt="'.$choices{$item}.'" valign="bottom" />';
11282:                             }
11283:                             $resulttext .= '<li>'.&mt("$choices{$item} set to [_1]",$newitem).'</li>';
11284:                         }
11285:                     }
11286:                     if ($role ne 'login') {
11287:                         $resulttext .= '</ul></li>';
11288:                     }
11289:                 } else {
11290:                     if ($confhash->{$role}{$key} eq '') {
11291:                         $resulttext .= '<li>'.&mt("$choices{$key} set to default").'</li>';
11292:                     } else {
11293:                         $resulttext .= '<li>'.&mt("$choices{$key} set to [_1]",$confhash->{$role}{$key}).'</li>';
11294:                     }
11295:                 }
11296:                 if ($role ne 'login') {
11297:                     $resulttext .= '</ul>';
11298:                 }
11299:             }
11300:         }
11301:     }
11302:     return $resulttext;
11303: }
11304: 
11305: sub thumb_dimensions {
11306:     return ('200','50');
11307: }
11308: 
11309: sub check_dimensions {
11310:     my ($inputfile) = @_;
11311:     my ($fullwidth,$fullheight);
11312:     if ($inputfile =~ m|^[/\w.\-]+$|) {
11313:         if (open(PIPE,"identify $inputfile 2>&1 |")) {
11314:             my $imageinfo = <PIPE>;
11315:             if (!close(PIPE)) {
11316:                 &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
11317:             }
11318:             chomp($imageinfo);
11319:             my ($fullsize) = 
11320:                 ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
11321:             if ($fullsize) {
11322:                 ($fullwidth,$fullheight) = split(/x/,$fullsize);
11323:             }
11324:         }
11325:     }
11326:     return ($fullwidth,$fullheight);
11327: }
11328: 
11329: sub check_configuser {
11330:     my ($uhome,$dom,$confname,$servadm) = @_;
11331:     my ($configuserok,%currroles);
11332:     if ($uhome eq 'no_host') {
11333:         srand( time() ^ ($$ + ($$ << 15))  ); # Seed rand.
11334:         my $configpass = &LONCAPA::Enrollment::create_password($dom);
11335:         $configuserok = 
11336:             &Apache::lonnet::modifyuser($dom,$confname,'','internal',
11337:                              $configpass,'','','','','',undef,$servadm);
11338:     } else {
11339:         $configuserok = 'ok';
11340:         %currroles = 
11341:             &Apache::lonnet::get_my_roles($confname,$dom,'userroles');
11342:     }
11343:     return ($configuserok,%currroles);
11344: }
11345: 
11346: sub check_authorstatus {
11347:     my ($dom,$confname,%currroles) = @_;
11348:     my $author_ok;
11349:     if (!$currroles{':'.$dom.':au'}) {
11350:         my $start = time;
11351:         my $end = 0;
11352:         $author_ok = 
11353:             &Apache::lonnet::assignrole($dom,$confname,'/'.$dom.'/',
11354:                                         'au',$end,$start,'','','domconfig');
11355:     } else {
11356:         $author_ok = 'ok';
11357:     }
11358:     return $author_ok;
11359: }
11360: 
11361: sub publishlogo {
11362:     my ($r,$action,$formname,$dom,$confname,$subdir,$thumbwidth,$thumbheight,$savefileas) = @_;
11363:     my ($output,$fname,$logourl);
11364:     if ($action eq 'upload') {
11365:         $fname=$env{'form.'.$formname.'.filename'};
11366:         chop($env{'form.'.$formname});
11367:     } else {
11368:         ($fname) = ($formname =~ /([^\/]+)$/);
11369:     }
11370:     if ($savefileas ne '') {
11371:         $fname = $savefileas;
11372:     }
11373:     $fname=&Apache::lonnet::clean_filename($fname);
11374: # See if there is anything left
11375:     unless ($fname) { return ('error: no uploaded file'); }
11376:     $fname="$subdir/$fname";
11377:     my $docroot=$r->dir_config('lonDocRoot');
11378:     my $filepath="$docroot/priv";
11379:     my $relpath = "$dom/$confname";
11380:     my ($fnamepath,$file,$fetchthumb);
11381:     $file=$fname;
11382:     if ($fname=~m|/|) {
11383:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
11384:     }
11385:     my @parts=split(/\//,"$filepath/$relpath/$fnamepath");
11386:     my $count;
11387:     for ($count=5;$count<=$#parts;$count++) {
11388:         $filepath.="/$parts[$count]";
11389:         if ((-e $filepath)!=1) {
11390:             mkdir($filepath,02770);
11391:         }
11392:     }
11393:     # Check for bad extension and disallow upload
11394:     if ($file=~/\.(\w+)$/ &&
11395:         (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
11396:         $output = 
11397:             &mt('Invalid file extension ([_1]) - reserved for internal use.',$1); 
11398:     } elsif ($file=~/\.(\w+)$/ &&
11399:         !defined(&Apache::loncommon::fileembstyle($1))) {
11400:         $output = &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
11401:     } elsif ($file=~/\.(\d+)\.(\w+)$/) {
11402:         $output = &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
11403:     } elsif (-d "$filepath/$file") {
11404:         $output = &mt('Filename is a directory name - rename the file and re-upload');
11405:     } else {
11406:         my $source = $filepath.'/'.$file;
11407:         my $logfile;
11408:         if (!open($logfile,">>",$source.'.log')) {
11409:             return (&mt('No write permission to Authoring Space'));
11410:         }
11411:         print $logfile
11412: "\n================= Publish ".localtime()." ================\n".
11413: $env{'user.name'}.':'.$env{'user.domain'}."\n";
11414: # Save the file
11415:         if (!open(FH,">",$source)) {
11416:             &Apache::lonnet::logthis('Failed to create '.$source);
11417:             return (&mt('Failed to create file'));
11418:         }
11419:         if ($action eq 'upload') {
11420:             if (!print FH ($env{'form.'.$formname})) {
11421:                 &Apache::lonnet::logthis('Failed to write to '.$source);
11422:                 return (&mt('Failed to write file'));
11423:             }
11424:         } else {
11425:             my $original = &Apache::lonnet::filelocation('',$formname);
11426:             if(!copy($original,$source)) {
11427:                 &Apache::lonnet::logthis('Failed to copy '.$original.' to '.$source);
11428:                 return (&mt('Failed to write file'));
11429:             }
11430:         }
11431:         close(FH);
11432:         chmod(0660, $source); # Permissions to rw-rw---.
11433: 
11434:         my $targetdir=$docroot.'/res/'.$dom.'/'.$confname .'/'.$fnamepath;
11435:         my $copyfile=$targetdir.'/'.$file;
11436: 
11437:         my @parts=split(/\//,$targetdir);
11438:         my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
11439:         for (my $count=5;$count<=$#parts;$count++) {
11440:             $path.="/$parts[$count]";
11441:             if (!-e $path) {
11442:                 print $logfile "\nCreating directory ".$path;
11443:                 mkdir($path,02770);
11444:             }
11445:         }
11446:         my $versionresult;
11447:         if (-e $copyfile) {
11448:             $versionresult = &logo_versioning($targetdir,$file,$logfile);
11449:         } else {
11450:             $versionresult = 'ok';
11451:         }
11452:         if ($versionresult eq 'ok') {
11453:             if (copy($source,$copyfile)) {
11454:                 print $logfile "\nCopied original source to ".$copyfile."\n";
11455:                 $output = 'ok';
11456:                 $logourl = '/res/'.$dom.'/'.$confname.'/'.$fname;
11457:                 push(@{$modified_urls},[$copyfile,$source]);
11458:                 my $metaoutput = 
11459:                     &write_metadata($dom,$confname,$formname,$targetdir,$file,$logfile);
11460:                 unless ($registered_cleanup) {
11461:                     my $handlers = $r->get_handlers('PerlCleanupHandler');
11462:                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
11463:                     $registered_cleanup=1;
11464:                 }
11465:             } else {
11466:                 print $logfile "\nUnable to write ".$copyfile.':'.$!."\n";
11467:                 $output = &mt('Failed to copy file to RES space').", $!";
11468:             }
11469:             if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
11470:                 my $inputfile = $filepath.'/'.$file;
11471:                 my $outfile = $filepath.'/'.'tn-'.$file;
11472:                 my ($fullwidth,$fullheight) = &check_dimensions($inputfile);
11473:                 if ($fullwidth ne '' && $fullheight ne '') { 
11474:                     if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
11475:                         my $thumbsize = $thumbwidth.'x'.$thumbheight;
11476:                         my @args = ('convert','-sample',$thumbsize,$inputfile,$outfile);
11477:                         system({$args[0]} @args);
11478:                         chmod(0660, $filepath.'/tn-'.$file);
11479:                         if (-e $outfile) {
11480:                             my $copyfile=$targetdir.'/tn-'.$file;
11481:                             if (copy($outfile,$copyfile)) {
11482:                                 print $logfile "\nCopied source to ".$copyfile."\n";
11483:                                 my $thumb_metaoutput = 
11484:                                     &write_metadata($dom,$confname,$formname,
11485:                                                     $targetdir,'tn-'.$file,$logfile);
11486:                                 push(@{$modified_urls},[$copyfile,$outfile]);
11487:                                 unless ($registered_cleanup) {
11488:                                     my $handlers = $r->get_handlers('PerlCleanupHandler');
11489:                                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
11490:                                     $registered_cleanup=1;
11491:                                 }
11492:                             } else {
11493:                                 print $logfile "\nUnable to write ".$copyfile.
11494:                                                ':'.$!."\n";
11495:                             }
11496:                         }
11497:                     }
11498:                 }
11499:             }
11500:         } else {
11501:             $output = $versionresult;
11502:         }
11503:     }
11504:     return ($output,$logourl);
11505: }
11506: 
11507: sub logo_versioning {
11508:     my ($targetdir,$file,$logfile) = @_;
11509:     my $target = $targetdir.'/'.$file;
11510:     my ($maxversion,$fn,$extn,$output);
11511:     $maxversion = 0;
11512:     if ($file =~ /^(.+)\.(\w+)$/) {
11513:         $fn=$1;
11514:         $extn=$2;
11515:     }
11516:     opendir(DIR,$targetdir);
11517:     while (my $filename=readdir(DIR)) {
11518:         if ($filename=~/\Q$fn\E\.(\d+)\.\Q$extn\E$/) {
11519:             $maxversion=($1>$maxversion)?$1:$maxversion;
11520:         }
11521:     }
11522:     $maxversion++;
11523:     print $logfile "\nCreating old version ".$maxversion."\n";
11524:     my $copyfile=$targetdir.'/'.$fn.'.'.$maxversion.'.'.$extn;
11525:     if (copy($target,$copyfile)) {
11526:         print $logfile "Copied old target to ".$copyfile."\n";
11527:         $copyfile=$copyfile.'.meta';
11528:         if (copy($target.'.meta',$copyfile)) {
11529:             print $logfile "Copied old target metadata to ".$copyfile."\n";
11530:             $output = 'ok';
11531:         } else {
11532:             print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
11533:             $output = &mt('Failed to copy old meta').", $!, ";
11534:         }
11535:     } else {
11536:         print $logfile "Unable to write ".$copyfile.':'.$!."\n";
11537:         $output = &mt('Failed to copy old target').", $!, ";
11538:     }
11539:     return $output;
11540: }
11541: 
11542: sub write_metadata {
11543:     my ($dom,$confname,$formname,$targetdir,$file,$logfile) = @_;
11544:     my (%metadatafields,%metadatakeys,$output);
11545:     $metadatafields{'title'}=$formname;
11546:     $metadatafields{'creationdate'}=time;
11547:     $metadatafields{'lastrevisiondate'}=time;
11548:     $metadatafields{'copyright'}='public';
11549:     $metadatafields{'modifyinguser'}=$env{'user.name'}.':'.
11550:                                          $env{'user.domain'};
11551:     $metadatafields{'authorspace'}=$confname.':'.$dom;
11552:     $metadatafields{'domain'}=$dom;
11553:     {
11554:         print $logfile "\nWrite metadata file for ".$targetdir.'/'.$file;
11555:         my $mfh;
11556:         if (open($mfh,">",$targetdir.'/'.$file.'.meta')) {
11557:             foreach (sort(keys(%metadatafields))) {
11558:                 unless ($_=~/\./) {
11559:                     my $unikey=$_;
11560:                     $unikey=~/^([A-Za-z]+)/;
11561:                     my $tag=$1;
11562:                     $tag=~tr/A-Z/a-z/;
11563:                     print $mfh "\n\<$tag";
11564:                     foreach (split(/\,/,$metadatakeys{$unikey})) {
11565:                         my $value=$metadatafields{$unikey.'.'.$_};
11566:                         $value=~s/\"/\'\'/g;
11567:                         print $mfh ' '.$_.'="'.$value.'"';
11568:                     }
11569:                     print $mfh '>'.
11570:                         &HTML::Entities::encode($metadatafields{$unikey},'<>&"')
11571:                             .'</'.$tag.'>';
11572:                 }
11573:             }
11574:             $output = 'ok';
11575:             print $logfile "\nWrote metadata";
11576:             close($mfh);
11577:         } else {
11578:             print $logfile "\nFailed to open metadata file";
11579:             $output = &mt('Could not write metadata');
11580:         }
11581:     }
11582:     return $output;
11583: }
11584: 
11585: sub notifysubscribed {
11586:     foreach my $targetsource (@{$modified_urls}){
11587:         next unless (ref($targetsource) eq 'ARRAY');
11588:         my ($target,$source)=@{$targetsource};
11589:         if ($source ne '') {
11590:             if (open(my $logfh,">>",$source.'.log')) {
11591:                 print $logfh "\nCleanup phase: Notifications\n";
11592:                 my @subscribed=&subscribed_hosts($target);
11593:                 foreach my $subhost (@subscribed) {
11594:                     print $logfh "\nNotifying host ".$subhost.':';
11595:                     my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
11596:                     print $logfh $reply;
11597:                 }
11598:                 my @subscribedmeta=&subscribed_hosts("$target.meta");
11599:                 foreach my $subhost (@subscribedmeta) {
11600:                     print $logfh "\nNotifying host for metadata only ".$subhost.':';
11601:                     my $reply=&Apache::lonnet::critical('update:'.$target.'.meta',
11602:                                                         $subhost);
11603:                     print $logfh $reply;
11604:                 }
11605:                 print $logfh "\n============ Done ============\n";
11606:                 close($logfh);
11607:             }
11608:         }
11609:     }
11610:     return OK;
11611: }
11612: 
11613: sub subscribed_hosts {
11614:     my ($target) = @_;
11615:     my @subscribed;
11616:     if (open(my $fh,"<","$target.subscription")) {
11617:         while (my $subline=<$fh>) {
11618:             if ($subline =~ /^($match_lonid):/) {
11619:                 my $host = $1;
11620:                 if ($host ne $Apache::lonnet::perlvar{'lonHostID'}) {
11621:                     unless (grep(/^\Q$host\E$/,@subscribed)) {
11622:                         push(@subscribed,$host);
11623:                     }
11624:                 }
11625:             }
11626:         }
11627:     }
11628:     return @subscribed;
11629: }
11630: 
11631: sub check_switchserver {
11632:     my ($dom,$confname) = @_;
11633:     my ($allowed,$switchserver);
11634:     my $home = &Apache::lonnet::homeserver($confname,$dom);
11635:     if ($home eq 'no_host') {
11636:         $home = &Apache::lonnet::domain($dom,'primary');
11637:     }
11638:     my @ids=&Apache::lonnet::current_machine_ids();
11639:     foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
11640:     if (!$allowed) {
11641: 	$switchserver='<a href="/adm/switchserver?otherserver='.$home.'&amp;role=dc./'.$dom.'/&amp;destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
11642:     }
11643:     return $switchserver;
11644: }
11645: 
11646: sub modify_quotas {
11647:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
11648:     my ($context,@usertools,@options,%validations,%titles,%confhash,%toolshash,
11649:         %limithash,$toolregexp,%conditions,$resulttext,%changes,$confname,$configuserok,
11650:         $author_ok,$switchserver,$errors,$validationitemsref,$validationnamesref,
11651:         $validationfieldsref);
11652:     if ($action eq 'quotas') {
11653:         $context = 'tools'; 
11654:     } else {
11655:         $context = $action;
11656:     }
11657:     if ($context eq 'requestcourses') {
11658:         @usertools = ('official','unofficial','community','textbook');
11659:         @options =('norequest','approval','validate','autolimit');
11660:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
11661:         %titles = &courserequest_titles();
11662:         $toolregexp = join('|',@usertools);
11663:         %conditions = &courserequest_conditions();
11664:         $confname = $dom.'-domainconfig';
11665:         my $servadm = $r->dir_config('lonAdmEMail');
11666:         ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
11667:         ($validationitemsref,$validationnamesref,$validationfieldsref) = 
11668:             &Apache::loncoursequeueadmin::requestcourses_validation_types();
11669:     } elsif ($context eq 'requestauthor') {
11670:         @usertools = ('author');
11671:         %titles = &authorrequest_titles();
11672:     } else {
11673:         @usertools = ('aboutme','blog','webdav','portfolio');
11674:         %titles = &tool_titles();
11675:     }
11676:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
11677:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
11678:     foreach my $key (keys(%env)) {
11679:         if ($context eq 'requestcourses') {
11680:             if ($key =~ /^form\.crsreq_($toolregexp)_(.+)$/) {
11681:                 my $item = $1;
11682:                 my $type = $2;
11683:                 if ($type =~ /^limit_(.+)/) {
11684:                     $limithash{$item}{$1} = $env{$key};
11685:                 } else {
11686:                     $confhash{$item}{$type} = $env{$key};
11687:                 }
11688:             }
11689:         } elsif ($context eq 'requestauthor') {
11690:             if ($key =~ /^\Qform.authorreq_\E(.+)$/) {
11691:                 $confhash{$1} = $env{$key};
11692:             }
11693:         } else {
11694:             if ($key =~ /^form\.quota_(.+)$/) {
11695:                 $confhash{'defaultquota'}{$1} = $env{$key};
11696:             } elsif ($key =~ /^form\.authorquota_(.+)$/) {
11697:                 $confhash{'authorquota'}{$1} = $env{$key};
11698:             } elsif ($key =~ /^form\.\Q$context\E_(.+)$/) {
11699:                 @{$toolshash{$1}} = &Apache::loncommon::get_env_multiple($key);
11700:             }
11701:         }
11702:     }
11703:     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
11704:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.'.$context.'notifyapproval');
11705:         @approvalnotify = sort(@approvalnotify);
11706:         $confhash{'notify'}{'approval'} = join(',',@approvalnotify);
11707:         my @crstypes = ('official','unofficial','community','textbook');
11708:         my @hasuniquecode = &Apache::loncommon::get_env_multiple('form.uniquecode');
11709:         foreach my $type (@hasuniquecode) {
11710:             if (grep(/^\Q$type\E$/,@crstypes)) {
11711:                 $confhash{'uniquecode'}{$type} = 1;
11712:             }
11713:         }
11714:         my (%newbook,%allpos);
11715:         if ($context eq 'requestcourses') {
11716:             foreach my $type ('textbooks','templates') {
11717:                 @{$allpos{$type}} = (); 
11718:                 my $invalid;
11719:                 if ($type eq 'textbooks') {
11720:                     $invalid = &mt('Invalid LON-CAPA course for textbook');
11721:                 } else {
11722:                     $invalid = &mt('Invalid LON-CAPA course for template');
11723:                 }
11724:                 if ($env{'form.'.$type.'_addbook'}) {
11725:                     if (($env{'form.'.$type.'_addbook_cnum'} =~ /^$match_courseid$/) &&
11726:                         ($env{'form.'.$type.'_addbook_cdom'} =~ /^$match_domain$/)) {
11727:                         if (&Apache::lonnet::homeserver($env{'form.'.$type.'_addbook_cnum'},
11728:                                                         $env{'form.'.$type.'_addbook_cdom'}) eq 'no_host') {
11729:                             $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
11730:                         } else {
11731:                             $newbook{$type} = $env{'form.'.$type.'_addbook_cdom'}.'_'.$env{'form.'.$type.'_addbook_cnum'};
11732:                             my $position = $env{'form.'.$type.'_addbook_pos'};
11733:                             $position =~ s/\D+//g;
11734:                             if ($position ne '') {
11735:                                 $allpos{$type}[$position] = $newbook{$type};
11736:                             }
11737:                         }
11738:                     } else {
11739:                         $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
11740:                     }
11741:                 }
11742:             } 
11743:         }
11744:         if (ref($domconfig{$action}) eq 'HASH') {
11745:             if (ref($domconfig{$action}{'notify'}) eq 'HASH') {
11746:                 if ($domconfig{$action}{'notify'}{'approval'} ne $confhash{'notify'}{'approval'}) {
11747:                     $changes{'notify'}{'approval'} = 1;
11748:                 }
11749:             } else {
11750:                 if ($confhash{'notify'}{'approval'}) {
11751:                     $changes{'notify'}{'approval'} = 1;
11752:                 }
11753:             }
11754:             if (ref($domconfig{$action}{'uniquecode'}) eq 'HASH') {
11755:                 if (ref($confhash{'uniquecode'}) eq 'HASH') {
11756:                     foreach my $crstype (keys(%{$domconfig{$action}{'uniquecode'}})) {
11757:                         unless ($confhash{'uniquecode'}{$crstype}) {
11758:                             $changes{'uniquecode'} = 1;
11759:                         }
11760:                     }
11761:                     unless ($changes{'uniquecode'}) {
11762:                         foreach my $crstype (keys(%{$confhash{'uniquecode'}})) {
11763:                             unless ($domconfig{$action}{'uniquecode'}{$crstype}) {
11764:                                 $changes{'uniquecode'} = 1;
11765:                             }
11766:                         }
11767:                     }
11768:                } else {
11769:                    $changes{'uniquecode'} = 1;
11770:                }
11771:             } elsif (ref($confhash{'uniquecode'}) eq 'HASH') {
11772:                 $changes{'uniquecode'} = 1;
11773:             }
11774:             if ($context eq 'requestcourses') {
11775:                 foreach my $type ('textbooks','templates') {
11776:                     if (ref($domconfig{$action}{$type}) eq 'HASH') {
11777:                         my %deletions;
11778:                         my @todelete = &Apache::loncommon::get_env_multiple('form.'.$type.'_del');
11779:                         if (@todelete) {
11780:                             map { $deletions{$_} = 1; } @todelete;
11781:                         }
11782:                         my %imgdeletions;
11783:                         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.'.$type.'_image_del');
11784:                         if (@todeleteimages) {
11785:                             map { $imgdeletions{$_} = 1; } @todeleteimages;
11786:                         }
11787:                         my $maxnum = $env{'form.'.$type.'_maxnum'};
11788:                         for (my $i=0; $i<=$maxnum; $i++) {
11789:                             my $itemid = $env{'form.'.$type.'_id_'.$i};
11790:                             my ($key) = ($itemid =~ /^\Q$type\E_(\w+)$/); 
11791:                             if (ref($domconfig{$action}{$type}{$key}) eq 'HASH') {
11792:                                 if ($deletions{$key}) {
11793:                                     if ($domconfig{$action}{$type}{$key}{'image'}) {
11794:                                         #FIXME need to obsolete item in RES space
11795:                                     }
11796:                                     next;
11797:                                 } else {
11798:                                     my $newpos = $env{'form.'.$itemid};
11799:                                     $newpos =~ s/\D+//g;
11800:                                     foreach my $item ('subject','title','publisher','author') {
11801:                                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
11802:                                                  ($type eq 'templates'));
11803:                                         $confhash{$type}{$key}{$item} = $env{'form.'.$type.'_'.$item.'_'.$i};
11804:                                         if ($domconfig{$action}{$type}{$key}{$item} ne $confhash{$type}{$key}{$item}) {
11805:                                             $changes{$type}{$key} = 1;
11806:                                         }
11807:                                     }
11808:                                     $allpos{$type}[$newpos] = $key;
11809:                                 }
11810:                                 if ($imgdeletions{$key}) {
11811:                                     $changes{$type}{$key} = 1;
11812:                                     #FIXME need to obsolete item in RES space
11813:                                 } elsif ($env{'form.'.$type.'_image_'.$i.'.filename'}) {
11814:                                     my ($cdom,$cnum) = split(/_/,$key);
11815:                                     if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
11816:                                         $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
11817:                                     } else {
11818:                                         my ($imgurl,$error) = &process_textbook_image($r,$dom,$confname,$type.'_image_'.$i,
11819:                                                                                       $cdom,$cnum,$type,$configuserok,
11820:                                                                                       $switchserver,$author_ok);
11821:                                         if ($imgurl) {
11822:                                             $confhash{$type}{$key}{'image'} = $imgurl;
11823:                                             $changes{$type}{$key} = 1; 
11824:                                         }
11825:                                         if ($error) {
11826:                                             &Apache::lonnet::logthis($error);
11827:                                             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
11828:                                         }
11829:                                     } 
11830:                                 } elsif ($domconfig{$action}{$type}{$key}{'image'}) {
11831:                                     $confhash{$type}{$key}{'image'} = 
11832:                                         $domconfig{$action}{$type}{$key}{'image'};
11833:                                 }
11834:                             }
11835:                         }
11836:                     }
11837:                 }
11838:             }
11839:         } else {
11840:             if ($confhash{'notify'}{'approval'}) {
11841:                 $changes{'notify'}{'approval'} = 1;
11842:             }
11843:             if (ref($confhash{'uniquecode'} eq 'HASH')) {
11844:                 $changes{'uniquecode'} = 1;
11845:             }
11846:         }
11847:         if ($context eq 'requestcourses') {
11848:             foreach my $type ('textbooks','templates') {
11849:                 if ($newbook{$type}) {
11850:                     $changes{$type}{$newbook{$type}} = 1;
11851:                     foreach my $item ('subject','title','publisher','author') {
11852:                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
11853:                                  ($type eq 'template'));
11854:                         $env{'form.'.$type.'_addbook_'.$item} =~ s/(`)/'/g;
11855:                         if ($env{'form.'.$type.'_addbook_'.$item}) {
11856:                             $confhash{$type}{$newbook{$type}}{$item} = $env{'form.'.$type.'_addbook_'.$item};
11857:                         }
11858:                     }
11859:                     if ($type eq 'textbooks') {
11860:                         if ($env{'form.'.$type.'_addbook_image.filename'} ne '') {
11861:                             my ($cdom,$cnum) = split(/_/,$newbook{$type});
11862:                             if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
11863:                                 $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
11864:                             } else {
11865:                                 my ($imageurl,$error) =
11866:                                     &process_textbook_image($r,$dom,$confname,$type.'_addbook_image',$cdom,$cnum,$type,
11867:                                                             $configuserok,$switchserver,$author_ok);
11868:                                 if ($imageurl) {
11869:                                     $confhash{$type}{$newbook{$type}}{'image'} = $imageurl;
11870:                                 }
11871:                                 if ($error) {
11872:                                     &Apache::lonnet::logthis($error);
11873:                                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
11874:                                 }
11875:                             }
11876:                         }
11877:                     }
11878:                 }
11879:                 if (@{$allpos{$type}} > 0) {
11880:                     my $idx = 0;
11881:                     foreach my $item (@{$allpos{$type}}) {
11882:                         if ($item ne '') {
11883:                             $confhash{$type}{$item}{'order'} = $idx;
11884:                             if (ref($domconfig{$action}) eq 'HASH') {
11885:                                 if (ref($domconfig{$action}{$type}) eq 'HASH') {
11886:                                     if (ref($domconfig{$action}{$type}{$item}) eq 'HASH') {
11887:                                         if ($domconfig{$action}{$type}{$item}{'order'} ne $idx) {
11888:                                             $changes{$type}{$item} = 1;
11889:                                         }
11890:                                     }
11891:                                 }
11892:                             }
11893:                             $idx ++;
11894:                         }
11895:                     }
11896:                 }
11897:             }
11898:             if (ref($validationitemsref) eq 'ARRAY') {
11899:                 foreach my $item (@{$validationitemsref}) {
11900:                     if ($item eq 'fields') {
11901:                         my @changed;
11902:                         @{$confhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.requestcourses_validation_'.$item);
11903:                         if (@{$confhash{'validation'}{$item}} > 0) {
11904:                             @{$confhash{'validation'}{$item}} = sort(@{$confhash{'validation'}{$item}});
11905:                         }
11906:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
11907:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
11908:                                 if (ref($domconfig{'requestcourses'}{'validation'}{$item}) eq 'ARRAY') {
11909:                                     @changed = &Apache::loncommon::compare_arrays($confhash{'validation'}{$item},
11910:                                                                                   $domconfig{'requestcourses'}{'validation'}{$item});
11911:                                 } else {
11912:                                     @changed = @{$confhash{'validation'}{$item}};
11913:                                 }
11914:                             } else {
11915:                                 @changed = @{$confhash{'validation'}{$item}};
11916:                             }
11917:                         } else {
11918:                             @changed = @{$confhash{'validation'}{$item}};
11919:                         }
11920:                         if (@changed) {
11921:                             if ($confhash{'validation'}{$item}) {
11922:                                 $changes{'validation'}{$item} = join(', ',@{$confhash{'validation'}{$item}});
11923:                             } else {
11924:                                 $changes{'validation'}{$item} = &mt('None');
11925:                             }
11926:                         }
11927:                     } else {
11928:                         $confhash{'validation'}{$item} = $env{'form.requestcourses_validation_'.$item};
11929:                         if ($item eq 'markup') {
11930:                             if ($env{'form.requestcourses_validation_'.$item}) {
11931:                                 $env{'form.requestcourses_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
11932:                             }
11933:                         }
11934:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
11935:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
11936:                                 if ($domconfig{'requestcourses'}{'validation'}{$item} ne $confhash{'validation'}{$item}) {
11937:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
11938:                                 }
11939:                             } else {
11940:                                 if ($confhash{'validation'}{$item} ne '') {
11941:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
11942:                                 }
11943:                             }
11944:                         } else {
11945:                             if ($confhash{'validation'}{$item} ne '') {
11946:                                 $changes{'validation'}{$item} = $confhash{'validation'}{$item};
11947:                             }
11948:                         }
11949:                     }
11950:                 }
11951:             }
11952:             if ($env{'form.validationdc'}) {
11953:                 my $newval = $env{'form.validationdc'};
11954:                 my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
11955:                 if (exists($domcoords{$newval})) {
11956:                     $confhash{'validation'}{'dc'} = $newval;
11957:                 }
11958:             }
11959:             if (ref($confhash{'validation'}) eq 'HASH') {
11960:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
11961:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
11962:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
11963:                             unless ($confhash{'validation'}{'dc'} eq $domconfig{'requestcourses'}{'validation'}{'dc'}) {
11964:                                 if ($confhash{'validation'}{'dc'} eq '') {
11965:                                     $changes{'validation'}{'dc'} = &mt('None');
11966:                                 } else {
11967:                                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
11968:                                 }
11969:                             }
11970:                         } elsif ($confhash{'validation'}{'dc'} ne '') {
11971:                             $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
11972:                         }
11973:                     } elsif ($confhash{'validation'}{'dc'} ne '') {
11974:                         $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
11975:                     }
11976:                 } elsif ($confhash{'validation'}{'dc'} ne '') {
11977:                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
11978:                 }
11979:             } else {
11980:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
11981:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
11982:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
11983:                             $changes{'validation'}{'dc'} = &mt('None');
11984:                         }
11985:                     }
11986:                 }
11987:             }
11988:         }
11989:     } else {
11990:         $confhash{'defaultquota'}{'default'} = $env{'form.defaultquota'};
11991:         $confhash{'authorquota'}{'default'} = $env{'form.authorquota'};
11992:     }
11993:     foreach my $item (@usertools) {
11994:         foreach my $type (@{$types},'default','_LC_adv') {
11995:             my $unset; 
11996:             if ($context eq 'requestcourses') {
11997:                 $unset = '0';
11998:                 if ($type eq '_LC_adv') {
11999:                     $unset = '';
12000:                 }
12001:                 if ($confhash{$item}{$type} eq 'autolimit') {
12002:                     $confhash{$item}{$type} .= '=';
12003:                     unless ($limithash{$item}{$type} =~ /\D/) {
12004:                         $confhash{$item}{$type} .= $limithash{$item}{$type};
12005:                     }
12006:                 }
12007:             } elsif ($context eq 'requestauthor') {
12008:                 $unset = '0';
12009:                 if ($type eq '_LC_adv') {
12010:                     $unset = '';
12011:                 }
12012:             } else {
12013:                 if (grep(/^\Q$type\E$/,@{$toolshash{$item}})) {
12014:                     $confhash{$item}{$type} = 1;
12015:                 } else {
12016:                     $confhash{$item}{$type} = 0;
12017:                 }
12018:             }
12019:             if (ref($domconfig{$action}) eq 'HASH') {
12020:                 if ($action eq 'requestauthor') {
12021:                     if ($domconfig{$action}{$type} ne $confhash{$type}) {
12022:                         $changes{$type} = 1;
12023:                     }
12024:                 } elsif (ref($domconfig{$action}{$item}) eq 'HASH') {
12025:                     if ($domconfig{$action}{$item}{$type} ne $confhash{$item}{$type}) {
12026:                         $changes{$item}{$type} = 1;
12027:                     }
12028:                 } else {
12029:                     if ($context eq 'requestcourses') {
12030:                         if ($confhash{$item}{$type} ne $unset) {
12031:                             $changes{$item}{$type} = 1;
12032:                         }
12033:                     } else {
12034:                         if (!$confhash{$item}{$type}) {
12035:                             $changes{$item}{$type} = 1;
12036:                         }
12037:                     }
12038:                 }
12039:             } else {
12040:                 if ($context eq 'requestcourses') {
12041:                     if ($confhash{$item}{$type} ne $unset) {
12042:                         $changes{$item}{$type} = 1;
12043:                     }
12044:                 } elsif ($context eq 'requestauthor') {
12045:                     if ($confhash{$type} ne $unset) {
12046:                         $changes{$type} = 1;
12047:                     }
12048:                 } else {
12049:                     if (!$confhash{$item}{$type}) {
12050:                         $changes{$item}{$type} = 1;
12051:                     }
12052:                 }
12053:             }
12054:         }
12055:     }
12056:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
12057:         if (ref($domconfig{'quotas'}) eq 'HASH') {
12058:             if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
12059:                 foreach my $key (keys(%{$domconfig{'quotas'}{'defaultquota'}})) {
12060:                     if (exists($confhash{'defaultquota'}{$key})) {
12061:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{'defaultquota'}{$key}) {
12062:                             $changes{'defaultquota'}{$key} = 1;
12063:                         }
12064:                     } else {
12065:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{'defaultquota'}{$key};
12066:                     }
12067:                 }
12068:             } else {
12069:                 foreach my $key (keys(%{$domconfig{'quotas'}})) {
12070:                     if (exists($confhash{'defaultquota'}{$key})) {
12071:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{$key}) {
12072:                             $changes{'defaultquota'}{$key} = 1;
12073:                         }
12074:                     } else {
12075:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{$key};
12076:                     }
12077:                 }
12078:             }
12079:             if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
12080:                 foreach my $key (keys(%{$domconfig{'quotas'}{'authorquota'}})) {
12081:                     if (exists($confhash{'authorquota'}{$key})) {
12082:                         if ($confhash{'authorquota'}{$key} ne $domconfig{'quotas'}{'authorquota'}{$key}) {
12083:                             $changes{'authorquota'}{$key} = 1;
12084:                         }
12085:                     } else {
12086:                         $confhash{'authorquota'}{$key} = $domconfig{'quotas'}{'authorquota'}{$key};
12087:                     }
12088:                 }
12089:             }
12090:         }
12091:         if (ref($confhash{'defaultquota'}) eq 'HASH') {
12092:             foreach my $key (keys(%{$confhash{'defaultquota'}})) {
12093:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
12094:                     if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
12095:                         if (!exists($domconfig{'quotas'}{'defaultquota'}{$key})) {
12096:                             $changes{'defaultquota'}{$key} = 1;
12097:                         }
12098:                     } else {
12099:                         if (!exists($domconfig{'quotas'}{$key})) {
12100:                             $changes{'defaultquota'}{$key} = 1;
12101:                         }
12102:                     }
12103:                 } else {
12104:                     $changes{'defaultquota'}{$key} = 1;
12105:                 }
12106:             }
12107:         }
12108:         if (ref($confhash{'authorquota'}) eq 'HASH') {
12109:             foreach my $key (keys(%{$confhash{'authorquota'}})) {
12110:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
12111:                     if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
12112:                         if (!exists($domconfig{'quotas'}{'authorquota'}{$key})) {
12113:                             $changes{'authorquota'}{$key} = 1;
12114:                         }
12115:                     } else {
12116:                         $changes{'authorquota'}{$key} = 1;
12117:                     }
12118:                 } else {
12119:                     $changes{'authorquota'}{$key} = 1;
12120:                 }
12121:             }
12122:         }
12123:     }
12124: 
12125:     if ($context eq 'requestauthor') {
12126:         $domdefaults{'requestauthor'} = \%confhash;
12127:     } else {
12128:         foreach my $key (keys(%confhash)) {
12129:             unless (($context eq 'requestcourses') && (($key eq 'textbooks') || ($key eq 'templates'))) {
12130:                 $domdefaults{$key} = $confhash{$key};
12131:             }
12132:         }
12133:     }
12134: 
12135:     my %quotahash = (
12136:                       $action => { %confhash }
12137:                     );
12138:     my $putresult = &Apache::lonnet::put_dom('configuration',\%quotahash,
12139:                                              $dom);
12140:     if ($putresult eq 'ok') {
12141:         if (keys(%changes) > 0) {
12142:             my $cachetime = 24*60*60;
12143:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
12144:             if (ref($lastactref) eq 'HASH') {
12145:                 $lastactref->{'domdefaults'} = 1;
12146:             }
12147:             $resulttext = &mt('Changes made:').'<ul>';
12148:             unless (($context eq 'requestcourses') ||
12149:                     ($context eq 'requestauthor')) {
12150:                 if (ref($changes{'defaultquota'}) eq 'HASH') {
12151:                     $resulttext .= '<li>'.&mt('Portfolio default quotas').'<ul>';
12152:                     foreach my $type (@{$types},'default') {
12153:                         if (defined($changes{'defaultquota'}{$type})) {
12154:                             my $typetitle = $usertypes->{$type};
12155:                             if ($type eq 'default') {
12156:                                 $typetitle = $othertitle;
12157:                             }
12158:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'defaultquota'}{$type}).'</li>';
12159:                         }
12160:                     }
12161:                     $resulttext .= '</ul></li>';
12162:                 }
12163:                 if (ref($changes{'authorquota'}) eq 'HASH') {
12164:                     $resulttext .= '<li>'.&mt('Authoring Space default quotas').'<ul>';
12165:                     foreach my $type (@{$types},'default') {
12166:                         if (defined($changes{'authorquota'}{$type})) {
12167:                             my $typetitle = $usertypes->{$type};
12168:                             if ($type eq 'default') {
12169:                                 $typetitle = $othertitle;
12170:                             }
12171:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'authorquota'}{$type}).'</li>';
12172:                         }
12173:                     }
12174:                     $resulttext .= '</ul></li>';
12175:                 }
12176:             }
12177:             my %newenv;
12178:             foreach my $item (@usertools) {
12179:                 my (%haschgs,%inconf);
12180:                 if ($context eq 'requestauthor') {
12181:                     %haschgs = %changes;
12182:                     %inconf = %confhash;
12183:                 } else {
12184:                     if (ref($changes{$item}) eq 'HASH') {
12185:                         %haschgs = %{$changes{$item}};
12186:                     }
12187:                     if (ref($confhash{$item}) eq 'HASH') {
12188:                         %inconf = %{$confhash{$item}};
12189:                     }
12190:                 }
12191:                 if (keys(%haschgs) > 0) {
12192:                     my $newacc = 
12193:                         &Apache::lonnet::usertools_access($env{'user.name'},
12194:                                                           $env{'user.domain'},
12195:                                                           $item,'reload',$context);
12196:                     if (($context eq 'requestcourses') ||
12197:                         ($context eq 'requestauthor')) {
12198:                         if ($env{'environment.canrequest.'.$item} ne $newacc) {
12199:                             $newenv{'environment.canrequest.'.$item} = $newacc;
12200:                         }
12201:                     } else {
12202:                         if ($env{'environment.availabletools.'.$item} ne $newacc) { 
12203:                             $newenv{'environment.availabletools.'.$item} = $newacc;
12204:                         }
12205:                     }
12206:                     unless ($context eq 'requestauthor') {
12207:                         $resulttext .= '<li>'.$titles{$item}.'<ul>';
12208:                     }
12209:                     foreach my $type (@{$types},'default','_LC_adv') {
12210:                         if ($haschgs{$type}) {
12211:                             my $typetitle = $usertypes->{$type};
12212:                             if ($type eq 'default') {
12213:                                 $typetitle = $othertitle;
12214:                             } elsif ($type eq '_LC_adv') {
12215:                                 $typetitle = 'LON-CAPA Advanced Users'; 
12216:                             }
12217:                             if ($inconf{$type}) {
12218:                                 if ($context eq 'requestcourses') {
12219:                                     my $cond;
12220:                                     if ($inconf{$type} =~ /^autolimit=(\d*)$/) {
12221:                                         if ($1 eq '') {
12222:                                             $cond = &mt('(Automatic processing of any request).');
12223:                                         } else {
12224:                                             $cond = &mt('(Automatic processing of requests up to limit of [quant,_1,request] per user).',$1);
12225:                                         }
12226:                                     } else { 
12227:                                         $cond = $conditions{$inconf{$type}};
12228:                                     }
12229:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1].',$typetitle).' '.$cond.'</li>';
12230:                                 } elsif ($context eq 'requestauthor') {
12231:                                     $resulttext .= '<li>'.&mt('Set to "[_1]" for "[_2]".',
12232:                                                              $titles{$inconf{$type}},$typetitle);
12233: 
12234:                                 } else {
12235:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1]',$typetitle).'</li>';
12236:                                 }
12237:                             } else {
12238:                                 if ($type eq '_LC_adv') {
12239:                                     if ($inconf{$type} eq '0') {
12240:                                         $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
12241:                                     } else { 
12242:                                         $resulttext .= '<li>'.&mt('No override set for [_1]',$typetitle).'</li>';
12243:                                     }
12244:                                 } else {
12245:                                     $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
12246:                                 }
12247:                             }
12248:                         }
12249:                     }
12250:                     unless ($context eq 'requestauthor') {
12251:                         $resulttext .= '</ul></li>';
12252:                     }
12253:                 }
12254:             }
12255:             if (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
12256:                 if (ref($changes{'notify'}) eq 'HASH') {
12257:                     if ($changes{'notify'}{'approval'}) {
12258:                         if (ref($confhash{'notify'}) eq 'HASH') {
12259:                             if ($confhash{'notify'}{'approval'}) {
12260:                                 $resulttext .= '<li>'.&mt('Notification of requests requiring approval will be sent to: ').$confhash{'notify'}{'approval'}.'</li>';
12261:                             } else {
12262:                                 $resulttext .= '<li>'.&mt('No Domain Coordinators will receive notification of requests requiring approval.').'</li>';
12263:                             }
12264:                         }
12265:                     }
12266:                 }
12267:             }
12268:             if ($action eq 'requestcourses') {
12269:                 my @offon = ('off','on');
12270:                 if ($changes{'uniquecode'}) {
12271:                     if (ref($confhash{'uniquecode'}) eq 'HASH') {
12272:                         my $codestr = join(' ',map{ &mt($_); } sort(keys(%{$confhash{'uniquecode'}})));
12273:                         $resulttext .= '<li>'.
12274:                                        &mt('Generation of six character code as course identifier for distribution to students set to on for: [_1].','<b>'.$codestr.'</b>').
12275:                                        '</li>';
12276:                     } else {
12277:                         $resulttext .= '<li>'.&mt('Generation of six character code as course identifier for distribution to students set to off.').
12278:                                        '</li>';
12279:                     }
12280:                 }
12281:                 foreach my $type ('textbooks','templates') {
12282:                     if (ref($changes{$type}) eq 'HASH') {
12283:                         $resulttext .= '<li>'.&mt("Available $type updated").'<ul>';
12284:                         foreach my $key (sort(keys(%{$changes{$type}}))) {
12285:                             my %coursehash = &Apache::lonnet::coursedescription($key);
12286:                             my $coursetitle = $coursehash{'description'};
12287:                             my $position = $confhash{$type}{$key}{'order'} + 1;
12288:                             $resulttext .= '<li>';
12289:                             foreach my $item ('subject','title','publisher','author') {
12290:                                 next if ((($item eq 'author') || ($item eq 'publisher')) &&
12291:                                          ($type eq 'templates'));
12292:                                 my $name = $item.':';
12293:                                 $name =~ s/^(\w)/\U$1/;
12294:                                 $resulttext .= &mt($name).' '.$confhash{$type}{$key}{$item}.'<br />';
12295:                             }
12296:                             $resulttext .= ' '.&mt('Order: [_1]',$position).'<br />';
12297:                             if ($type eq 'textbooks') {
12298:                                 if ($confhash{$type}{$key}{'image'}) {
12299:                                     $resulttext .= ' '.&mt('Image: [_1]',
12300:                                                    '<img src="'.$confhash{$type}{$key}{'image'}.'"'.
12301:                                                    ' alt="Textbook cover" />').'<br />';
12302:                                 }
12303:                             }
12304:                             $resulttext .= ' '.&mt('LON-CAPA Course: [_1]',$coursetitle).'</li>';
12305:                         }
12306:                         $resulttext .= '</ul></li>';
12307:                     }
12308:                 }
12309:                 if (ref($changes{'validation'}) eq 'HASH') {
12310:                     if ((ref($validationitemsref) eq 'ARRAY') && (ref($validationnamesref) eq 'HASH')) {
12311:                         $resulttext .= '<li>'.&mt('Validation of courses/communities updated').'<ul>';
12312:                         foreach my $item (@{$validationitemsref}) {
12313:                             if (exists($changes{'validation'}{$item})) {
12314:                                 if ($item eq 'markup') {
12315:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
12316:                                                               '<br /><pre>'.$changes{'validation'}{$item}.'</pre>').'</li>';
12317:                                 } else {
12318:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
12319:                                                               '<b>'.$changes{'validation'}{$item}.'</b>').'</li>';
12320:                                 }
12321:                             }
12322:                         }
12323:                         if (exists($changes{'validation'}{'dc'})) {
12324:                             $resulttext .= '<li>'.&mt('Validated course requests identified as processed by: [_1]',
12325:                                                      '<b>'.$changes{'validation'}{'dc'}.'</b>').'</li>';
12326:                         }
12327:                     }
12328:                 }
12329:             }
12330:             $resulttext .= '</ul>';
12331:             if (keys(%newenv)) {
12332:                 &Apache::lonnet::appenv(\%newenv);
12333:             }
12334:         } else {
12335:             if ($context eq 'requestcourses') {
12336:                 $resulttext = &mt('No changes made to rights to request creation of courses.');
12337:             } elsif ($context eq 'requestauthor') {
12338:                 $resulttext = &mt('No changes made to rights to request author space.');
12339:             } else {
12340:                 $resulttext = &mt('No changes made to availability of personal information pages, blogs, portfolios or default quotas');
12341:             }
12342:         }
12343:     } else {
12344:         $resulttext = '<span class="LC_error">'.
12345: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
12346:     }
12347:     if ($errors) {
12348:         $resulttext .= '<p>'.&mt('The following errors occurred when modifying Textbook settings.').
12349:                        '<ul>'.$errors.'</ul></p>';
12350:     }
12351:     return $resulttext;
12352: }
12353: 
12354: sub process_textbook_image {
12355:     my ($r,$dom,$confname,$caller,$cdom,$cnum,$type,$configuserok,$switchserver,$author_ok) = @_;
12356:     my $filename = $env{'form.'.$caller.'.filename'};
12357:     my ($error,$url);
12358:     my ($width,$height) = (50,50);
12359:     if ($configuserok eq 'ok') {
12360:         if ($switchserver) {
12361:             $error = &mt('Upload of textbook image is not permitted to this server: [_1]',
12362:                          $switchserver);
12363:         } elsif ($author_ok eq 'ok') {
12364:             my ($result,$imageurl) =
12365:                 &publishlogo($r,'upload',$caller,$dom,$confname,
12366:                              "$type/$cdom/$cnum/cover",$width,$height);
12367:             if ($result eq 'ok') {
12368:                 $url = $imageurl;
12369:             } else {
12370:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
12371:             }
12372:         } else {
12373:             $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);
12374:         }
12375:     } else {
12376:         $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);
12377:     }
12378:     return ($url,$error);
12379: }
12380: 
12381: sub modify_ltitools {
12382:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
12383:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
12384:     my ($newid,@allpos,%changes,%confhash,%encconfig,$errors,$resulttext);
12385:     my $confname = $dom.'-domainconfig';
12386:     my $servadm = $r->dir_config('lonAdmEMail');
12387:     my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
12388:     my (%posslti,%possfield);
12389:     my @courseroles = ('cc','in','ta','ep','st');
12390:     my @ltiroles = qw(Instructor ContentDeveloper TeachingAssistant Learner);
12391:     map { $posslti{$_} = 1; } @ltiroles;
12392:     my @allfields = ('fullname','firstname','lastname','email','user','roles');
12393:     map { $possfield{$_} = 1; } @allfields;
12394:     my %lt = &ltitools_names();
12395:     if ($env{'form.ltitools_add'}) {
12396:         my $title = $env{'form.ltitools_add_title'};
12397:         $title =~ s/(`)/'/g;
12398:         ($newid,my $error) = &get_ltitools_id($dom,$title);
12399:         if ($newid) {
12400:             my $position = $env{'form.ltitools_add_pos'};
12401:             $position =~ s/\D+//g;
12402:             if ($position ne '') {
12403:                 $allpos[$position] = $newid;
12404:             }
12405:             $changes{$newid} = 1;
12406:             foreach my $item ('title','url','key','secret','lifetime') {
12407:                 $env{'form.ltitools_add_'.$item} =~ s/(`)/'/g;
12408:                 if ($item eq 'lifetime') {
12409:                     $env{'form.ltitools_add_'.$item} =~ s/[^\d.]//g;
12410:                 }
12411:                 if ($env{'form.ltitools_add_'.$item}) {
12412:                     if (($item eq 'key') || ($item eq 'secret')) {
12413:                         $encconfig{$newid}{$item} = $env{'form.ltitools_add_'.$item};
12414:                     } else {
12415:                         $confhash{$newid}{$item} = $env{'form.ltitools_add_'.$item};
12416:                     }
12417:                 }
12418:             }
12419:             if ($env{'form.ltitools_add_version'} eq 'LTI-1p0') {
12420:                 $confhash{$newid}{'version'} = $env{'form.ltitools_add_version'};
12421:             }
12422:             if ($env{'form.ltitools_add_msgtype'} eq 'basic-lti-launch-request') {
12423:                 $confhash{$newid}{'msgtype'} = $env{'form.ltitools_add_msgtype'};
12424:             }
12425:             if ($env{'form.ltitools_add_sigmethod'} eq 'HMAC-SHA256') {
12426:                 $confhash{$newid}{'sigmethod'} = $env{'form.ltitools_add_sigmethod'};
12427:             } else {
12428:                 $confhash{$newid}{'sigmethod'} = 'HMAC-SHA1';
12429:             }
12430:             foreach my $item ('width','height','linktext','explanation') {
12431:                 $env{'form.ltitools_add_'.$item} =~ s/^\s+//;
12432:                 $env{'form.ltitools_add_'.$item} =~ s/\s+$//;
12433:                 if (($item eq 'width') || ($item eq 'height')) {
12434:                     if ($env{'form.ltitools_add_'.$item} =~ /^\d+$/) {
12435:                         $confhash{$newid}{'display'}{$item} = $env{'form.ltitools_add_'.$item};
12436:                     }
12437:                 } else {
12438:                     if ($env{'form.ltitools_add_'.$item} ne '') {
12439:                         $confhash{$newid}{'display'}{$item} = $env{'form.ltitools_add_'.$item};
12440:                     }
12441:                 }
12442:             }
12443:             if ($env{'form.ltitools_add_target'} eq 'window') {
12444:                 $confhash{$newid}{'display'}{'target'} = $env{'form.ltitools_add_target'};
12445:             } elsif ($env{'form.ltitools_add_target'} eq 'tab') {
12446:                 $confhash{$newid}{'display'}{'target'} = $env{'form.ltitools_add_target'};
12447:             } else {
12448:                 $confhash{$newid}{'display'}{'target'} = 'iframe';
12449:             }
12450:             if ($env{'form.ltitools_add_image.filename'} ne '') {
12451:                 my ($imageurl,$error) =
12452:                     &process_ltitools_image($r,$dom,$confname,'ltitools_add_image',$newid,
12453:                                             $configuserok,$switchserver,$author_ok);
12454:                 if ($imageurl) {
12455:                     $confhash{$newid}{'image'} = $imageurl;
12456:                 }
12457:                 if ($error) {
12458:                     &Apache::lonnet::logthis($error);
12459:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12460:                 }
12461:             }
12462:             my @fields = &Apache::loncommon::get_env_multiple('form.ltitools_add_fields');
12463:             foreach my $field (@fields) {
12464:                 if ($possfield{$field}) {
12465:                     if ($field eq 'roles') {
12466:                         foreach my $role (@courseroles) {
12467:                             my $choice = $env{'form.ltitools_add_roles_'.$role};
12468:                             if (($choice ne '') && ($posslti{$choice})) {
12469:                                 $confhash{$newid}{'roles'}{$role} = $choice;
12470:                                 if ($role eq 'cc') {
12471:                                     $confhash{$newid}{'roles'}{'co'} = $choice;
12472:                                 }
12473:                             }
12474:                         }
12475:                     } else {
12476:                         $confhash{$newid}{'fields'}{$field} = 1;
12477:                     }
12478:                 }
12479:             }
12480:             if (ref($confhash{$newid}{'fields'}) eq 'HASH') {
12481:                 if ($confhash{$newid}{'fields'}{'user'}) {
12482:                     if ($env{'form.ltitools_userincdom_add'}) {
12483:                         $confhash{$newid}{'incdom'} = 1;
12484:                     }
12485:                 }
12486:             }
12487:             my @courseconfig = &Apache::loncommon::get_env_multiple('form.ltitools_courseconfig');
12488:             foreach my $item (@courseconfig) {
12489:                 $confhash{$newid}{'crsconf'}{$item} = 1;
12490:             }
12491:             if ($env{'form.ltitools_add_custom'}) {
12492:                 my $name = $env{'form.ltitools_add_custom_name'};
12493:                 my $value = $env{'form.ltitools_add_custom_value'};
12494:                 $value =~ s/(`)/'/g;
12495:                 $name =~ s/(`)/'/g;
12496:                 $confhash{$newid}{'custom'}{$name} = $value;
12497:             }
12498:         } else {
12499:             my $error = &mt('Failed to acquire unique ID for new external tool');
12500:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12501:         }
12502:     }
12503:     if (ref($domconfig{$action}) eq 'HASH') {
12504:         my %deletions;
12505:         my @todelete = &Apache::loncommon::get_env_multiple('form.ltitools_del');
12506:         if (@todelete) {
12507:             map { $deletions{$_} = 1; } @todelete;
12508:         }
12509:         my %customadds;
12510:         my @newcustom = &Apache::loncommon::get_env_multiple('form.ltitools_customadd');
12511:         if (@newcustom) {
12512:             map { $customadds{$_} = 1; } @newcustom;
12513:         }
12514:         my %imgdeletions;
12515:         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.ltitools_image_del');
12516:         if (@todeleteimages) {
12517:             map { $imgdeletions{$_} = 1; } @todeleteimages;
12518:         }
12519:         my $maxnum = $env{'form.ltitools_maxnum'};
12520:         for (my $i=0; $i<=$maxnum; $i++) {
12521:             my $itemid = $env{'form.ltitools_id_'.$i};
12522:             $itemid =~ s/\D+//g;
12523:             if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
12524:                 if ($deletions{$itemid}) {
12525:                     if ($domconfig{$action}{$itemid}{'image'}) {
12526:                         #FIXME need to obsolete item in RES space
12527:                     }
12528:                     $changes{$itemid} = $domconfig{$action}{$itemid}{'title'};
12529:                     next;
12530:                 } else {
12531:                     my $newpos = $env{'form.ltitools_'.$itemid};
12532:                     $newpos =~ s/\D+//g;
12533:                     foreach my $item ('title','url','lifetime') {
12534:                         $confhash{$itemid}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
12535:                         if ($domconfig{$action}{$itemid}{$item} ne $confhash{$itemid}{$item}) {
12536:                             $changes{$itemid} = 1;
12537:                         }
12538:                     }
12539:                     foreach my $item ('key','secret') {
12540:                         $encconfig{$itemid}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
12541:                         if ($domconfig{$action}{$itemid}{$item} ne $encconfig{$itemid}{$item}) {
12542:                             $changes{$itemid} = 1;
12543:                         }
12544:                     }
12545:                     if ($env{'form.ltitools_version_'.$i} eq 'LTI-1p0') {
12546:                         $confhash{$itemid}{'version'} = $env{'form.ltitools_version_'.$i};
12547:                     }
12548:                     if ($env{'form.ltitools_msgtype_'.$i} eq 'basic-lti-launch-request') {
12549:                         $confhash{$itemid}{'msgtype'} = $env{'form.ltitools_msgtype_'.$i};
12550:                     }
12551:                     if ($env{'form.ltitools_sigmethod_'.$i} eq 'HMAC-SHA256') {
12552:                         $confhash{$itemid}{'sigmethod'} = $env{'form.ltitools_sigmethod_'.$i};
12553:                     } else {
12554:                         $confhash{$itemid}{'sigmethod'} = 'HMAC-SHA1';
12555:                     }
12556:                     if ($domconfig{$action}{$itemid}{'sigmethod'} eq '') {
12557:                         if ($confhash{$itemid}{'sigmethod'} ne 'HMAC-SHA1') {
12558:                             $changes{$itemid} = 1;
12559:                         }
12560:                     } elsif ($domconfig{$action}{$itemid}{'sigmethod'} ne $confhash{$itemid}{'sigmethod'}) {
12561:                         $changes{$itemid} = 1;
12562:                     }
12563:                     foreach my $size ('width','height') {
12564:                         $env{'form.ltitools_'.$size.'_'.$i} =~ s/^\s+//;
12565:                         $env{'form.ltitools_'.$size.'_'.$i} =~ s/\s+$//;
12566:                         if ($env{'form.ltitools_'.$size.'_'.$i} =~ /^\d+$/) {
12567:                             $confhash{$itemid}{'display'}{$size} = $env{'form.ltitools_'.$size.'_'.$i};
12568:                             if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
12569:                                 if ($domconfig{$action}{$itemid}{'display'}{$size} ne $confhash{$itemid}{'display'}{$size}) {
12570:                                     $changes{$itemid} = 1;
12571:                                 }
12572:                             } else {
12573:                                 $changes{$itemid} = 1;
12574:                             }
12575:                         } elsif (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
12576:                             if ($domconfig{$action}{$itemid}{'display'}{$size} ne '') {
12577:                                 $changes{$itemid} = 1;
12578:                             }
12579:                         }
12580:                     }
12581:                     foreach my $item ('linktext','explanation') {
12582:                         $env{'form.ltitools_'.$item.'_'.$i} =~ s/^\s+//;
12583:                         $env{'form.ltitools_'.$item.'_'.$i} =~ s/\s+$//;
12584:                         if ($env{'form.ltitools_'.$item.'_'.$i} ne '') {
12585:                             $confhash{$itemid}{'display'}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
12586:                             if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
12587:                                 if ($domconfig{$action}{$itemid}{'display'}{$item} ne $confhash{$itemid}{'display'}{$item}) {
12588:                                     $changes{$itemid} = 1;
12589:                                 }
12590:                             } else {
12591:                                 $changes{$itemid} = 1;
12592:                             }
12593:                         } elsif (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
12594:                             if ($domconfig{$action}{$itemid}{'display'}{$item} ne '') {
12595:                                 $changes{$itemid} = 1;
12596:                             }
12597:                         }
12598:                     }
12599:                     if ($env{'form.ltitools_target_'.$i} eq 'window') {
12600:                         $confhash{$itemid}{'display'}{'target'} = $env{'form.ltitools_target_'.$i};
12601:                     } elsif ($env{'form.ltitools_target_'.$i} eq 'tab') {
12602:                         $confhash{$itemid}{'display'}{'target'} = $env{'form.ltitools_target_'.$i};
12603:                     } else {
12604:                         $confhash{$itemid}{'display'}{'target'} = 'iframe';
12605:                     }
12606:                     if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
12607:                         if ($domconfig{$action}{$itemid}{'display'}{'target'} ne $confhash{$itemid}{'display'}{'target'}) {
12608:                             $changes{$itemid} = 1;
12609:                         }
12610:                     } else {
12611:                         $changes{$itemid} = 1;
12612:                     }
12613:                     my @courseconfig = &Apache::loncommon::get_env_multiple('form.ltitools_courseconfig_'.$i);
12614:                     foreach my $item ('label','title','target','linktext','explanation','append') {
12615:                         if (grep(/^\Q$item\E$/,@courseconfig)) {
12616:                             $confhash{$itemid}{'crsconf'}{$item} = 1;
12617:                             if (ref($domconfig{$action}{$itemid}{'crsconf'}) eq 'HASH') {
12618:                                 if ($domconfig{$action}{$itemid}{'crsconf'}{$item} ne $confhash{$itemid}{'crsconf'}{$item}) {
12619:                                     $changes{$itemid} = 1;
12620:                                 }
12621:                             } else {
12622:                                 $changes{$itemid} = 1;
12623:                             }
12624:                         }
12625:                     }
12626:                     my @fields = &Apache::loncommon::get_env_multiple('form.ltitools_fields_'.$i);
12627:                     foreach my $field (@fields) {
12628:                         if ($possfield{$field}) {
12629:                             if ($field eq 'roles') {
12630:                                 foreach my $role (@courseroles) {
12631:                                     my $choice = $env{'form.ltitools_roles_'.$role.'_'.$i};
12632:                                     if (($choice ne '') && ($posslti{$choice})) {
12633:                                         $confhash{$itemid}{'roles'}{$role} = $choice;
12634:                                         if ($role eq 'cc') {
12635:                                             $confhash{$itemid}{'roles'}{'co'} = $choice;
12636:                                         }
12637:                                     }
12638:                                     if (ref($domconfig{$action}{$itemid}{'roles'}) eq 'HASH') {
12639:                                         if ($domconfig{$action}{$itemid}{'roles'}{$role} ne $confhash{$itemid}{'roles'}{$role}) {
12640:                                             $changes{$itemid} = 1;
12641:                                         }
12642:                                     } elsif ($confhash{$itemid}{'roles'}{$role}) {
12643:                                         $changes{$itemid} = 1;
12644:                                     }
12645:                                 }
12646:                             } else {
12647:                                 $confhash{$itemid}{'fields'}{$field} = 1;
12648:                                 if (ref($domconfig{$action}{$itemid}{'fields'}) eq 'HASH') {
12649:                                     if ($domconfig{$action}{$itemid}{'fields'}{$field} ne $confhash{$itemid}{'fields'}{$field}) {
12650:                                         $changes{$itemid} = 1;
12651:                                     }
12652:                                 } else {
12653:                                     $changes{$itemid} = 1;
12654:                                 }
12655:                             }
12656:                         }
12657:                     }
12658:                     if (ref($confhash{$itemid}{'fields'}) eq 'HASH') {
12659:                         if ($confhash{$itemid}{'fields'}{'user'}) {
12660:                             if ($env{'form.ltitools_userincdom_'.$i}) {
12661:                                 $confhash{$itemid}{'incdom'} = 1;
12662:                             }
12663:                             if ($domconfig{$action}{$itemid}{'incdom'} ne $confhash{$itemid}{'incdom'}) {
12664:                                 $changes{$itemid} = 1;
12665:                             }
12666:                         }
12667:                     }
12668:                     $allpos[$newpos] = $itemid;
12669:                 }
12670:                 if ($imgdeletions{$itemid}) {
12671:                     $changes{$itemid} = 1;
12672:                     #FIXME need to obsolete item in RES space
12673:                 } elsif ($env{'form.ltitools_image_'.$i.'.filename'}) {
12674:                     my ($imgurl,$error) = &process_ltitools_image($r,$dom,$confname,'ltitools_image_'.$i,
12675:                                                                  $itemid,$configuserok,$switchserver,
12676:                                                                  $author_ok);
12677:                     if ($imgurl) {
12678:                         $confhash{$itemid}{'image'} = $imgurl;
12679:                         $changes{$itemid} = 1;
12680:                     }
12681:                     if ($error) {
12682:                         &Apache::lonnet::logthis($error);
12683:                         $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12684:                     }
12685:                 } elsif ($domconfig{$action}{$itemid}{'image'}) {
12686:                     $confhash{$itemid}{'image'} =
12687:                        $domconfig{$action}{$itemid}{'image'};
12688:                 }
12689:                 if ($customadds{$i}) {
12690:                     my $name = $env{'form.ltitools_custom_name_'.$i};
12691:                     $name =~ s/(`)/'/g;
12692:                     $name =~ s/^\s+//;
12693:                     $name =~ s/\s+$//;
12694:                     my $value = $env{'form.ltitools_custom_value_'.$i};
12695:                     $value =~ s/(`)/'/g;
12696:                     $value =~ s/^\s+//;
12697:                     $value =~ s/\s+$//;
12698:                     if ($name ne '') {
12699:                         $confhash{$itemid}{'custom'}{$name} = $value;
12700:                         $changes{$itemid} = 1;
12701:                     }
12702:                 }
12703:                 my %customdels;
12704:                 my @customdeletions = &Apache::loncommon::get_env_multiple('form.ltitools_customdel_'.$i);
12705:                 if (@customdeletions) {
12706:                     $changes{$itemid} = 1;
12707:                 }
12708:                 map { $customdels{$_} = 1; } @customdeletions;
12709:                 if (ref($domconfig{$action}{$itemid}{'custom'}) eq 'HASH') {
12710:                     foreach my $key (keys(%{$domconfig{$action}{$itemid}{'custom'}})) {
12711:                         unless ($customdels{$key}) {
12712:                             if ($env{'form.ltitools_customval_'.$key.'_'.$i} ne '') {
12713:                                 $confhash{$itemid}{'custom'}{$key} = $env{'form.ltitools_customval_'.$key.'_'.$i};
12714:                             }
12715:                             if ($domconfig{$action}{$itemid}{'custom'}{$key} ne $env{'form.ltitools_customval_'.$key.'_'.$i}) {
12716:                                 $changes{$itemid} = 1;
12717:                             }
12718:                         }
12719:                     }
12720:                 }
12721:                 unless ($changes{$itemid}) {
12722:                     foreach my $key (keys(%{$domconfig{$action}{$itemid}})) {
12723:                         if (ref($domconfig{$action}{$itemid}{$key}) eq 'HASH') {
12724:                             if (ref($confhash{$itemid}{$key}) eq 'HASH') {
12725:                                 foreach my $innerkey (keys(%{$domconfig{$action}{$itemid}{$key}})) {
12726:                                     unless (exists($confhash{$itemid}{$key}{$innerkey})) {
12727:                                         $changes{$itemid} = 1;
12728:                                         last;
12729:                                     }
12730:                                 }
12731:                             } elsif (keys(%{$domconfig{$action}{$itemid}{$key}}) > 0) {
12732:                                 $changes{$itemid} = 1;
12733:                             }
12734:                         }
12735:                         last if ($changes{$itemid});
12736:                     }
12737:                 }
12738:             }
12739:         }
12740:     }
12741:     if (@allpos > 0) {
12742:         my $idx = 0;
12743:         foreach my $itemid (@allpos) {
12744:             if ($itemid ne '') {
12745:                 $confhash{$itemid}{'order'} = $idx;
12746:                 if (ref($domconfig{$action}) eq 'HASH') {
12747:                     if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
12748:                         if ($domconfig{$action}{$itemid}{'order'} ne $idx) {
12749:                             $changes{$itemid} = 1;
12750:                         }
12751:                     }
12752:                 }
12753:                 $idx ++;
12754:             }
12755:         }
12756:     }
12757:     my %ltitoolshash = (
12758:                           $action => { %confhash }
12759:                        );
12760:     my $putresult = &Apache::lonnet::put_dom('configuration',\%ltitoolshash,
12761:                                              $dom);
12762:     if ($putresult eq 'ok') {
12763:         my %ltienchash = (
12764:                              $action => { %encconfig }
12765:                          );
12766:         &Apache::lonnet::put_dom('encconfig',\%ltienchash,$dom,undef,1);
12767:         if (keys(%changes) > 0) {
12768:             my $cachetime = 24*60*60;
12769:             my %ltiall = %confhash;
12770:             foreach my $id (keys(%ltiall)) {
12771:                 if (ref($encconfig{$id}) eq 'HASH') {
12772:                     foreach my $item ('key','secret') {
12773:                         $ltiall{$id}{$item} = $encconfig{$id}{$item};
12774:                     }
12775:                 }
12776:             }
12777:             &Apache::lonnet::do_cache_new('ltitools',$dom,\%ltiall,$cachetime);
12778:             if (ref($lastactref) eq 'HASH') {
12779:                 $lastactref->{'ltitools'} = 1;
12780:             }
12781:             $resulttext = &mt('Changes made:').'<ul>';
12782:             my %bynum;
12783:             foreach my $itemid (sort(keys(%changes))) {
12784:                 my $position = $confhash{$itemid}{'order'};
12785:                 $bynum{$position} = $itemid;
12786:             }
12787:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
12788:                 my $itemid = $bynum{$pos};
12789:                 if (ref($confhash{$itemid}) ne 'HASH') {
12790:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
12791:                 } else {
12792:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'title'}.'</b>';
12793:                     if ($confhash{$itemid}{'image'}) {
12794:                         $resulttext .= '&nbsp;'.
12795:                                        '<img src="'.$confhash{$itemid}{'image'}.'"'.
12796:                                        ' alt="'.&mt('Tool Provider icon').'" />';
12797:                     }
12798:                     $resulttext .= '</li><ul>';
12799:                     my $position = $pos + 1;
12800:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
12801:                     foreach my $item ('version','msgtype','sigmethod','url','lifetime') {
12802:                         if ($confhash{$itemid}{$item} ne '') {
12803:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{$item}.'</li>';
12804:                         }
12805:                     }
12806:                     if ($encconfig{$itemid}{'key'} ne '') {
12807:                         $resulttext .= '<li>'.$lt{'key'}.':&nbsp;'.$encconfig{$itemid}{'key'}.'</li>';
12808:                     }
12809:                     if ($encconfig{$itemid}{'secret'} ne '') {
12810:                         $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;';
12811:                         my $num = length($encconfig{$itemid}{'secret'});
12812:                         $resulttext .= ('*'x$num).'</li>';
12813:                     }
12814:                     $resulttext .= '<li>'.&mt('Configurable in course:');
12815:                     my @possconfig = ('label','title','target','linktext','explanation','append');
12816:                     my $numconfig = 0;
12817:                     if (ref($confhash{$itemid}{'crsconf'}) eq 'HASH') {
12818:                         foreach my $item (@possconfig) {
12819:                             if ($confhash{$itemid}{'crsconf'}{$item}) {
12820:                                 $numconfig ++;
12821:                                 $resulttext .= ' "'.$lt{'crs'.$item}.'"';
12822:                             }
12823:                         }
12824:                     }
12825:                     if (!$numconfig) {
12826:                         $resulttext .= &mt('None');
12827:                     }
12828:                     $resulttext .= '</li>';
12829:                     if (ref($confhash{$itemid}{'display'}) eq 'HASH') {
12830:                         my $displaylist;
12831:                         if ($confhash{$itemid}{'display'}{'target'}) {
12832:                             $displaylist = &mt('Display target').':&nbsp;'.
12833:                                            $confhash{$itemid}{'display'}{'target'}.',';
12834:                         }
12835:                         foreach my $size ('width','height') {
12836:                             if ($confhash{$itemid}{'display'}{$size}) {
12837:                                 $displaylist .= ('&nbsp;'x2).$lt{$size}.':&nbsp;'.
12838:                                                 $confhash{$itemid}{'display'}{$size}.',';
12839:                             }
12840:                         }
12841:                         if ($displaylist) {
12842:                             $displaylist =~ s/,$//;
12843:                             $resulttext .= '<li>'.$displaylist.'</li>';
12844:                         }
12845:                         foreach my $item ('linktext','explanation') {
12846:                             if ($confhash{$itemid}{'display'}{$item}) {
12847:                                 $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{'display'}{$item}.'</li>';
12848:                             }
12849:                         }
12850:                     }
12851:                     if (ref($confhash{$itemid}{'fields'}) eq 'HASH') {
12852:                         my $fieldlist;
12853:                         foreach my $field (@allfields) {
12854:                             if ($confhash{$itemid}{'fields'}{$field}) {
12855:                                 $fieldlist .= ('&nbsp;'x2).$lt{$field}.',';
12856:                             }
12857:                         }
12858:                         if ($fieldlist) {
12859:                             $fieldlist =~ s/,$//;
12860:                             if ($confhash{$itemid}{'fields'}{'user'}) {
12861:                                 if ($confhash{$itemid}{'incdom'}) {
12862:                                     $fieldlist .= ' ('.&mt('username:domain').')';
12863:                                 } else {
12864:                                     $fieldlist .= ' ('.&mt('username').')';
12865:                                 }
12866:                             }
12867:                             $resulttext .= '<li>'.&mt('Data sent').':'.$fieldlist.'</li>';
12868:                         }
12869:                     }
12870:                     if (ref($confhash{$itemid}{'roles'}) eq 'HASH') {
12871:                         my $rolemaps;
12872:                         foreach my $role (@courseroles) {
12873:                             if ($confhash{$itemid}{'roles'}{$role}) {
12874:                                 $rolemaps .= ('&nbsp;'x2).&Apache::lonnet::plaintext($role,'Course').'='.
12875:                                              $confhash{$itemid}{'roles'}{$role}.',';
12876:                             }
12877:                         }
12878:                         if ($rolemaps) {
12879:                             $rolemaps =~ s/,$//;
12880:                             $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
12881:                         }
12882:                     }
12883:                     if (ref($confhash{$itemid}{'custom'}) eq 'HASH') {
12884:                         my $customlist;
12885:                         if (keys(%{$confhash{$itemid}{'custom'}})) {
12886:                             foreach my $key (sort(keys(%{$confhash{$itemid}{'custom'}}))) {
12887:                                 $customlist .= $key.':'.$confhash{$itemid}{'custom'}{$key}.('&nbsp;'x2);
12888:                             }
12889:                         }
12890:                         if ($customlist) {
12891:                             $resulttext .= '<li>'.&mt('Custom items').': '.$customlist.'</li>';
12892:                         }
12893:                     }
12894:                     $resulttext .= '</ul></li>';
12895:                 }
12896:             }
12897:             $resulttext .= '</ul>';
12898:         } else {
12899:             $resulttext = &mt('No changes made.');
12900:         }
12901:     } else {
12902:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
12903:     }
12904:     if ($errors) {
12905:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
12906:                        $errors.'</ul>';
12907:     }
12908:     return $resulttext;
12909: }
12910: 
12911: sub process_ltitools_image {
12912:     my ($r,$dom,$confname,$caller,$itemid,$configuserok,$switchserver,$author_ok) = @_;
12913:     my $filename = $env{'form.'.$caller.'.filename'};
12914:     my ($error,$url);
12915:     my ($width,$height) = (21,21);
12916:     if ($configuserok eq 'ok') {
12917:         if ($switchserver) {
12918:             $error = &mt('Upload of Tool Provider (LTI) icon is not permitted to this server: [_1]',
12919:                          $switchserver);
12920:         } elsif ($author_ok eq 'ok') {
12921:             my ($result,$imageurl,$madethumb) =
12922:                 &publishlogo($r,'upload',$caller,$dom,$confname,
12923:                              "ltitools/$itemid/icon",$width,$height);
12924:             if ($result eq 'ok') {
12925:                 if ($madethumb) {
12926:                     my ($path,$imagefile) = ($imageurl =~ m{^(.+)/([^/]+)$});
12927:                     my $imagethumb = "$path/tn-".$imagefile;
12928:                     $url = $imagethumb;
12929:                 } else {
12930:                     $url = $imageurl;
12931:                 }
12932:             } else {
12933:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
12934:             }
12935:         } else {
12936:             $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);
12937:         }
12938:     } else {
12939:         $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);
12940:     }
12941:     return ($url,$error);
12942: }
12943: 
12944: sub get_ltitools_id {
12945:     my ($cdom,$title) = @_;
12946:     # get lock on ltitools db
12947:     my $lockhash = {
12948:                       lock => $env{'user.name'}.
12949:                               ':'.$env{'user.domain'},
12950:                    };
12951:     my $tries = 0;
12952:     my $gotlock = &Apache::lonnet::newput_dom('ltitools',$lockhash,$cdom);
12953:     my ($id,$error);
12954: 
12955:     while (($gotlock ne 'ok') && ($tries<10)) {
12956:         $tries ++;
12957:         sleep (0.1);
12958:         $gotlock = &Apache::lonnet::newput_dom('ltitools',$lockhash,$cdom);
12959:     }
12960:     if ($gotlock eq 'ok') {
12961:         my %currids = &Apache::lonnet::dump_dom('ltitools',$cdom);
12962:         if ($currids{'lock'}) {
12963:             delete($currids{'lock'});
12964:             if (keys(%currids)) {
12965:                 my @curr = sort { $a <=> $b } keys(%currids);
12966:                 if ($curr[-1] =~ /^\d+$/) {
12967:                     $id = 1 + $curr[-1];
12968:                 }
12969:             } else {
12970:                 $id = 1;
12971:             }
12972:             if ($id) {
12973:                 unless (&Apache::lonnet::newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
12974:                     $error = 'nostore';
12975:                 }
12976:             } else {
12977:                 $error = 'nonumber';
12978:             }
12979:         }
12980:         my $dellockoutcome = &Apache::lonnet::del_dom('ltitools',['lock'],$cdom);
12981:     } else {
12982:         $error = 'nolock';
12983:     }
12984:     return ($id,$error);
12985: }
12986: 
12987: sub modify_lti {
12988:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
12989:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
12990:     my (%encconfig,$errors,$resulttext);
12991: 
12992:     my (%currltisec,%secchanges,%newltisec,%newltienc,%keyset,%newkeyset);
12993:     $newltisec{'private'}{'keys'} = [];
12994:     $newltisec{'encrypt'} = {};
12995:     $newltisec{'rules'} = {};
12996:     $newltisec{'linkprot'} = {};
12997:     if (ref($domconfig{'ltisec'}) eq 'HASH') {
12998:         %currltisec = %{$domconfig{'ltisec'}};
12999:         if (ref($currltisec{'linkprot'}) eq 'HASH') {
13000:             foreach my $id (keys(%{$currltisec{'linkprot'}})) {
13001:                 unless ($id =~ /^\d+$/) {
13002:                     delete($currltisec{'linkprot'}{$id});
13003:                 }
13004:             }
13005:         }
13006:         if (ref($currltisec{'private'}) eq 'HASH') {
13007:             if (ref($currltisec{'private'}{'keys'}) eq 'ARRAY') {
13008:                 $newltisec{'private'}{'keys'} = $currltisec{'private'}{'keys'};
13009:                 map { $keyset{$_} = 1; } @{$currltisec{'private'}{'keys'}};
13010:             }
13011:         }
13012:     }
13013:     foreach my $item ('crs','dom') {
13014:         my $formelement = 'form.ltisec_'.$item.'linkprot';
13015:         if ($env{$formelement}) {
13016:             $newltisec{'encrypt'}{$item} = 1;
13017:             if (ref($currltisec{'encrypt'}) eq 'HASH') {
13018:                 unless ($currltisec{'encrypt'}{$item}) {
13019:                     $secchanges{'encrypt'} = 1;
13020:                 }
13021:             } else {
13022:                 $secchanges{'encrypt'} = 1;
13023:             }
13024:         } elsif (ref($currltisec{'encrypt'}) eq 'HASH') {
13025:             if ($currltisec{'encrypt'}{$item}) {
13026:                 $secchanges{'encrypt'} = 1;
13027:             }
13028:         }
13029:     }
13030:     unless (exists($currltisec{'rules'})) {
13031:         $currltisec{'rules'} = {};
13032:     }
13033:     &password_rule_changes('secrets',$newltisec{'rules'},$currltisec{'rules'},\%secchanges);
13034: 
13035:     my @ids=&Apache::lonnet::current_machine_ids();
13036:     my %servers = &Apache::lonnet::get_servers($dom,'library');
13037: 
13038:     foreach my $hostid (keys(%servers)) {
13039:         if (($hostid ne '') && (grep(/^\Q$hostid\E$/,@ids))) {
13040:             my $newkey;
13041:             my $keyitem = 'form.ltisec_privkey_'.$hostid;
13042:             if (exists($env{$keyitem})) {
13043:                 $env{$keyitem} =~ s/(`)/'/g;
13044:                 if ($keyset{$hostid}) {
13045:                     if ($env{'form.ltisec_changeprivkey_'.$hostid}) {
13046:                         if ($env{$keyitem} ne '') {
13047:                             $secchanges{'private'} = 1;
13048:                             $newkeyset{$hostid} = $env{$keyitem};
13049:                         }
13050:                     }
13051:                 } elsif ($env{$keyitem} ne '') {
13052:                     unless (grep(/^\Q$hostid\E$/,@{$newltisec{'private'}{'keys'}})) {
13053:                         push(@{$newltisec{'private'}{'keys'}},$hostid);
13054:                     }
13055:                     $secchanges{'private'} = 1;
13056:                     $newkeyset{$hostid} = $env{$keyitem};
13057:                 }
13058:             }
13059:         }
13060:     }
13061: 
13062:     my (%linkprotchg,$linkprotoutput,$is_home);
13063:     my $proterror = &Apache::courseprefs::process_linkprot($dom,'',$currltisec{'linkprot'},
13064:                                                            \%linkprotchg,'domain');
13065:     my $home = &Apache::lonnet::domain($dom,'primary');
13066:     unless (($home eq 'no_host') || ($home eq '')) {
13067:         my @ids=&Apache::lonnet::current_machine_ids();
13068:         foreach my $id (@ids) { if ($id eq $home) { $is_home=1; } }
13069:     }
13070: 
13071:     if (keys(%linkprotchg)) {
13072:         $secchanges{'linkprot'} = 1;
13073:         my %oldlinkprot;
13074:         if (ref($currltisec{'linkprot'}) eq 'HASH') {
13075:             %oldlinkprot = %{$currltisec{'linkprot'}};
13076:         }
13077:         foreach my $id (keys(%linkprotchg)) {
13078:             if (ref($linkprotchg{$id}) eq 'HASH') {
13079:                 foreach my $inner (keys(%{$linkprotchg{$id}})) {
13080:                     if (($inner eq 'secret') || ($inner eq 'key')) {
13081:                         if ($is_home) {
13082:                             $newltienc{$id}{$inner} = $linkprotchg{$id}{$inner};
13083:                         }
13084:                     }
13085:                 }
13086:             } else {
13087:                 $newltisec{'linkprot'}{$id} = $linkprotchg{$id};
13088:             }
13089:         }
13090:         $linkprotoutput = &Apache::courseprefs::store_linkprot($dom,'','domain',\%linkprotchg,\%oldlinkprot);
13091:         if (keys(%linkprotchg)) {
13092:             %{$newltisec{'linkprot'}} = %linkprotchg;
13093:         }
13094:     }
13095:     if (ref($currltisec{'linkprot'}) eq 'HASH') {
13096:         foreach my $id (%{$currltisec{'linkprot'}}) {
13097:             next if ($id !~ /^\d+$/);
13098:             unless (exists($linkprotchg{$id})) {
13099:                 if (ref($currltisec{'linkprot'}{$id}) eq 'HASH') {
13100:                     foreach my $inner (keys(%{$currltisec{'linkprot'}{$id}})) {
13101:                         if (($inner eq 'secret') || ($inner eq 'key')) {
13102:                             if ($is_home) {
13103:                                 $newltienc{$id}{$inner} = $currltisec{'linkprot'}{$id}{$inner};
13104:                             }
13105:                         } else {
13106:                             $newltisec{'linkprot'}{$id}{$inner} = $currltisec{'linkprot'}{$id}{$inner};
13107:                         }
13108:                     }
13109:                 } else {
13110:                     $newltisec{'linkprot'}{$id} = $currltisec{'linkprot'}{$id};
13111:                 }
13112:             }
13113:         }
13114:     }
13115:     if ($proterror) {
13116:         $errors .= '<li>'.$proterror.'</li>';
13117:     }
13118: 
13119:     my ($putresult,%keystore);
13120:     if (keys(%secchanges)) {
13121:         my %ltienchash;
13122:         my %ltihash = (
13123:                           'ltisec' => { %newltisec }
13124:                       );
13125:         $putresult = &Apache::lonnet::put_dom('configuration',\%ltihash,$dom);
13126:         if ($putresult eq 'ok') {
13127:             if ($secchanges{'private'}) {
13128:                 my $who = &escape($env{'user.name'}.':'.$env{'user.domain'});
13129:                 foreach my $hostid (keys(%newkeyset)) {
13130:                     my $storehash = {
13131:                                        key => $newkeyset{$hostid},
13132:                                        who => $env{'user.name'}.':'.$env{'user.domain'},
13133:                                     };
13134:                     $keystore{$hostid} = &Apache::lonnet::store_dom($storehash,'lti','private',
13135:                                                                     $dom,$hostid);
13136:                 }
13137:             }
13138:             if (ref($lastactref) eq 'HASH') {
13139:                 if (($secchanges{'encrypt'}) || ($secchanges{'private'})) {
13140:                     $lastactref->{'domdefaults'} = 1;
13141:                 }
13142:             }
13143:             if (($secchanges{'linkprot'}) && ($is_home)) {
13144:                 my %ltienchash = (
13145:                                      'linkprot' =>  { %newltienc }
13146:                                  );
13147:                 &Apache::lonnet::put_dom('encconfig',\%ltienchash,$dom,undef,1);
13148:             }
13149:         }
13150:     } else {
13151:         return &mt('No changes made.');
13152:     }
13153:     if ($putresult eq 'ok') {
13154:         $resulttext = &mt('Changes made:').'<ul>';
13155:         foreach my $item (keys(%secchanges)) {
13156:             if ($item eq 'encrypt') {
13157:                 my %encrypted = (
13158:                           crs  => {
13159:                                     on => &mt('Encryption of stored link protection secrets defined in courses enabled'),
13160:                                     off => &mt('Encryption of stored link protection secrets defined in courses disabled'),
13161:                                   },
13162:                           dom => {
13163:                                    on => &mt('Encryption of stored link protection secrets defined in domain enabled'),
13164:                                    off => &mt('Encryption of stored link protection secrets defined in domain disabled'),
13165:                                  },
13166:                 );
13167:                 foreach my $type ('crs','dom') {
13168:                     my $shown = $encrypted{$type}{'off'};
13169:                     if (ref($newltisec{$item}) eq 'HASH') {
13170:                         if ($newltisec{$item}{$type}) {
13171:                             $shown = $encrypted{$type}{'on'};
13172:                         }
13173:                     }
13174:                     $resulttext .= '<li>'.$shown.'</li>';
13175:                 }
13176:             } elsif ($item eq 'rules') {
13177:                 my %titles = &Apache::lonlocal::texthash(
13178:                                   min   => 'Minimum password length',
13179:                                   max   => 'Maximum password length',
13180:                                   chars => 'Required characters',
13181:                 );
13182:                 foreach my $rule ('min','max') {
13183:                     if ($newltisec{rules}{$rule} eq '') {
13184:                         if ($rule eq 'min') {
13185:                             $resulttext .= '<li>'.&mt('[_1] not set.',$titles{$rule});
13186:                                            ' '.&mt('Default of [_1] will be used',
13187:                                                        $Apache::lonnet::passwdmin).'</li>';
13188:                         } else {
13189:                             $resulttext .= '<li>'.&mt('[_1] set to none',$titles{$rule}).'</li>';
13190:                         }
13191:                     } else {
13192:                         $resulttext .= '<li>'.&mt('[_1] set to [_2]',$titles{$rule},$newltisec{rules}{$rule}).'</li>';
13193:                     }
13194:                 }
13195:                 if (ref($newltisec{'rules'}{'chars'}) eq 'ARRAY') {
13196:                     if (@{$newltisec{'rules'}{'chars'}} > 0) {
13197:                         my %rulenames = &Apache::lonlocal::texthash(
13198:                                             uc => 'At least one upper case letter',
13199:                                             lc => 'At least one lower case letter',
13200:                                             num => 'At least one number',
13201:                                             spec => 'At least one non-alphanumeric',
13202:                                             );
13203:                         my $needed = '<ul><li>'.
13204:                                      join('</li><li>',map {$rulenames{$_} } @{$newltisec{'rules'}{'chars'}}).
13205:                                      '</li></ul>';
13206:                         $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$titles{'chars'},$needed).'</li>';
13207:                     } else {
13208:                         $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
13209:                     }
13210:                 } else {
13211:                     $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
13212:                 }
13213:             } elsif ($item eq 'private') {
13214:                 if (keys(%newkeyset)) {
13215:                     foreach my $hostid (sort(keys(%newkeyset))) {
13216:                         if ($keystore{$hostid} eq 'ok') {
13217:                             $resulttext .= '<li>'.&mt('Encryption key for storage of shared secrets saved for [_1]',$hostid).'</li>';
13218:                         }
13219:                     }
13220:                 }
13221:             } elsif ($item eq 'linkprot') {
13222:                 $resulttext .= $linkprotoutput;
13223:             }
13224:         }
13225:         $resulttext .= '</ul>';
13226:     } else {
13227:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
13228:     }
13229:     if ($errors) {
13230:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
13231:                        $errors.'</ul>';
13232:     }
13233:     return $resulttext;
13234: }
13235: 
13236: sub modify_autoenroll {
13237:     my ($dom,$lastactref,%domconfig) = @_;
13238:     my ($resulttext,%changes);
13239:     my %currautoenroll;
13240:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
13241:         foreach my $key (keys(%{$domconfig{'autoenroll'}})) {
13242:             $currautoenroll{$key} = $domconfig{'autoenroll'}{$key};
13243:         }
13244:     }
13245:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
13246:     my %title = ( run => 'Auto-enrollment active',
13247:                   sender => 'Sender for notification messages',
13248:                   coowners => 'Automatic assignment of co-ownership to instructors of record (institutional data)',
13249:                   autofailsafe => 'Failsafe for no drops if institutional data missing for a section');
13250:     my @offon = ('off','on');
13251:     my $sender_uname = $env{'form.sender_uname'};
13252:     my $sender_domain = $env{'form.sender_domain'};
13253:     if ($sender_domain eq '') {
13254:         $sender_uname = '';
13255:     } elsif ($sender_uname eq '') {
13256:         $sender_domain = '';
13257:     }
13258:     my $coowners = $env{'form.autoassign_coowners'};
13259:     my $autofailsafe = $env{'form.autoenroll_autofailsafe'};
13260:     $autofailsafe =~ s{^\s+|\s+$}{}g;
13261:     if ($autofailsafe =~ /\D/) {
13262:         undef($autofailsafe);
13263:     }
13264:     my $failsafe = $env{'form.autoenroll_failsafe'};
13265:     unless (($failsafe eq 'zero') || ($failsafe eq 'any')) {
13266:         $failsafe = 'off';
13267:         undef($autofailsafe);
13268:     }
13269:     my %autoenrollhash =  (
13270:                        autoenroll => { 'run' => $env{'form.autoenroll_run'},
13271:                                        'sender_uname' => $sender_uname,
13272:                                        'sender_domain' => $sender_domain,
13273:                                        'co-owners' => $coowners,
13274:                                        'autofailsafe' => $autofailsafe,
13275:                                        'failsafe' => $failsafe,
13276:                                 }
13277:                      );
13278:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autoenrollhash,
13279:                                              $dom);
13280:     if ($putresult eq 'ok') {
13281:         if (exists($currautoenroll{'run'})) {
13282:              if ($currautoenroll{'run'} ne $env{'form.autoenroll_run'}) {
13283:                  $changes{'run'} = 1;
13284:              }
13285:         } elsif ($autorun) {
13286:             if ($env{'form.autoenroll_run'} ne '1') {
13287:                  $changes{'run'} = 1;
13288:             }
13289:         }
13290:         if ($currautoenroll{'sender_uname'} ne $sender_uname) {
13291:             $changes{'sender'} = 1;
13292:         }
13293:         if ($currautoenroll{'sender_domain'} ne $sender_domain) {
13294:             $changes{'sender'} = 1;
13295:         }
13296:         if ($currautoenroll{'co-owners'} ne '') {
13297:             if ($currautoenroll{'co-owners'} ne $coowners) {
13298:                 $changes{'coowners'} = 1;
13299:             }
13300:         } elsif ($coowners) {
13301:             $changes{'coowners'} = 1;
13302:         }
13303:         if ($currautoenroll{'autofailsafe'} ne $autofailsafe) {
13304:             $changes{'autofailsafe'} = 1;
13305:         }
13306:         if ($currautoenroll{'failsafe'} ne $failsafe) {
13307:             $changes{'failsafe'} = 1;
13308:         }
13309:         if (keys(%changes) > 0) {
13310:             $resulttext = &mt('Changes made:').'<ul>';
13311:             if ($changes{'run'}) {
13312:                 $resulttext .= '<li>'.&mt("$title{'run'} set to $offon[$env{'form.autoenroll_run'}]").'</li>';
13313:             }
13314:             if ($changes{'sender'}) {
13315:                 if ($sender_uname eq '' || $sender_domain eq '') {
13316:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to default (course owner).").'</li>';
13317:                 } else {
13318:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to [_1]",$sender_uname.':'.$sender_domain).'</li>';
13319:                 }
13320:             }
13321:             if ($changes{'coowners'}) {
13322:                 $resulttext .= '<li>'.&mt("$title{'coowners'} set to $offon[$env{'form.autoassign_coowners'}]").'</li>';
13323:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
13324:                 if (ref($lastactref) eq 'HASH') {
13325:                     $lastactref->{'domainconfig'} = 1;
13326:                 }
13327:             }
13328:             if ($changes{'autofailsafe'}) {
13329:                 if ($autofailsafe ne '') {
13330:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section set to: [_1]',$autofailsafe).'</li>';
13331:                 } else {
13332:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section not in use').'</li>';
13333:                 }
13334:             }
13335:             if ($changes{'failsafe'}) {
13336:                 if ($failsafe eq 'off') {
13337:                     unless ($changes{'autofailsafe'}) {
13338:                         $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section not in use').'</li>';
13339:                     }
13340:                 } elsif ($failsafe eq 'zero') {
13341:                     $resulttext .= '<li>'.&mt('Failsafe applies if retrieved section enrollment is zero').'</li>';
13342:                 } else {
13343:                     $resulttext .= '<li>'.&mt('Failsafe applies if retrieved section enrollment is zero or greater').'</li>';
13344:                 }
13345:             }
13346:             if (($changes{'autofailsafe'}) || ($changes{'failsafe'})) {
13347:                 &Apache::lonnet::get_domain_defaults($dom,1);
13348:                 if (ref($lastactref) eq 'HASH') {
13349:                     $lastactref->{'domdefaults'} = 1;
13350:                 }
13351:             }
13352:             $resulttext .= '</ul>';
13353:         } else {
13354:             $resulttext = &mt('No changes made to auto-enrollment settings');
13355:         }
13356:     } else {
13357:         $resulttext = '<span class="LC_error">'.
13358: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
13359:     }
13360:     return $resulttext;
13361: }
13362: 
13363: sub modify_autoupdate {
13364:     my ($dom,%domconfig) = @_;
13365:     my ($resulttext,%currautoupdate,%fields,%changes);
13366:     if (ref($domconfig{'autoupdate'}) eq 'HASH') {
13367:         foreach my $key (keys(%{$domconfig{'autoupdate'}})) {
13368:             $currautoupdate{$key} = $domconfig{'autoupdate'}{$key};
13369:         }
13370:     }
13371:     my @offon = ('off','on');
13372:     my %title = &Apache::lonlocal::texthash (
13373:                     run        => 'Auto-update:',
13374:                     classlists => 'Updates to user information in classlists?',
13375:                     unexpired  => 'Skip updates for users without active or future roles?',
13376:                     lastactive => 'Skip updates for inactive users?',
13377:                 );
13378:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
13379:     my %fieldtitles = &Apache::lonlocal::texthash (
13380:                         id => 'Student/Employee ID',
13381:                         permanentemail => 'E-mail address',
13382:                         lastname => 'Last Name',
13383:                         firstname => 'First Name',
13384:                         middlename => 'Middle Name',
13385:                         generation => 'Generation',
13386:                       );
13387:     $othertitle = &mt('All users');
13388:     if (keys(%{$usertypes}) >  0) {
13389:         $othertitle = &mt('Other users');
13390:     }
13391:     foreach my $key (keys(%env)) {
13392:         if ($key =~ /^form\.updateable_(.+)_([^_]+)$/) {
13393:             my ($usertype,$item) = ($1,$2);
13394:             if (grep(/^\Q$item\E$/,keys(%fieldtitles))) {
13395:                 if ($usertype eq 'default') {   
13396:                     push(@{$fields{$1}},$2);
13397:                 } elsif (ref($types) eq 'ARRAY') {
13398:                     if (grep(/^\Q$usertype\E$/,@{$types})) {
13399:                         push(@{$fields{$1}},$2);
13400:                     }
13401:                 }
13402:             }
13403:         }
13404:     }
13405:     my @lockablenames = &Apache::loncommon::get_env_multiple('form.lockablenames');
13406:     @lockablenames = sort(@lockablenames);
13407:     if (ref($currautoupdate{'lockablenames'}) eq 'ARRAY') {
13408:         my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
13409:         if (@changed) {
13410:             $changes{'lockablenames'} = 1;
13411:         }
13412:     } else {
13413:         if (@lockablenames) {
13414:             $changes{'lockablenames'} = 1;
13415:         }
13416:     }
13417:     my %updatehash = (
13418:                       autoupdate => { run => $env{'form.autoupdate_run'},
13419:                                       classlists => $env{'form.classlists'},
13420:                                       unexpired  => $env{'form.unexpired'},
13421:                                       fields => {%fields},
13422:                                       lockablenames => \@lockablenames,
13423:                                     }
13424:                      );
13425:     my $lastactivedays;
13426:     if ($env{'form.lastactive'}) {
13427:         $lastactivedays = $env{'form.lastactivedays'};
13428:         $lastactivedays =~ s/^\s+|\s+$//g;
13429:         unless ($lastactivedays =~ /^\d+$/) {
13430:             undef($lastactivedays);
13431:             $env{'form.lastactive'} = 0;
13432:         }
13433:     }
13434:     $updatehash{'autoupdate'}{'lastactive'} = $lastactivedays;
13435:     foreach my $key (keys(%currautoupdate)) {
13436:         if (($key eq 'run') || ($key eq 'classlists') || ($key eq 'unexpired') || ($key eq 'lastactive')) {
13437:             if (exists($updatehash{autoupdate}{$key})) {
13438:                 if ($currautoupdate{$key} ne $updatehash{autoupdate}{$key}) {
13439:                     $changes{$key} = 1;
13440:                 }
13441:             }
13442:         } elsif ($key eq 'fields') {
13443:             if (ref($currautoupdate{$key}) eq 'HASH') {
13444:                 foreach my $item (@{$types},'default') {
13445:                     if (ref($currautoupdate{$key}{$item}) eq 'ARRAY') {
13446:                         my $change = 0;
13447:                         foreach my $type (@{$currautoupdate{$key}{$item}}) {
13448:                             if (!exists($fields{$item})) {
13449:                                 $change = 1;
13450:                                 last;
13451:                             } elsif (ref($fields{$item}) eq 'ARRAY') {
13452:                                 if (!grep(/^\Q$type\E$/,@{$fields{$item}})) {
13453:                                     $change = 1;
13454:                                     last;
13455:                                 }
13456:                             }
13457:                         }
13458:                         if ($change) {
13459:                             push(@{$changes{$key}},$item);
13460:                         }
13461:                     } 
13462:                 }
13463:             }
13464:         } elsif ($key eq 'lockablenames') {
13465:             if (ref($currautoupdate{$key}) eq 'ARRAY') {
13466:                 my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
13467:                 if (@changed) {
13468:                     $changes{'lockablenames'} = 1;
13469:                 }
13470:             } else {
13471:                 if (@lockablenames) {
13472:                     $changes{'lockablenames'} = 1;
13473:                 }
13474:             }
13475:         }
13476:     }
13477:     unless (grep(/^\Qlockablenames\E$/,keys(%currautoupdate))) {
13478:         if (@lockablenames) {
13479:             $changes{'lockablenames'} = 1;
13480:         }
13481:     }
13482:     unless (grep(/^unexpired$/,keys(%currautoupdate))) {
13483:         if ($updatehash{'autoupdate'}{'unexpired'}) {
13484:             $changes{'unexpired'} = 1;
13485:         }
13486:     }
13487:     unless (grep(/^lastactive$/,keys(%currautoupdate))) {
13488:         if ($updatehash{'autoupdate'}{'lastactive'} ne '') {
13489:             $changes{'lastactive'} = 1;
13490:         }
13491:     }
13492:     foreach my $item (@{$types},'default') {
13493:         if (defined($fields{$item})) {
13494:             if (ref($currautoupdate{'fields'}) eq 'HASH') {
13495:                 if (ref($currautoupdate{'fields'}{$item}) eq 'ARRAY') {
13496:                     my $change = 0;
13497:                     if (ref($fields{$item}) eq 'ARRAY') {
13498:                         foreach my $type (@{$fields{$item}}) {
13499:                             if (!grep(/^\Q$type\E$/,@{$currautoupdate{'fields'}{$item}})) {
13500:                                 $change = 1;
13501:                                 last;
13502:                             }
13503:                         }
13504:                     }
13505:                     if ($change) {
13506:                         push(@{$changes{'fields'}},$item);
13507:                     }
13508:                 } else {
13509:                     push(@{$changes{'fields'}},$item);
13510:                 }
13511:             } else {
13512:                 push(@{$changes{'fields'}},$item);
13513:             }
13514:         }
13515:     }
13516:     my $putresult = &Apache::lonnet::put_dom('configuration',\%updatehash,
13517:                                              $dom);
13518:     if ($putresult eq 'ok') {
13519:         if (keys(%changes) > 0) {
13520:             $resulttext = &mt('Changes made:').'<ul>';
13521:             foreach my $key (sort(keys(%changes))) {
13522:                 if ($key eq 'lockablenames') {
13523:                     $resulttext .= '<li>';
13524:                     if (@lockablenames) {
13525:                         $usertypes->{'default'} = $othertitle;
13526:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update), available for the following affiliations:").' '.
13527:                                    join(', ', map { $usertypes->{$_}; } @lockablenames).'</li>';
13528:                     } else {
13529:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update) is unavailable.");
13530:                     }
13531:                     $resulttext .= '</li>';
13532:                 } elsif (ref($changes{$key}) eq 'ARRAY') {
13533:                     foreach my $item (@{$changes{$key}}) {
13534:                         my @newvalues;
13535:                         foreach my $type (@{$fields{$item}}) {
13536:                             push(@newvalues,$fieldtitles{$type});
13537:                         }
13538:                         my $newvaluestr;
13539:                         if (@newvalues > 0) {
13540:                             $newvaluestr = join(', ',@newvalues);
13541:                         } else {
13542:                             $newvaluestr = &mt('none');
13543:                         }
13544:                         if ($item eq 'default') {
13545:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$othertitle,$newvaluestr).'</li>';
13546:                         } else {
13547:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$usertypes->{$item},$newvaluestr).'</li>';
13548:                         }
13549:                     }
13550:                 } else {
13551:                     my $newvalue;
13552:                     if ($key eq 'run') {
13553:                         $newvalue = $offon[$env{'form.autoupdate_run'}];
13554:                     } elsif ($key eq 'lastactive') {
13555:                         $newvalue = $offon[$env{'form.lastactive'}];
13556:                         unless ($lastactivedays eq '') {
13557:                             $newvalue .= '; '.&mt('inactive = no activity in last [quant,_1,day]',$lastactivedays);
13558:                         }
13559:                     } else {
13560:                         $newvalue = $offon[$env{'form.'.$key}];
13561:                     }
13562:                     $resulttext .= '<li>'.&mt("[_1] set to $newvalue",$title{$key}).'</li>';
13563:                 }
13564:             }
13565:             $resulttext .= '</ul>';
13566:         } else {
13567:             $resulttext = &mt('No changes made to autoupdates');
13568:         }
13569:     } else {
13570:         $resulttext = '<span class="LC_error">'.
13571: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
13572:     }
13573:     return $resulttext;
13574: }
13575: 
13576: sub modify_autocreate {
13577:     my ($dom,%domconfig) = @_;
13578:     my ($resulttext,%changes,%currautocreate,%newvals,%autocreatehash);
13579:     if (ref($domconfig{'autocreate'}) eq 'HASH') {
13580:         foreach my $key (keys(%{$domconfig{'autocreate'}})) {
13581:             $currautocreate{$key} = $domconfig{'autocreate'}{$key};
13582:         }
13583:     }
13584:     my %title= ( xml => 'Auto-creation of courses in XML course description files',
13585:                  req => 'Auto-creation of validated requests for official courses',
13586:                  xmldc => 'Identity of course creator of courses from XML files',
13587:                );
13588:     my @types = ('xml','req');
13589:     foreach my $item (@types) {
13590:         $newvals{$item} = $env{'form.autocreate_'.$item};
13591:         $newvals{$item} =~ s/\D//g;
13592:         $newvals{$item} = 0 if ($newvals{$item} eq '');
13593:     }
13594:     $newvals{'xmldc'} = $env{'form.autocreate_xmldc'};
13595:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
13596:     unless (exists($domcoords{$newvals{'xmldc'}})) {
13597:         $newvals{'xmldc'} = '';
13598:     } 
13599:     %autocreatehash =  (
13600:                         autocreate => { xml => $newvals{'xml'},
13601:                                         req => $newvals{'req'},
13602:                                       }
13603:                        );
13604:     if ($newvals{'xmldc'} ne '') {
13605:         $autocreatehash{'autocreate'}{'xmldc'} = $newvals{'xmldc'};
13606:     }
13607:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autocreatehash,
13608:                                              $dom);
13609:     if ($putresult eq 'ok') {
13610:         my @items = @types;
13611:         if ($newvals{'xml'}) {
13612:             push(@items,'xmldc');
13613:         }
13614:         foreach my $item (@items) {
13615:             if (exists($currautocreate{$item})) {
13616:                 if ($currautocreate{$item} ne $newvals{$item}) {
13617:                     $changes{$item} = 1;
13618:                 }
13619:             } elsif ($newvals{$item}) {
13620:                 $changes{$item} = 1;
13621:             }
13622:         }
13623:         if (keys(%changes) > 0) {
13624:             my @offon = ('off','on'); 
13625:             $resulttext = &mt('Changes made:').'<ul>';
13626:             foreach my $item (@types) {
13627:                 if ($changes{$item}) {
13628:                     my $newtxt = $offon[$newvals{$item}];
13629:                     $resulttext .= '<li>'.
13630:                                    &mt("$title{$item} set to [_1]$newtxt [_2]",
13631:                                        '<b>','</b>').
13632:                                    '</li>';
13633:                 }
13634:             }
13635:             if ($changes{'xmldc'}) {
13636:                 my ($dcname,$dcdom) = split(':',$newvals{'xmldc'});
13637:                 my $newtxt = &Apache::loncommon::plainname($dcname,$dcdom);
13638:                 $resulttext .= '<li>'.&mt("$title{'xmldc'} set to [_1]",'<b>'.$newtxt.'</b>').'</li>'; 
13639:             }
13640:             $resulttext .= '</ul>';
13641:         } else {
13642:             $resulttext = &mt('No changes made to auto-creation settings');
13643:         }
13644:     } else {
13645:         $resulttext = '<span class="LC_error">'.
13646:             &mt('An error occurred: [_1]',$putresult).'</span>';
13647:     }
13648:     return $resulttext;
13649: }
13650: 
13651: sub modify_directorysrch {
13652:     my ($dom,$lastactref,%domconfig) = @_;
13653:     my ($resulttext,%changes);
13654:     my %currdirsrch;
13655:     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
13656:         foreach my $key (keys(%{$domconfig{'directorysrch'}})) {
13657:             $currdirsrch{$key} = $domconfig{'directorysrch'}{$key};
13658:         }
13659:     }
13660:     my %title = ( available => 'Institutional directory search available',
13661:                   localonly => 'Other domains can search institution',
13662:                   lcavailable => 'LON-CAPA directory search available',
13663:                   lclocalonly => 'Other domains can search LON-CAPA domain',
13664:                   searchby => 'Search types',
13665:                   searchtypes => 'Search latitude');
13666:     my @offon = ('off','on');
13667:     my @otherdoms = ('Yes','No');
13668: 
13669:     my @searchtypes = &Apache::loncommon::get_env_multiple('form.searchtypes');  
13670:     my @cansearch = &Apache::loncommon::get_env_multiple('form.cansearch');
13671:     my @searchby = &Apache::loncommon::get_env_multiple('form.searchby');
13672: 
13673:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
13674:     if (keys(%{$usertypes}) == 0) {
13675:         @cansearch = ('default');
13676:     } else {
13677:         if (ref($currdirsrch{'cansearch'}) eq 'ARRAY') {
13678:             foreach my $type (@{$currdirsrch{'cansearch'}}) {
13679:                 if (!grep(/^\Q$type\E$/,@cansearch)) {
13680:                     push(@{$changes{'cansearch'}},$type);
13681:                 }
13682:             }
13683:             foreach my $type (@cansearch) {
13684:                 if (!grep(/^\Q$type\E$/,@{$currdirsrch{'cansearch'}})) {
13685:                     push(@{$changes{'cansearch'}},$type);
13686:                 }
13687:             }
13688:         } else {
13689:             push(@{$changes{'cansearch'}},@cansearch);
13690:         }
13691:     }
13692: 
13693:     if (ref($currdirsrch{'searchby'}) eq 'ARRAY') {
13694:         foreach my $by (@{$currdirsrch{'searchby'}}) {
13695:             if (!grep(/^\Q$by\E$/,@searchby)) {
13696:                 push(@{$changes{'searchby'}},$by);
13697:             }
13698:         }
13699:         foreach my $by (@searchby) {
13700:             if (!grep(/^\Q$by\E$/,@{$currdirsrch{'searchby'}})) {
13701:                 push(@{$changes{'searchby'}},$by);
13702:             }
13703:         }
13704:     } else {
13705:         push(@{$changes{'searchby'}},@searchby);
13706:     }
13707: 
13708:     if (ref($currdirsrch{'searchtypes'}) eq 'ARRAY') {
13709:         foreach my $type (@{$currdirsrch{'searchtypes'}}) {
13710:             if (!grep(/^\Q$type\E$/,@searchtypes)) {
13711:                 push(@{$changes{'searchtypes'}},$type);
13712:             }
13713:         }
13714:         foreach my $type (@searchtypes) {
13715:             if (!grep(/^\Q$type\E$/,@{$currdirsrch{'searchtypes'}})) {
13716:                 push(@{$changes{'searchtypes'}},$type);
13717:             }
13718:         }
13719:     } else {
13720:         if (exists($currdirsrch{'searchtypes'})) {
13721:             foreach my $type (@searchtypes) {  
13722:                 if ($type ne $currdirsrch{'searchtypes'}) { 
13723:                     push(@{$changes{'searchtypes'}},$type);
13724:                 }
13725:             }
13726:             if (!grep(/^\Q$currdirsrch{'searchtypes'}\E/,@searchtypes)) {
13727:                 push(@{$changes{'searchtypes'}},$currdirsrch{'searchtypes'});
13728:             }   
13729:         } else {
13730:             push(@{$changes{'searchtypes'}},@searchtypes); 
13731:         }
13732:     }
13733: 
13734:     my %dirsrch_hash =  (
13735:             directorysrch => { available => $env{'form.dirsrch_available'},
13736:                                cansearch => \@cansearch,
13737:                                localonly => $env{'form.dirsrch_instlocalonly'},
13738:                                lclocalonly => $env{'form.dirsrch_domlocalonly'},
13739:                                lcavailable => $env{'form.dirsrch_domavailable'},
13740:                                searchby => \@searchby,
13741:                                searchtypes => \@searchtypes,
13742:                              }
13743:             );
13744:     my $putresult = &Apache::lonnet::put_dom('configuration',\%dirsrch_hash,
13745:                                              $dom);
13746:     if ($putresult eq 'ok') {
13747:         if (exists($currdirsrch{'available'})) {
13748:              if ($currdirsrch{'available'} ne $env{'form.dirsrch_available'}) {
13749:                  $changes{'available'} = 1;
13750:              }
13751:         } else {
13752:             if ($env{'form.dirsrch_available'} eq '1') {
13753:                 $changes{'available'} = 1;
13754:             }
13755:         }
13756:         if (exists($currdirsrch{'lcavailable'})) {
13757:             if ($currdirsrch{'lcavailable'} ne $env{'form.dirsrch_domavailable'}) {
13758:                 $changes{'lcavailable'} = 1;
13759:             }
13760:         } else {
13761:             if ($env{'form.dirsrch_lcavailable'} eq '1') {
13762:                 $changes{'lcavailable'} = 1;
13763:             }
13764:         }
13765:         if (exists($currdirsrch{'localonly'})) {
13766:             if ($currdirsrch{'localonly'} ne $env{'form.dirsrch_instlocalonly'}) {
13767:                 $changes{'localonly'} = 1;
13768:             }
13769:         } else {
13770:             if ($env{'form.dirsrch_instlocalonly'} eq '1') {
13771:                 $changes{'localonly'} = 1;
13772:             }
13773:         }
13774:         if (exists($currdirsrch{'lclocalonly'})) {
13775:             if ($currdirsrch{'lclocalonly'} ne $env{'form.dirsrch_domlocalonly'}) {
13776:                 $changes{'lclocalonly'} = 1;
13777:             }
13778:         } else {
13779:             if ($env{'form.dirsrch_domlocalonly'} eq '1') {
13780:                 $changes{'lclocalonly'} = 1;
13781:             }
13782:         }
13783:         if (keys(%changes) > 0) {
13784:             $resulttext = &mt('Changes made:').'<ul>';
13785:             if ($changes{'available'}) {
13786:                 $resulttext .= '<li>'.&mt("$title{'available'} set to: $offon[$env{'form.dirsrch_available'}]").'</li>';
13787:             }
13788:             if ($changes{'lcavailable'}) {
13789:                 $resulttext .= '<li>'.&mt("$title{'lcavailable'} set to: $offon[$env{'form.dirsrch_domavailable'}]").'</li>';
13790:             }
13791:             if ($changes{'localonly'}) {
13792:                 $resulttext .= '<li>'.&mt("$title{'localonly'} set to: $otherdoms[$env{'form.dirsrch_instlocalonly'}]").'</li>';
13793:             }
13794:             if ($changes{'lclocalonly'}) {
13795:                 $resulttext .= '<li>'.&mt("$title{'lclocalonly'} set to: $otherdoms[$env{'form.dirsrch_domlocalonly'}]").'</li>';
13796:             }
13797:             if (ref($changes{'cansearch'}) eq 'ARRAY') {
13798:                 my $chgtext;
13799:                 if (ref($usertypes) eq 'HASH') {
13800:                     if (keys(%{$usertypes}) > 0) {
13801:                         foreach my $type (@{$types}) {
13802:                             if (grep(/^\Q$type\E$/,@cansearch)) {
13803:                                 $chgtext .= $usertypes->{$type}.'; ';
13804:                             }
13805:                         }
13806:                         if (grep(/^default$/,@cansearch)) {
13807:                             $chgtext .= $othertitle;
13808:                         } else {
13809:                             $chgtext =~ s/\; $//;
13810:                         }
13811:                         $resulttext .=
13812:                             '<li>'.
13813:                             &mt("Users from domain '[_1]' permitted to search the institutional directory set to: [_2]",
13814:                                 '<span class="LC_cusr_emph">'.$dom.'</span>',$chgtext).
13815:                             '</li>';
13816:                     }
13817:                 }
13818:             }
13819:             if (ref($changes{'searchby'}) eq 'ARRAY') {
13820:                 my ($searchtitles,$titleorder) = &sorted_searchtitles();
13821:                 my $chgtext;
13822:                 foreach my $type (@{$titleorder}) {
13823:                     if (grep(/^\Q$type\E$/,@searchby)) {
13824:                         if (defined($searchtitles->{$type})) {
13825:                             $chgtext .= $searchtitles->{$type}.'; ';
13826:                         }
13827:                     }
13828:                 }
13829:                 $chgtext =~ s/\; $//;
13830:                 $resulttext .= '<li>'.&mt("$title{'searchby'} set to: [_1]",$chgtext).'</li>';
13831:             }
13832:             if (ref($changes{'searchtypes'}) eq 'ARRAY') {
13833:                 my ($srchtypes_desc,$srchtypeorder) = &sorted_searchtypes(); 
13834:                 my $chgtext;
13835:                 foreach my $type (@{$srchtypeorder}) {
13836:                     if (grep(/^\Q$type\E$/,@searchtypes)) {
13837:                         if (defined($srchtypes_desc->{$type})) {
13838:                             $chgtext .= $srchtypes_desc->{$type}.'; ';
13839:                         }
13840:                     }
13841:                 }
13842:                 $chgtext =~ s/\; $//;
13843:                 $resulttext .= '<li>'.&mt($title{'searchtypes'}.' set to: "[_1]"',$chgtext).'</li>';
13844:             }
13845:             $resulttext .= '</ul>';
13846:             &Apache::lonnet::do_cache_new('directorysrch',$dom,$dirsrch_hash{'directorysrch'},3600);
13847:             if (ref($lastactref) eq 'HASH') {
13848:                 $lastactref->{'directorysrch'} = 1;
13849:             }
13850:         } else {
13851:             $resulttext = &mt('No changes made to directory search settings');
13852:         }
13853:     } else {
13854:         $resulttext = '<span class="LC_error">'.
13855:                       &mt('An error occurred: [_1]',$putresult).'</span>';
13856:     }
13857:     return $resulttext;
13858: }
13859: 
13860: sub modify_contacts {
13861:     my ($dom,$lastactref,%domconfig) = @_;
13862:     my ($resulttext,%currsetting,%newsetting,%changes,%contacts_hash);
13863:     if (ref($domconfig{'contacts'}) eq 'HASH') {
13864:         foreach my $key (keys(%{$domconfig{'contacts'}})) {
13865:             $currsetting{$key} = $domconfig{'contacts'}{$key};
13866:         }
13867:     }
13868:     my (%others,%to,%bcc,%includestr,%includeloc);
13869:     my @contacts = ('supportemail','adminemail');
13870:     my @mailings = ('errormail','packagesmail','helpdeskmail','otherdomsmail',
13871:                     'lonstatusmail','requestsmail','updatesmail','idconflictsmail','hostipmail');
13872:     my @toggles = ('reporterrors','reportupdates','reportstatus');
13873:     my @lonstatus = ('threshold','sysmail','weights','excluded');
13874:     my ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
13875:     foreach my $type (@mailings) {
13876:         @{$newsetting{$type}} = 
13877:             &Apache::loncommon::get_env_multiple('form.'.$type);
13878:         foreach my $item (@contacts) {
13879:             if (grep(/^\Q$item\E$/,@{$newsetting{$type}})) {
13880:                 $contacts_hash{contacts}{$type}{$item} = 1;
13881:             } else {
13882:                 $contacts_hash{contacts}{$type}{$item} = 0;
13883:             }
13884:         }
13885:         $others{$type} = $env{'form.'.$type.'_others'};
13886:         $contacts_hash{contacts}{$type}{'others'} = $others{$type};
13887:         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
13888:             $bcc{$type} = $env{'form.'.$type.'_bcc'};
13889:             $contacts_hash{contacts}{$type}{'bcc'} = $bcc{$type};
13890:             if (($env{'form.'.$type.'_includestr'} ne '') && ($env{'form.'.$type.'_includeloc'} =~ /^s|b$/)) {
13891:                 $includestr{$type} = $env{'form.'.$type.'_includestr'};
13892:                 $includeloc{$type} = $env{'form.'.$type.'_includeloc'};
13893:                 $contacts_hash{contacts}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
13894:             }
13895:         }
13896:     }
13897:     foreach my $item (@contacts) {
13898:         $to{$item} = $env{'form.'.$item};
13899:         $contacts_hash{'contacts'}{$item} = $to{$item};
13900:     }
13901:     foreach my $item (@toggles) {
13902:         if ($env{'form.'.$item} =~ /^(0|1)$/) {
13903:             $contacts_hash{'contacts'}{$item} = $env{'form.'.$item};
13904:         }
13905:     }
13906:     my ($lonstatus_defs,$lonstatus_names) = &Apache::loncommon::lon_status_items();
13907:     foreach my $item (@lonstatus) {
13908:         if ($item eq 'excluded') {
13909:             my (%serverhomes,@excluded);
13910:             map { $serverhomes{$_} = 1; } values(%Apache::lonnet::serverhomeIDs);
13911:             my @possexcluded = &Apache::loncommon::get_env_multiple('form.errorexcluded');
13912:             if (@possexcluded) {
13913:                 foreach my $id (sort(@possexcluded)) {
13914:                     if ($serverhomes{$id}) {
13915:                         push(@excluded,$id);
13916:                     }
13917:                 }
13918:             }
13919:             if (@excluded) {
13920:                 $contacts_hash{'contacts'}{'lonstatus'}{$item} = \@excluded;
13921:             }
13922:         } elsif ($item eq 'weights') {
13923:             foreach my $type ('E','W','N','U') {
13924:                 $env{'form.error'.$item.'_'.$type} =~ s/^\s+|\s+$//g;
13925:                 if ($env{'form.error'.$item.'_'.$type} =~ /^\d+$/) {
13926:                     unless ($env{'form.error'.$item.'_'.$type} == $lonstatus_defs->{$type}) {
13927:                         $contacts_hash{'contacts'}{'lonstatus'}{$item}{$type} =
13928:                             $env{'form.error'.$item.'_'.$type};
13929:                     }
13930:                 }
13931:             }
13932:         } elsif (($item eq 'threshold') || ($item eq 'sysmail')) {
13933:             $env{'form.error'.$item} =~ s/^\s+|\s+$//g;
13934:             if ($env{'form.error'.$item} =~ /^\d+$/) {
13935:                 unless ($env{'form.error'.$item} == $lonstatus_defs->{$item}) {
13936:                     $contacts_hash{'contacts'}{'lonstatus'}{$item} = $env{'form.error'.$item};
13937:                 }
13938:             }
13939:         }
13940:     }
13941:     if ((ref($fields) eq 'ARRAY') && (ref($possoptions) eq 'HASH')) {
13942:         foreach my $field (@{$fields}) {
13943:             if (ref($possoptions->{$field}) eq 'ARRAY') {
13944:                 my $value = $env{'form.helpform_'.$field};
13945:                 $value =~ s/^\s+|\s+$//g;
13946:                 if (grep(/^\Q$value\E$/,@{$possoptions->{$field}})) {
13947:                     $contacts_hash{'contacts'}{'helpform'}{$field} = $value;
13948:                     if ($field eq 'screenshot') {
13949:                         $env{'form.helpform_maxsize'} =~ s/^\s+|\s+$//g;
13950:                         if ($env{'form.helpform_maxsize'} =~ /^\d+\.?\d*$/) {
13951:                             $contacts_hash{'contacts'}{'helpform'}{'maxsize'} = $env{'form.helpform_maxsize'};
13952:                         }
13953:                     }
13954:                 }
13955:             }
13956:         }
13957:     }
13958:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
13959:     my (@statuses,%usertypeshash,@overrides);
13960:     if ((ref($types) eq 'ARRAY') && (@{$types} > 0)) {
13961:         @statuses = @{$types};
13962:         if (ref($usertypes) eq 'HASH') {
13963:             %usertypeshash = %{$usertypes};
13964:         }
13965:     }
13966:     if (@statuses) {
13967:         my @possoverrides = &Apache::loncommon::get_env_multiple('form.overrides');
13968:         foreach my $type (@possoverrides) {
13969:             if (($type ne '') && (grep(/^\Q$type\E$/,@statuses))) {
13970:                 push(@overrides,$type);
13971:             }
13972:         }
13973:         if (@overrides) {
13974:             foreach my $type (@overrides) {
13975:                 my @standard = &Apache::loncommon::get_env_multiple('form.override_'.$type);
13976:                 foreach my $item (@contacts) {
13977:                     if (grep(/^\Q$item\E$/,@standard)) {
13978:                         $contacts_hash{'contacts'}{'overrides'}{$type}{$item} = 1;
13979:                         $newsetting{'override_'.$type}{$item} = 1;
13980:                     } else {
13981:                         $contacts_hash{'contacts'}{'overrides'}{$type}{$item} = 0;
13982:                         $newsetting{'override_'.$type}{$item} = 0;
13983:                     }
13984:                 }
13985:                 $contacts_hash{'contacts'}{'overrides'}{$type}{'others'} = $env{'form.override_'.$type.'_others'};
13986:                 $contacts_hash{'contacts'}{'overrides'}{$type}{'bcc'} = $env{'form.override_'.$type.'_bcc'};
13987:                 $newsetting{'override_'.$type}{'others'} = $env{'form.override_'.$type.'_others'};
13988:                 $newsetting{'override_'.$type}{'bcc'} = $env{'form.override_'.$type.'_bcc'};
13989:                 if (($env{'form.override_'.$type.'_includestr'} ne '') && ($env{'form.override_'.$type.'_includeloc'} =~ /^s|b$/)) {
13990:                     $includestr{$type} = $env{'form.override_'.$type.'_includestr'};
13991:                     $includeloc{$type} = $env{'form.override_'.$type.'_includeloc'};
13992:                     $contacts_hash{'contacts'}{'overrides'}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
13993:                     $newsetting{'override_'.$type}{'include'} = $contacts_hash{'contacts'}{'overrides'}{$type}{'include'};
13994:                 }
13995:             }    
13996:         }
13997:     }
13998:     if (keys(%currsetting) > 0) {
13999:         foreach my $item (@contacts) {
14000:             if ($to{$item} ne $currsetting{$item}) {
14001:                 $changes{$item} = 1;
14002:             }
14003:         }
14004:         foreach my $type (@mailings) {
14005:             foreach my $item (@contacts) {
14006:                 if (ref($currsetting{$type}) eq 'HASH') {
14007:                     if ($currsetting{$type}{$item} ne $contacts_hash{contacts}{$type}{$item}) {
14008:                         push(@{$changes{$type}},$item);
14009:                     }
14010:                 } else {
14011:                     push(@{$changes{$type}},@{$newsetting{$type}});
14012:                 }
14013:             }
14014:             if ($others{$type} ne $currsetting{$type}{'others'}) {
14015:                 push(@{$changes{$type}},'others');
14016:             }
14017:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
14018:                 if ($bcc{$type} ne $currsetting{$type}{'bcc'}) {
14019:                     push(@{$changes{$type}},'bcc'); 
14020:                 }
14021:                 my ($currloc,$currstr) = split(/:/,$currsetting{$type}{'include'},2);
14022:                 if (($includeloc{$type} ne $currloc) || (&escape($includestr{$type}) ne $currstr)) {
14023:                     push(@{$changes{$type}},'include');
14024:                 }
14025:             }
14026:         }
14027:         if (ref($fields) eq 'ARRAY') {
14028:             if (ref($currsetting{'helpform'}) eq 'HASH') {
14029:                 foreach my $field (@{$fields}) {
14030:                     if ($currsetting{'helpform'}{$field} ne $contacts_hash{'contacts'}{'helpform'}{$field}) {
14031:                         push(@{$changes{'helpform'}},$field);
14032:                     }
14033:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
14034:                         if ($currsetting{'helpform'}{'maxsize'} ne $contacts_hash{'contacts'}{'helpform'}{'maxsize'}) {
14035:                             push(@{$changes{'helpform'}},'maxsize');
14036:                         }
14037:                     }
14038:                 }
14039:             } else {
14040:                 foreach my $field (@{$fields}) {
14041:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
14042:                         push(@{$changes{'helpform'}},$field);
14043:                     }
14044:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
14045:                         if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
14046:                             push(@{$changes{'helpform'}},'maxsize');
14047:                         }
14048:                     }
14049:                 }
14050:             }
14051:         }
14052:         if (@statuses) {
14053:             if (ref($currsetting{'overrides'}) eq 'HASH') {
14054:                 foreach my $key (keys(%{$currsetting{'overrides'}})) {
14055:                     if (ref($currsetting{'overrides'}{$key}) eq 'HASH') {
14056:                         if (ref($newsetting{'override_'.$key}) eq 'HASH') {
14057:                             foreach my $item (@contacts,'bcc','others','include') {
14058:                                 if ($currsetting{'overrides'}{$key}{$item} ne $newsetting{'override_'.$key}{$item}) {
14059:                                     push(@{$changes{'overrides'}},$key);
14060:                                     last;
14061:                                 }
14062:                             }
14063:                         } else {
14064:                             push(@{$changes{'overrides'}},$key);
14065:                         }
14066:                     }
14067:                 }
14068:                 foreach my $key (@overrides) {
14069:                     unless (exists($currsetting{'overrides'}{$key})) {
14070:                         push(@{$changes{'overrides'}},$key);
14071:                     }
14072:                 }
14073:             } else {
14074:                 foreach my $key (@overrides) {
14075:                     push(@{$changes{'overrides'}},$key);
14076:                 }
14077:             }
14078:         }
14079:         if (ref($currsetting{'lonstatus'}) eq 'HASH') {
14080:             foreach my $key ('excluded','weights','threshold','sysmail') {
14081:                 if ($key eq 'excluded') {
14082:                     if ((ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') &&
14083:                         (ref($contacts_hash{contacts}{lonstatus}{excluded}) eq 'ARRAY')) {
14084:                         if ((ref($currsetting{'lonstatus'}{$key}) eq 'ARRAY') &&
14085:                             (@{$currsetting{'lonstatus'}{$key}})) {
14086:                             my @diffs =
14087:                                 &Apache::loncommon::compare_arrays($contacts_hash{contacts}{lonstatus}{excluded},
14088:                                                                    $currsetting{'lonstatus'}{$key});
14089:                             if (@diffs) {
14090:                                 push(@{$changes{'lonstatus'}},$key);
14091:                             }
14092:                         } elsif (@{$contacts_hash{contacts}{lonstatus}{excluded}}) {
14093:                             push(@{$changes{'lonstatus'}},$key);
14094:                         }
14095:                     } elsif ((ref($currsetting{'lonstatus'}{$key}) eq 'ARRAY') &&
14096:                              (@{$currsetting{'lonstatus'}{$key}})) {
14097:                         push(@{$changes{'lonstatus'}},$key);
14098:                     }
14099:                 } elsif ($key eq 'weights') {
14100:                     if ((ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') &&
14101:                         (ref($contacts_hash{contacts}{lonstatus}{$key}) eq 'HASH')) {
14102:                         if (ref($currsetting{'lonstatus'}{$key}) eq 'HASH') {
14103:                             foreach my $type ('E','W','N','U') {
14104:                                 unless ($contacts_hash{contacts}{lonstatus}{$key}{$type} eq
14105:                                         $currsetting{'lonstatus'}{$key}{$type}) {
14106:                                     push(@{$changes{'lonstatus'}},$key);
14107:                                     last;
14108:                                 }
14109:                             }
14110:                         } else {
14111:                             foreach my $type ('E','W','N','U') {
14112:                                 if ($contacts_hash{contacts}{lonstatus}{$key}{$type} ne '') {
14113:                                     push(@{$changes{'lonstatus'}},$key);
14114:                                     last;
14115:                                 }
14116:                             }
14117:                         }
14118:                     } elsif (ref($currsetting{'lonstatus'}{$key}) eq 'HASH') {
14119:                         foreach my $type ('E','W','N','U') {
14120:                             if ($currsetting{'lonstatus'}{$key}{$type} ne '') {
14121:                                 push(@{$changes{'lonstatus'}},$key);
14122:                                 last;
14123:                             }
14124:                         }
14125:                     }
14126:                 } elsif (($key eq 'threshold') || ($key eq 'sysmail')) {
14127:                     if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
14128:                         if ($currsetting{'lonstatus'}{$key} =~ /^\d+$/) {
14129:                             if ($currsetting{'lonstatus'}{$key} != $contacts_hash{contacts}{lonstatus}{$key}) {
14130:                                 push(@{$changes{'lonstatus'}},$key);
14131:                             }
14132:                         } elsif ($contacts_hash{contacts}{lonstatus}{$key} =~ /^\d+$/) {
14133:                             push(@{$changes{'lonstatus'}},$key);
14134:                         }
14135:                     } elsif ($currsetting{'lonstatus'}{$key} =~ /^\d+$/) {
14136:                         push(@{$changes{'lonstatus'}},$key);
14137:                     }
14138:                 }
14139:             }
14140:         } else {
14141:             if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
14142:                 foreach my $key ('excluded','weights','threshold','sysmail') {
14143:                     if (exists($contacts_hash{contacts}{lonstatus}{$key})) {
14144:                         push(@{$changes{'lonstatus'}},$key);
14145:                     }
14146:                 }
14147:             }
14148:         }
14149:     } else {
14150:         my %default;
14151:         $default{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
14152:         $default{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
14153:         $default{'errormail'} = 'adminemail';
14154:         $default{'packagesmail'} = 'adminemail';
14155:         $default{'helpdeskmail'} = 'supportemail';
14156:         $default{'otherdomsmail'} = 'supportemail';
14157:         $default{'lonstatusmail'} = 'adminemail';
14158:         $default{'requestsmail'} = 'adminemail';
14159:         $default{'updatesmail'} = 'adminemail';
14160:         $default{'hostipmail'} = 'adminemail';
14161:         foreach my $item (@contacts) {
14162:            if ($to{$item} ne $default{$item}) {
14163:                $changes{$item} = 1;
14164:            }
14165:         }
14166:         foreach my $type (@mailings) {
14167:             if ((@{$newsetting{$type}} != 1) || ($newsetting{$type}[0] ne $default{$type})) {
14168:                 push(@{$changes{$type}},@{$newsetting{$type}});
14169:             }
14170:             if ($others{$type} ne '') {
14171:                 push(@{$changes{$type}},'others');
14172:             }
14173:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
14174:                 if ($bcc{$type} ne '') {
14175:                     push(@{$changes{$type}},'bcc');
14176:                 }
14177:                 if (($includeloc{$type} =~ /^b|s$/) && ($includestr{$type} ne '')) {
14178:                     push(@{$changes{$type}},'include');
14179:                 }
14180:             }
14181:         }
14182:         if (ref($fields) eq 'ARRAY') {
14183:             foreach my $field (@{$fields}) {
14184:                 if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
14185:                     push(@{$changes{'helpform'}},$field);
14186:                 }
14187:                 if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
14188:                     if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
14189:                         push(@{$changes{'helpform'}},'maxsize');
14190:                     }
14191:                 }
14192:             }
14193:         }
14194:         if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
14195:             foreach my $key ('excluded','weights','threshold','sysmail') {
14196:                 if (exists($contacts_hash{contacts}{lonstatus}{$key})) {
14197:                     push(@{$changes{'lonstatus'}},$key);
14198:                 }
14199:             }
14200:         }
14201:     }
14202:     foreach my $item (@toggles) {
14203:         if (($env{'form.'.$item} == 1) && ($currsetting{$item} == 0)) {
14204:             $changes{$item} = 1;
14205:         } elsif ((!$env{'form.'.$item}) &&
14206:                  (($currsetting{$item} eq '') || ($currsetting{$item} == 1))) {
14207:             $changes{$item} = 1;
14208:         }
14209:     }
14210:     my $putresult = &Apache::lonnet::put_dom('configuration',\%contacts_hash,
14211:                                              $dom);
14212:     if ($putresult eq 'ok') {
14213:         if (keys(%changes) > 0) {
14214:             &Apache::loncommon::devalidate_domconfig_cache($dom);
14215:             if (ref($lastactref) eq 'HASH') {
14216:                 $lastactref->{'domainconfig'} = 1;
14217:             }
14218:             my ($titles,$short_titles)  = &contact_titles();
14219:             $resulttext = &mt('Changes made:').'<ul>';
14220:             foreach my $item (@contacts) {
14221:                 if ($changes{$item}) {
14222:                     $resulttext .= '<li>'.$titles->{$item}.
14223:                                     &mt(' set to: ').
14224:                                     '<span class="LC_cusr_emph">'.
14225:                                     $to{$item}.'</span></li>';
14226:                 }
14227:             }
14228:             foreach my $type (@mailings) {
14229:                 if (ref($changes{$type}) eq 'ARRAY') {
14230:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
14231:                         $resulttext .= '<li>'.$titles->{$type}.' -- '.&mt('sent to').': ';
14232:                     } else {
14233:                         $resulttext .= '<li>'.$titles->{$type}.': ';
14234:                     }
14235:                     my @text;
14236:                     foreach my $item (@{$newsetting{$type}}) {
14237:                         push(@text,$short_titles->{$item});
14238:                     }
14239:                     if ($others{$type} ne '') {
14240:                         push(@text,$others{$type});
14241:                     }
14242:                     if (@text) {
14243:                         $resulttext .= '<span class="LC_cusr_emph">'.
14244:                                        join(', ',@text).'</span>';
14245:                     }
14246:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
14247:                         if ($bcc{$type} ne '') {
14248:                             my $bcctext;
14249:                             if (@text) {
14250:                                 $bcctext = '&nbsp;'.&mt('with Bcc to');
14251:                             } else {
14252:                                 $bcctext = '(Bcc)';
14253:                             }
14254:                             $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$bcc{$type}.'</span>';
14255:                         } elsif (!@text) {
14256:                             $resulttext .= &mt('No one');
14257:                         }
14258:                         if ($includestr{$type} ne '') {
14259:                             if ($includeloc{$type} eq 'b') {
14260:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail body:').' '.$includestr{$type};
14261:                             } elsif ($includeloc{$type} eq 's') {
14262:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail subject:').' '.$includestr{$type};
14263:                             }
14264:                         }
14265:                     } elsif (!@text) {
14266:                         $resulttext .= &mt('No recipients');
14267:                     }
14268:                     $resulttext .= '</li>';
14269:                 }
14270:             }
14271:             if (ref($changes{'overrides'}) eq 'ARRAY') {
14272:                 my @deletions;
14273:                 foreach my $type (@{$changes{'overrides'}}) {
14274:                     if ($usertypeshash{$type}) {
14275:                         if (grep(/^\Q$type\E/,@overrides)) {
14276:                             $resulttext .= '<li>'.&mt("Overrides based on requester's affiliation set for [_1]",
14277:                                                       $usertypeshash{$type}).'<ul><li>';
14278:                             if (ref($newsetting{'override_'.$type}) eq 'HASH') {
14279:                                 my @text;
14280:                                 foreach my $item (@contacts) {
14281:                                     if ($newsetting{'override_'.$type}{$item}) {
14282:                                         push(@text,$short_titles->{$item});
14283:                                     }
14284:                                 }
14285:                                 if ($newsetting{'override_'.$type}{'others'} ne '') {
14286:                                     push(@text,$newsetting{'override_'.$type}{'others'});
14287:                                 }
14288: 
14289:                                 if (@text) {
14290:                                     $resulttext .= &mt('Helpdesk e-mail sent to: [_1]',
14291:                                                        '<span class="LC_cusr_emph">'.join(', ',@text).'</span>');
14292:                                 }
14293:                                 if ($newsetting{'override_'.$type}{'bcc'} ne '') {
14294:                                     my $bcctext;
14295:                                     if (@text) {
14296:                                         $bcctext = '&nbsp;'.&mt('with Bcc to');
14297:                                     } else {
14298:                                         $bcctext = '(Bcc)';
14299:                                     }
14300:                                     $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$newsetting{'override_'.$type}{'bcc'}.'</span>';
14301:                                 } elsif (!@text) {
14302:                                      $resulttext .= &mt('Helpdesk e-mail sent to no one');
14303:                                 }
14304:                                 $resulttext .= '</li>';
14305:                                 if ($newsetting{'override_'.$type}{'include'} ne '') {
14306:                                     my ($loc,$str) = split(/:/,$newsetting{'override_'.$type}{'include'});
14307:                                     if ($loc eq 'b') {
14308:                                         $resulttext .= '<li>'.&mt('Text automatically added to e-mail body:').' '.&unescape($str).'</li>';
14309:                                     } elsif ($loc eq 's') {
14310:                                         $resulttext .= '<li>'.&mt('Text automatically added to e-mail subject:').' '.&unescape($str).'</li>';
14311:                                     }
14312:                                 }
14313:                             }
14314:                             $resulttext .= '</li></ul></li>';
14315:                         } else {
14316:                             push(@deletions,$usertypeshash{$type});
14317:                         }
14318:                     }
14319:                 }
14320:                 if (@deletions) {
14321:                     $resulttext .= '<li>'.&mt("Overrides based on requester's affiliation discontinued for: [_1]",
14322:                                               join(', ',@deletions)).'</li>';
14323:                 }
14324:             }
14325:             my @offon = ('off','on');
14326:             my $corelink = &core_link_msu();
14327:             if ($changes{'reporterrors'}) {
14328:                 $resulttext .= '<li>'.
14329:                                &mt('E-mail error reports to [_1] set to "'.
14330:                                    $offon[$env{'form.reporterrors'}].'".',
14331:                                    $corelink).
14332:                                '</li>';
14333:             }
14334:             if ($changes{'reportupdates'}) {
14335:                 $resulttext .= '<li>'.
14336:                                 &mt('E-mail record of completed LON-CAPA updates to [_1] set to "'.
14337:                                     $offon[$env{'form.reportupdates'}].'".',
14338:                                     $corelink).
14339:                                 '</li>';
14340:             }
14341:             if ($changes{'reportstatus'}) {
14342:                 $resulttext .= '<li>'.
14343:                                 &mt('E-mail status if errors above threshold to [_1] set to "'.
14344:                                     $offon[$env{'form.reportstatus'}].'".',
14345:                                     $corelink).
14346:                                 '</li>';
14347:             }
14348:             if (ref($changes{'lonstatus'}) eq 'ARRAY') {
14349:                 $resulttext .= '<li>'.
14350:                                &mt('Nightly status check e-mail settings').':<ul>';
14351:                 my (%defval,%use_def,%shown);
14352:                 $defval{'threshold'} = $lonstatus_defs->{'threshold'};
14353:                 $defval{'sysmail'} = $lonstatus_defs->{'sysmail'};
14354:                 $defval{'weights'} =
14355:                     join(', ',map { $lonstatus_names->{$_}.'='.$lonstatus_defs->{$_}; } ('E','W','N','U'));
14356:                 $defval{'excluded'} = &mt('None');
14357:                 if (ref($contacts_hash{'contacts'}{'lonstatus'}) eq 'HASH') {
14358:                     foreach my $item ('threshold','sysmail','weights','excluded') {
14359:                         if (exists($contacts_hash{'contacts'}{'lonstatus'}{$item})) {
14360:                             if (($item eq 'threshold') || ($item eq 'sysmail')) {
14361:                                 $shown{$item} = $contacts_hash{'contacts'}{'lonstatus'}{$item};
14362:                             } elsif ($item eq 'weights') {
14363:                                 if (ref($contacts_hash{'contacts'}{'lonstatus'}{$item}) eq 'HASH') {
14364:                                     foreach my $type ('E','W','N','U') {
14365:                                         $shown{$item} .= $lonstatus_names->{$type}.'=';
14366:                                         if (exists($contacts_hash{'contacts'}{'lonstatus'}{$item}{$type})) {
14367:                                             $shown{$item} .= $contacts_hash{'contacts'}{'lonstatus'}{$item}{$type};
14368:                                         } else {
14369:                                             $shown{$item} .= $lonstatus_defs->{$type};
14370:                                         }
14371:                                         $shown{$item} .= ', ';
14372:                                     }
14373:                                     $shown{$item} =~ s/, $//;
14374:                                 } else {
14375:                                     $shown{$item} = $defval{$item};
14376:                                 }
14377:                             } elsif ($item eq 'excluded') {
14378:                                 if (ref($contacts_hash{'contacts'}{'lonstatus'}{$item}) eq 'ARRAY') {
14379:                                     $shown{$item} = join(', ',@{$contacts_hash{'contacts'}{'lonstatus'}{$item}});
14380:                                 } else {
14381:                                     $shown{$item} = $defval{$item};
14382:                                 }
14383:                             }
14384:                         } else {
14385:                             $shown{$item} = $defval{$item};
14386:                         }
14387:                     }
14388:                 } else {
14389:                     foreach my $item ('threshold','weights','excluded','sysmail') {
14390:                         $shown{$item} = $defval{$item};
14391:                     }
14392:                 }
14393:                 foreach my $item ('threshold','weights','excluded','sysmail') {
14394:                     $resulttext .= '<li>'.&mt($titles->{'error'.$item}.' -- [_1]',
14395:                                           $shown{$item}).'</li>';
14396:                 }
14397:                 $resulttext .= '</ul></li>';
14398:             }
14399:             if ((ref($changes{'helpform'}) eq 'ARRAY') && (ref($fields) eq 'ARRAY')) {
14400:                 my (@optional,@required,@unused,$maxsizechg);
14401:                 foreach my $field (@{$changes{'helpform'}}) {
14402:                     if ($field eq 'maxsize') {
14403:                         $maxsizechg = 1;
14404:                         next;
14405:                     }
14406:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'yes') {
14407:                         push(@optional,$field);
14408:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'no') {
14409:                         push(@unused,$field);
14410:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'req') {
14411:                         push(@required,$field);
14412:                     }
14413:                 }
14414:                 if (@optional) {
14415:                     $resulttext .= '<li>'.
14416:                                    &mt('Help form fields changed to "Optional": [_1].',
14417:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @optional)).'</span>'.
14418:                                    '</li>';
14419:                 }
14420:                 if (@required) {
14421:                     $resulttext .= '<li>'.
14422:                                    &mt('Help form fields changed to "Required": [_1].',
14423:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @required)).'</span>'.
14424:                                    '</li>';
14425:                 }
14426:                 if (@unused) {
14427:                     $resulttext .= '<li>'.
14428:                                    &mt('Help form fields changed to "Not shown": [_1].',
14429:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @unused)).'</span>'.
14430:                                    '</li>';
14431:                 }
14432:                 if ($maxsizechg) {
14433:                     $resulttext .= '<li>'.
14434:                                    &mt('Max size for file uploaded to help form by logged-in user set to [_1] MB.',
14435:                                        $contacts_hash{'contacts'}{'helpform'}{'maxsize'}).
14436:                                    '</li>';
14437:                 }
14438:             }
14439:             $resulttext .= '</ul>';
14440:         } else {
14441:             $resulttext = &mt('No changes made to contacts and form settings');
14442:         }
14443:     } else {
14444:         $resulttext = '<span class="LC_error">'.
14445:             &mt('An error occurred: [_1].',$putresult).'</span>';
14446:     }
14447:     return $resulttext;
14448: }
14449: 
14450: sub modify_passwords {
14451:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
14452:     my ($resulttext,%current,%changes,%newvalues,@oktypes,$errors,
14453:         $updatedefaults,$updateconf);
14454:     my $customfn = 'resetpw.html';
14455:     if (ref($domconfig{'passwords'}) eq 'HASH') {
14456:         %current = %{$domconfig{'passwords'}};
14457:     }
14458:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
14459:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
14460:     if (ref($types) eq 'ARRAY') {
14461:         @oktypes = @{$types};
14462:     }
14463:     push(@oktypes,'default');
14464: 
14465:     my %titles = &Apache::lonlocal::texthash (
14466:         intauth_cost   => 'Encryption cost for bcrypt (positive integer)',
14467:         intauth_check  => 'Check bcrypt cost if authenticated',
14468:         intauth_switch => 'Existing crypt-based switched to bcrypt on authentication',
14469:         permanent      => 'Permanent e-mail address',
14470:         critical       => 'Critical notification address',
14471:         notify         => 'Notification address',
14472:         min            => 'Minimum password length',
14473:         max            => 'Maximum password length',
14474:         chars          => 'Required characters',
14475:         numsaved       => 'Number of previous passwords to save',
14476:         reset          => 'Resetting Forgotten Password',
14477:         intauth        => 'Encryption of Stored Passwords (Internal Auth)',
14478:         rules          => 'Rules for LON-CAPA Passwords',
14479:         crsownerchg    => 'Course Owner Changing Student Passwords',
14480:         username       => 'Username',
14481:         email          => 'E-mail address',
14482:     );
14483: 
14484: #
14485: # Retrieve current domain configuration for internal authentication from $domconfig{'defaults'}.
14486: #
14487:     my (%curr_defaults,%save_defaults);
14488:     if (ref($domconfig{'defaults'}) eq 'HASH') {
14489:         foreach my $key (keys(%{$domconfig{'defaults'}})) {
14490:             if ($key =~ /^intauth_(cost|check|switch)$/) {
14491:                 $curr_defaults{$key} = $domconfig{'defaults'}{$key};
14492:             } else {
14493:                 $save_defaults{$key} = $domconfig{'defaults'}{$key};
14494:             }
14495:         }
14496:     }
14497:     my %staticdefaults = (
14498:         'resetlink'      => 2,
14499:         'resetcase'      => \@oktypes,
14500:         'resetprelink'   => 'both',
14501:         'resetemail'     => ['critical','notify','permanent'],
14502:         'intauth_cost'   => 10,
14503:         'intauth_check'  => 0,
14504:         'intauth_switch' => 0,
14505:     );
14506:     $staticdefaults{'min'} = $Apache::lonnet::passwdmin;
14507:     foreach my $type (@oktypes) {
14508:         $staticdefaults{'resetpostlink'}{$type} = ['email','username'];
14509:     }
14510:     my $linklife = $env{'form.passwords_link'};
14511:     $linklife =~ s/^\s+|\s+$//g;
14512:     if (($linklife =~ /^\d+(|\.\d*)$/) && ($linklife > 0)) {
14513:         $newvalues{'resetlink'} = $linklife;
14514:         if ($current{'resetlink'}) {
14515:             if ($current{'resetlink'} ne $linklife) {
14516:                 $changes{'reset'} = 1;
14517:             }
14518:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
14519:             if ($staticdefaults{'resetlink'} ne $linklife) {
14520:                 $changes{'reset'} = 1;
14521:             }
14522:         }
14523:     } elsif ($current{'resetlink'}) {
14524:         $changes{'reset'} = 1;
14525:     }
14526:     my @casesens;
14527:     my @posscase = &Apache::loncommon::get_env_multiple('form.passwords_case_sensitive');
14528:     foreach my $case (sort(@posscase)) {
14529:         if (grep(/^\Q$case\E$/,@oktypes)) {
14530:             push(@casesens,$case);
14531:         }
14532:     }
14533:     $newvalues{'resetcase'} = \@casesens;
14534:     if (ref($current{'resetcase'}) eq 'ARRAY') {
14535:         my @diffs = &Apache::loncommon::compare_arrays($current{'resetcase'},\@casesens);
14536:         if (@diffs > 0) {
14537:             $changes{'reset'} = 1;
14538:         }
14539:     } elsif (!ref($domconfig{passwords}) eq 'HASH') {
14540:         my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetcase'},\@casesens);
14541:         if (@diffs > 0) {
14542:             $changes{'reset'} = 1;
14543:         }
14544:     }
14545:     if ($env{'form.passwords_prelink'} =~ /^(both|either)$/) {
14546:         $newvalues{'resetprelink'} = $env{'form.passwords_prelink'};
14547:         if (exists($current{'resetprelink'})) {
14548:             if ($current{'resetprelink'} ne $newvalues{'resetprelink'}) {
14549:                 $changes{'reset'} = 1;
14550:             }
14551:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
14552:             if ($staticdefaults{'resetprelink'} ne $newvalues{'resetprelink'}) {
14553:                 $changes{'reset'} = 1;
14554:             }
14555:         }
14556:     } elsif ($current{'resetprelink'}) {
14557:         $changes{'reset'} = 1;
14558:     }
14559:     foreach my $type (@oktypes) {
14560:         my @possplink = &Apache::loncommon::get_env_multiple('form.passwords_postlink_'.$type);
14561:         my @postlink;
14562:         foreach my $item (sort(@possplink)) {
14563:             if ($item =~ /^(email|username)$/) {
14564:                 push(@postlink,$item);
14565:             }
14566:         }
14567:         $newvalues{'resetpostlink'}{$type} = \@postlink;
14568:         unless ($changes{'reset'}) {
14569:             if (ref($current{'resetpostlink'}) eq 'HASH') {
14570:                 if (ref($current{'resetpostlink'}{$type}) eq 'ARRAY') {
14571:                     my @diffs = &Apache::loncommon::compare_arrays($current{'resetpostlink'}{$type},\@postlink);
14572:                     if (@diffs > 0) {
14573:                         $changes{'reset'} = 1;
14574:                     }
14575:                 } else {
14576:                     $changes{'reset'} = 1;
14577:                 }
14578:             } elsif (!ref($domconfig{passwords}) eq 'HASH') {
14579:                 my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetpostlink'}{$type},\@postlink);
14580:                 if (@diffs > 0) {
14581:                     $changes{'reset'} = 1;
14582:                 }
14583:             }
14584:         }
14585:     }
14586:     my @possemailsrc = &Apache::loncommon::get_env_multiple('form.passwords_emailsrc');
14587:     my @resetemail;
14588:     foreach my $item (sort(@possemailsrc)) {
14589:         if ($item =~ /^(permanent|critical|notify)$/) {
14590:             push(@resetemail,$item);
14591:         }
14592:     }
14593:     $newvalues{'resetemail'} = \@resetemail;
14594:     unless ($changes{'reset'}) {
14595:         if (ref($current{'resetemail'}) eq 'ARRAY') {
14596:             my @diffs = &Apache::loncommon::compare_arrays($current{'resetemail'},\@resetemail);
14597:             if (@diffs > 0) {
14598:                 $changes{'reset'} = 1;
14599:             }
14600:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
14601:             my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetemail'},\@resetemail);
14602:             if (@diffs > 0) {
14603:                 $changes{'reset'} = 1;
14604:             }
14605:         }
14606:     }
14607:     if ($env{'form.passwords_stdtext'} == 0) {
14608:         $newvalues{'resetremove'} = 1;
14609:         unless ($current{'resetremove'}) {
14610:             $changes{'reset'} = 1;
14611:         }
14612:     } elsif ($current{'resetremove'}) {
14613:         $changes{'reset'} = 1;
14614:     }
14615:     if ($env{'form.passwords_customfile.filename'} ne '') {
14616:         my $servadm = $r->dir_config('lonAdmEMail');
14617:         my $servadm = $r->dir_config('lonAdmEMail');
14618:         my ($configuserok,$author_ok,$switchserver) =
14619:             &config_check($dom,$confname,$servadm);
14620:         my $error;
14621:         if ($configuserok eq 'ok') {
14622:             if ($switchserver) {
14623:                 $error = &mt("Upload of file containing domain-specific text is not permitted to this server: [_1]",$switchserver);
14624:             } else {
14625:                 if ($author_ok eq 'ok') {
14626:                     my ($result,$customurl) =
14627:                         &publishlogo($r,'upload','passwords_customfile',$dom,
14628:                                      $confname,'customtext/resetpw','','',$customfn);
14629:                     if ($result eq 'ok') {
14630:                         $newvalues{'resetcustom'} = $customurl;
14631:                         $changes{'reset'} = 1;
14632:                     } else {
14633:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$customfn,$result);
14634:                     }
14635:                 } else {
14636:                     $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);
14637:                 }
14638:             }
14639:         } else {
14640:             $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);
14641:         }
14642:         if ($error) {
14643:             &Apache::lonnet::logthis($error);
14644:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
14645:         }
14646:     } elsif ($current{'resetcustom'}) {
14647:         if ($env{'form.passwords_custom_del'}) {
14648:             $changes{'reset'} = 1;
14649:         } else {
14650:             $newvalues{'resetcustom'} = $current{'resetcustom'};
14651:         }
14652:     }
14653:     $env{'form.intauth_cost'} =~ s/^\s+|\s+$//g;
14654:     if (($env{'form.intauth_cost'} ne '') && ($env{'form.intauth_cost'} =~ /^\d+$/)) {
14655:         $save_defaults{'intauth_cost'} = $env{'form.intauth_cost'};
14656:         if ($save_defaults{'intauth_cost'} ne $curr_defaults{'intauth_cost'}) {
14657:             $changes{'intauth'} = 1;
14658:         }
14659:     } else {
14660:         $save_defaults{'intauth_cost'} = $curr_defaults{'intauth_cost'};
14661:     }
14662:     if ($env{'form.intauth_check'} =~ /^(0|1|2)$/) {
14663:         $save_defaults{'intauth_check'} = $env{'form.intauth_check'};
14664:         if ($save_defaults{'intauth_check'} ne $curr_defaults{'intauth_check'}) {
14665:             $changes{'intauth'} = 1;
14666:         }
14667:     } else {
14668:         $save_defaults{'intauth_check'} = $curr_defaults{'intauth_check'};
14669:     }
14670:     if ($env{'form.intauth_switch'} =~ /^(0|1|2)$/) {
14671:         $save_defaults{'intauth_switch'} = $env{'form.intauth_switch'};
14672:         if ($save_defaults{'intauth_switch'} ne $curr_defaults{'intauth_switch'}) {
14673:             $changes{'intauth'} = 1;
14674:         }
14675:     } else {
14676:         $save_defaults{'intauth_check'} = $curr_defaults{'intauth_check'};
14677:     }
14678:     foreach my $item ('cost','check','switch') {
14679:         if ($save_defaults{'intauth_'.$item} ne $domdefaults{'intauth_'.$item}) {
14680:             $domdefaults{'intauth_'.$item} = $save_defaults{'intauth_'.$item};
14681:             $updatedefaults = 1;
14682:         }
14683:     }
14684:     &password_rule_changes('passwords',\%newvalues,\%current,\%changes);
14685:     my %crsownerchg = (
14686:                         by => [],
14687:                         for => [],
14688:                       );
14689:     foreach my $item ('by','for') {
14690:         my @posstypes = &Apache::loncommon::get_env_multiple('form.passwords_crsowner_'.$item);
14691:         foreach my $type (sort(@posstypes)) {
14692:             if (grep(/^\Q$type\E$/,@oktypes)) {
14693:                 push(@{$crsownerchg{$item}},$type);
14694:             }
14695:         }
14696:     }
14697:     $newvalues{'crsownerchg'} = \%crsownerchg;
14698:     if (ref($current{'crsownerchg'}) eq 'HASH') {
14699:         foreach my $item ('by','for') {
14700:             if (ref($current{'crsownerchg'}{$item}) eq 'ARRAY') {
14701:                 my @diffs = &Apache::loncommon::compare_arrays($current{'crsownerchg'}{$item},$crsownerchg{$item});
14702:                 if (@diffs > 0) {
14703:                     $changes{'crsownerchg'} = 1;
14704:                     last;
14705:                 }
14706:             }
14707:         }
14708:     } elsif (!(ref($domconfig{passwords}) eq 'HASH')) {
14709:         foreach my $item ('by','for') {
14710:             if (@{$crsownerchg{$item}} > 0) {
14711:                 $changes{'crsownerchg'} = 1;
14712:                 last;
14713:             }
14714:         }
14715:     }
14716: 
14717:     my %confighash = (
14718:                         defaults  => \%save_defaults,
14719:                         passwords => \%newvalues,
14720:                      );
14721:     &process_captcha('passwords',\%changes,$confighash{'passwords'},$domconfig{'passwords'});
14722: 
14723:     my $putresult = &Apache::lonnet::put_dom('configuration',\%confighash,$dom);
14724:     if ($putresult eq 'ok') {
14725:         if (keys(%changes) > 0) {
14726:             $resulttext = &mt('Changes made: ').'<ul>';
14727:             foreach my $key ('reset','intauth','rules','crsownerchg') {
14728:                 if ($changes{$key}) {
14729:                     unless ($key eq 'intauth') {
14730:                         $updateconf = 1;
14731:                     }
14732:                     $resulttext .= '<li>'.$titles{$key}.':<ul>';
14733:                     if ($key eq 'reset') {
14734:                         if ($confighash{'passwords'}{'captcha'} eq 'original') {
14735:                             $resulttext .= '<li>'.&mt('CAPTCHA validation set to use: original CAPTCHA').'</li>';
14736:                         } elsif ($confighash{'passwords'}{'captcha'} eq 'recaptcha') {
14737:                             $resulttext .= '<li>'.&mt('CAPTCHA validation set to use: reCAPTCHA').' '.
14738:                                            &mt('version: [_1]',$confighash{'passwords'}{'recaptchaversion'}).'<br />';
14739:                             if (ref($confighash{'passwords'}{'recaptchakeys'}) eq 'HASH') {
14740:                                 $resulttext .= &mt('Public key: [_1]',$confighash{'passwords'}{'recaptchakeys'}{'public'}).'</br>'.
14741:                                                &mt('Private key: [_1]',$confighash{'passwords'}{'recaptchakeys'}{'private'}).'</li>';
14742:                             }
14743:                         } else {
14744:                             $resulttext .= '<li>'.&mt('No CAPTCHA validation').'</li>';
14745:                         }
14746:                         if ($confighash{'passwords'}{'resetlink'}) {
14747:                             $resulttext .= '<li>'.&mt('Reset link expiration set to [quant,_1,hour]',$confighash{'passwords'}{'resetlink'}).'</li>';
14748:                         } else {
14749:                             $resulttext .= '<li>'.&mt('No reset link expiration set.').' '.
14750:                                                   &mt('Will default to 2 hours').'</li>';
14751:                         }
14752:                         if (ref($confighash{'passwords'}{'resetcase'}) eq 'ARRAY') {
14753:                             if (@{$confighash{'passwords'}{'resetcase'}} == 0) {
14754:                                 $resulttext .= '<li>'.&mt('User input for username and/or e-mail address not case sensitive for "Forgot Password" web form').'</li>';
14755:                             } else {
14756:                                 my $casesens;
14757:                                 foreach my $type (@{$confighash{'passwords'}{'resetcase'}}) {
14758:                                     if ($type eq 'default') {
14759:                                         $casesens .= $othertitle.', ';
14760:                                     } elsif ($usertypes->{$type} ne '') {
14761:                                         $casesens .= $usertypes->{$type}.', ';
14762:                                     }
14763:                                 }
14764:                                 $casesens =~ s/\Q, \E$//;
14765:                                 $resulttext .= '<li>'.&mt('"Forgot Password" web form input for username and/or e-mail address is case-sensitive for: [_1]',$casesens).'</li>';
14766:                             }
14767:                         } else {
14768:                             $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>';
14769:                         }
14770:                         if ($confighash{'passwords'}{'resetprelink'} eq 'either') {
14771:                             $resulttext .= '<li>'.&mt('Users can enter either a username or an e-mail address in "Forgot Password" web form').'</li>';
14772:                         } else {
14773:                             $resulttext .= '<li>'.&mt('Users can enter both a username and an e-mail address in "Forgot Password" web form').'</li>';
14774:                         }
14775:                         if (ref($confighash{'passwords'}{'resetpostlink'}) eq 'HASH') {
14776:                             my $output;
14777:                             if (ref($types) eq 'ARRAY') {
14778:                                 foreach my $type (@{$types}) {
14779:                                     if (ref($confighash{'passwords'}{'resetpostlink'}{$type}) eq 'ARRAY') {
14780:                                         if (@{$confighash{'passwords'}{'resetpostlink'}{$type}} == 0) {
14781:                                             $output .= $usertypes->{$type}.' -- '.&mt('none');
14782:                                         } else {
14783:                                             $output .= $usertypes->{$type}.' -- '.
14784:                                                        join(', ',map { $titles{$_}; } (@{$confighash{'passwords'}{'resetpostlink'}{$type}})).'; ';
14785:                                         }
14786:                                     }
14787:                                 }
14788:                             }
14789:                             if (ref($confighash{'passwords'}{'resetpostlink'}{'default'}) eq 'ARRAY') {
14790:                                 if (@{$confighash{'passwords'}{'resetpostlink'}{'default'}} == 0) {
14791:                                     $output .= $othertitle.' -- '.&mt('none');
14792:                                 } else {
14793:                                     $output .= $othertitle.' -- '.
14794:                                                join(', ',map { $titles{$_}; } (@{$confighash{'passwords'}{'resetpostlink'}{'default'}}));
14795:                                 }
14796:                             }
14797:                             if ($output) {
14798:                                 $resulttext .= '<li>'.&mt('Information required for new password form (by user type) set to: [_1]',$output).'</li>';
14799:                             } else {
14800:                                 $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>';
14801:                             }
14802:                         } else {
14803:                             $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>';
14804:                         }
14805:                         if (ref($confighash{'passwords'}{'resetemail'}) eq 'ARRAY') {
14806:                             if (@{$confighash{'passwords'}{'resetemail'}} > 0) {
14807:                                 $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$confighash{'passwords'}{'resetemail'}})).'</li>';
14808:                             } else {
14809:                                 $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$staticdefaults{'resetemail'}})).'</li>';
14810:                             }
14811:                         } else {
14812:                             $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$staticdefaults{'resetemail'}})).'</li>';
14813:                         }
14814:                         if ($confighash{'passwords'}{'resetremove'}) {
14815:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" web form not shown').'</li>';
14816:                         } else {
14817:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" web form is shown').'</li>';
14818:                         }
14819:                         if ($confighash{'passwords'}{'resetcustom'}) {
14820:                             my $customlink = &Apache::loncommon::modal_link($confighash{'passwords'}{'resetcustom'},
14821:                                                                             &mt('custom text'),600,500,undef,undef,
14822:                                                                             undef,undef,'background-color:#ffffff');
14823:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" form includes: [_1]',$customlink).'</li>';
14824:                         } else {
14825:                             $resulttext .= '<li>'.&mt('No custom text included in preamble to "Forgot Password" form').'</li>';
14826:                         }
14827:                     } elsif ($key eq 'intauth') {
14828:                         foreach my $item ('cost','switch','check') {
14829:                             my $value = $save_defaults{$key.'_'.$item};
14830:                             if ($item eq 'switch') {
14831:                                 my %optiondesc = &Apache::lonlocal::texthash (
14832:                                                      0 => 'No',
14833:                                                      1 => 'Yes',
14834:                                                      2 => 'Yes, and copy existing passwd file to passwd.bak file',
14835:                                                  );
14836:                                 if ($value =~ /^(0|1|2)$/) {
14837:                                     $value = $optiondesc{$value};
14838:                                 } else {
14839:                                     $value = &mt('none -- defaults to No');
14840:                                 }
14841:                             } elsif ($item eq 'check') {
14842:                                 my %optiondesc = &Apache::lonlocal::texthash (
14843:                                                      0 => 'No',
14844:                                                      1 => 'Yes, allow login then update passwd file using default cost (if higher)',
14845:                                                      2 => 'Yes, disallow login if stored cost is less than domain default',
14846:                                                  );
14847:                                 if ($value =~ /^(0|1|2)$/) {
14848:                                     $value = $optiondesc{$value};
14849:                                 } else {
14850:                                     $value = &mt('none -- defaults to No');
14851:                                 }
14852:                             }
14853:                             $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$titles{$key.'_'.$item},$value).'</li>';
14854:                         }
14855:                     } elsif ($key eq 'rules') {
14856:                         foreach my $rule ('min','max','numsaved') {
14857:                             if ($confighash{'passwords'}{$rule} eq '') {
14858:                                 if ($rule eq 'min') {
14859:                                     $resulttext .= '<li>'.&mt('[_1] not set.',$titles{$rule});
14860:                                                    ' '.&mt('Default of [_1] will be used',
14861:                                                            $Apache::lonnet::passwdmin).'</li>';
14862:                                 } else {
14863:                                     $resulttext .= '<li>'.&mt('[_1] set to none',$titles{$rule}).'</li>';
14864:                                 }
14865:                             } else {
14866:                                 $resulttext .= '<li>'.&mt('[_1] set to [_2]',$titles{$rule},$confighash{'passwords'}{$rule}).'</li>';
14867:                             }
14868:                         }
14869:                         if (ref($confighash{'passwords'}{'chars'}) eq 'ARRAY') {
14870:                             if (@{$confighash{'passwords'}{'chars'}} > 0) {
14871:                                 my %rulenames = &Apache::lonlocal::texthash(
14872:                                                      uc => 'At least one upper case letter',
14873:                                                      lc => 'At least one lower case letter',
14874:                                                      num => 'At least one number',
14875:                                                      spec => 'At least one non-alphanumeric',
14876:                                                    );
14877:                                 my $needed = '<ul><li>'.
14878:                                              join('</li><li>',map {$rulenames{$_} } @{$confighash{'passwords'}{'chars'}}).
14879:                                              '</li></ul>';
14880:                                 $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$titles{'chars'},$needed).'</li>';
14881:                             } else {
14882:                                 $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
14883:                             }
14884:                         } else {
14885:                             $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
14886:                         }
14887:                     } elsif ($key eq 'crsownerchg') {
14888:                         if (ref($confighash{'passwords'}{'crsownerchg'}) eq 'HASH') {
14889:                             if ((@{$confighash{'passwords'}{'crsownerchg'}{'by'}} == 0) ||
14890:                                 (@{$confighash{'passwords'}{'crsownerchg'}{'for'}} == 0)) {
14891:                                 $resulttext .= '<li>'.&mt('Course owner may not change student passwords.').'</li>';
14892:                             } else {
14893:                                 my %crsownerstr;
14894:                                 foreach my $item ('by','for') {
14895:                                     if (ref($confighash{'passwords'}{'crsownerchg'}{$item}) eq 'ARRAY') {
14896:                                         foreach my $type (@{$confighash{'passwords'}{'crsownerchg'}{$item}}) {
14897:                                             if ($type eq 'default') {
14898:                                                 $crsownerstr{$item} .= $othertitle.', ';
14899:                                             } elsif ($usertypes->{$type} ne '') {
14900:                                                 $crsownerstr{$item} .= $usertypes->{$type}.', ';
14901:                                             }
14902:                                         }
14903:                                         $crsownerstr{$item} =~ s/\Q, \E$//;
14904:                                     }
14905:                                 }
14906:                                 $resulttext .= '<li>'.&mt('Course owner (with status: [_1]) may change passwords for students (with status: [_2]).',
14907:                                            $crsownerstr{'by'},$crsownerstr{'for'}).'</li>';
14908:                             }
14909:                         } else {
14910:                             $resulttext .= '<li>'.&mt('Course owner may not change student passwords.').'</li>';
14911:                         }
14912:                     }
14913:                     $resulttext .= '</ul></li>';
14914:                 }
14915:             }
14916:             $resulttext .= '</ul>';
14917:         } else {
14918:             $resulttext = &mt('No changes made to password settings');
14919:         }
14920:         my $cachetime = 24*60*60;
14921:         if ($updatedefaults) {
14922:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
14923:             if (ref($lastactref) eq 'HASH') {
14924:                 $lastactref->{'domdefaults'} = 1;
14925:             }
14926:         }
14927:         if ($updateconf) {
14928:             &Apache::lonnet::do_cache_new('passwdconf',$dom,$confighash{'passwords'},$cachetime);
14929:             if (ref($lastactref) eq 'HASH') {
14930:                 $lastactref->{'passwdconf'} = 1;
14931:             }
14932:         }
14933:     } else {
14934:         $resulttext = '<span class="LC_error">'.
14935:             &mt('An error occurred: [_1]',$putresult).'</span>';
14936:     }
14937:     if ($errors) {
14938:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
14939:                        $errors.'</ul></p>';
14940:     }
14941:     return $resulttext;
14942: }
14943: 
14944: sub password_rule_changes {
14945:     my ($prefix,$newvalues,$current,$changes) = @_;
14946:     return unless ((ref($newvalues) eq 'HASH') &&
14947:                    (ref($current) eq 'HASH') &&
14948:                    (ref($changes) eq 'HASH'));
14949:     my (@rules,%staticdefaults);
14950:     if ($prefix eq 'passwords') {
14951:         @rules = ('min','max','numsaved');
14952:     } elsif ($prefix eq 'secrets') {
14953:         @rules = ('min','max');
14954:     }
14955:     $staticdefaults{'min'} = $Apache::lonnet::passwdmin;
14956:     foreach my $rule (@rules) {
14957:         $env{'form.'.$prefix.'_'.$rule} =~ s/^\s+|\s+$//g;
14958:         my $ruleok;
14959:         if ($rule eq 'min') {
14960:             if ($env{'form.'.$prefix.'_'.$rule} =~ /^\d+$/) {
14961:                 if ($env{'form.'.$prefix.'_'.$rule} >= $staticdefaults{$rule}) {
14962:                     $ruleok = 1;
14963:                 }
14964:             }
14965:         } elsif (($env{'form.'.$prefix.'_'.$rule} =~ /^\d+$/) &&
14966:                  ($env{'form.'.$prefix.'_'.$rule} ne '0')) {
14967:             $ruleok = 1;
14968:         }
14969:         if ($ruleok) {
14970:             $newvalues->{$rule} = $env{'form.'.$prefix.'_'.$rule};
14971:             if (exists($current->{$rule})) {
14972:                 if ($newvalues->{$rule} ne $current->{$rule}) {
14973:                     $changes->{'rules'} = 1;
14974:                 }
14975:             } elsif ($rule eq 'min') {
14976:                 if ($staticdefaults{$rule} ne $newvalues->{$rule}) {
14977:                     $changes->{'rules'} = 1;
14978:                 }
14979:             } else {
14980:                 $changes->{'rules'} = 1;
14981:             }
14982:         } elsif (exists($current->{$rule})) {
14983:             $changes->{'rules'} = 1;
14984:         }
14985:     }
14986:     my @posschars = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_chars');
14987:     my @chars;
14988:     foreach my $item (sort(@posschars)) {
14989:         if ($item =~ /^(uc|lc|num|spec)$/) {
14990:             push(@chars,$item);
14991:         }
14992:     }
14993:     $newvalues->{'chars'} = \@chars;
14994:     unless ($changes->{'rules'}) {
14995:         if (ref($current->{'chars'}) eq 'ARRAY') {
14996:             my @diffs = &Apache::loncommon::compare_arrays($current->{'chars'},\@chars);
14997:             if (@diffs > 0) {
14998:                 $changes->{'rules'} = 1;
14999:             }
15000:         } else {
15001:             if (@chars > 0) {
15002:                 $changes->{'rules'} = 1;
15003:             }
15004:         }
15005:     }
15006:     return;
15007: }
15008: 
15009: sub modify_usercreation {
15010:     my ($dom,%domconfig) = @_;
15011:     my ($resulttext,%curr_usercreation,%changes,%authallowed,%cancreate,%save_usercreate);
15012:     my $warningmsg;
15013:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
15014:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
15015:             if ($key eq 'cancreate') {
15016:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
15017:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
15018:                         if (($item eq 'requestcrs') || ($item eq 'course') || ($item eq 'author')) {
15019:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
15020:                         } else {
15021:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
15022:                         }
15023:                     }
15024:                 }
15025:             } elsif ($key eq 'email_rule') {
15026:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
15027:             } else {
15028:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
15029:             }
15030:         }
15031:     }
15032:     my @username_rule = &Apache::loncommon::get_env_multiple('form.username_rule');
15033:     my @id_rule = &Apache::loncommon::get_env_multiple('form.id_rule');
15034:     my @contexts = ('author','course','requestcrs');
15035:     foreach my $item(@contexts) {
15036:         $cancreate{$item} = $env{'form.can_createuser_'.$item};
15037:     }
15038:     if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
15039:         foreach my $item (@contexts) {
15040:             if ($curr_usercreation{'cancreate'}{$item} ne $cancreate{$item}) {
15041:                 push(@{$changes{'cancreate'}},$item);
15042:             }
15043:         }
15044:     } elsif (ref($curr_usercreation{'cancreate'}) eq 'ARRAY') {
15045:         foreach my $item (@contexts) {
15046:             if (!grep(/^\Q$item\E$/,@{$curr_usercreation{'cancreate'}})) {
15047:                 if ($cancreate{$item} ne 'any') {
15048:                     push(@{$changes{'cancreate'}},$item);
15049:                 }
15050:             } else {
15051:                 if ($cancreate{$item} ne 'none') {
15052:                     push(@{$changes{'cancreate'}},$item);
15053:                 }
15054:             }
15055:         }
15056:     } else {
15057:         foreach my $item (@contexts)  {
15058:             push(@{$changes{'cancreate'}},$item);
15059:         }
15060:     }
15061: 
15062:     if (ref($curr_usercreation{'username_rule'}) eq 'ARRAY') {
15063:         foreach my $type (@{$curr_usercreation{'username_rule'}}) {
15064:             if (!grep(/^\Q$type\E$/,@username_rule)) {
15065:                 push(@{$changes{'username_rule'}},$type);
15066:             }
15067:         }
15068:         foreach my $type (@username_rule) {
15069:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'username_rule'}})) {
15070:                 push(@{$changes{'username_rule'}},$type);
15071:             }
15072:         }
15073:     } else {
15074:         push(@{$changes{'username_rule'}},@username_rule);
15075:     }
15076: 
15077:     if (ref($curr_usercreation{'id_rule'}) eq 'ARRAY') {
15078:         foreach my $type (@{$curr_usercreation{'id_rule'}}) {
15079:             if (!grep(/^\Q$type\E$/,@id_rule)) {
15080:                 push(@{$changes{'id_rule'}},$type);
15081:             }
15082:         }
15083:         foreach my $type (@id_rule) {
15084:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'id_rule'}})) {
15085:                 push(@{$changes{'id_rule'}},$type);
15086:             }
15087:         }
15088:     } else {
15089:         push(@{$changes{'id_rule'}},@id_rule);
15090:     }
15091: 
15092:     my @authen_contexts = ('author','course','domain');
15093:     my @authtypes = ('int','krb4','krb5','loc');
15094:     my %authhash;
15095:     foreach my $item (@authen_contexts) {
15096:         my @authallowed =  &Apache::loncommon::get_env_multiple('form.'.$item.'_auth');
15097:         foreach my $auth (@authtypes) {
15098:             if (grep(/^\Q$auth\E$/,@authallowed)) {
15099:                 $authhash{$item}{$auth} = 1;
15100:             } else {
15101:                 $authhash{$item}{$auth} = 0;
15102:             }
15103:         }
15104:     }
15105:     if (ref($curr_usercreation{'authtypes'}) eq 'HASH') {
15106:         foreach my $item (@authen_contexts) {
15107:             if (ref($curr_usercreation{'authtypes'}{$item}) eq 'HASH') {
15108:                 foreach my $auth (@authtypes) {
15109:                     if ($authhash{$item}{$auth} ne $curr_usercreation{'authtypes'}{$item}{$auth}) {
15110:                         push(@{$changes{'authtypes'}},$item);
15111:                         last;
15112:                     }
15113:                 }
15114:             }
15115:         }
15116:     } else {
15117:         foreach my $item (@authen_contexts) {
15118:             push(@{$changes{'authtypes'}},$item);
15119:         }
15120:     }
15121: 
15122:     $save_usercreate{'cancreate'}{'course'} = $cancreate{'course'}; 
15123:     $save_usercreate{'cancreate'}{'author'} = $cancreate{'author'};
15124:     $save_usercreate{'cancreate'}{'requestcrs'} = $cancreate{'requestcrs'};
15125:     $save_usercreate{'id_rule'} = \@id_rule;
15126:     $save_usercreate{'username_rule'} = \@username_rule,
15127:     $save_usercreate{'authtypes'} = \%authhash;
15128: 
15129:     my %usercreation_hash =  (
15130:         usercreation     => \%save_usercreate,
15131:     );
15132: 
15133:     my $putresult = &Apache::lonnet::put_dom('configuration',\%usercreation_hash,
15134:                                              $dom);
15135: 
15136:     if ($putresult eq 'ok') {
15137:         if (keys(%changes) > 0) {
15138:             $resulttext = &mt('Changes made:').'<ul>';
15139:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
15140:                 my %lt = &usercreation_types();
15141:                 foreach my $type (@{$changes{'cancreate'}}) {
15142:                     my $chgtext = $lt{$type}.', ';
15143:                     if ($cancreate{$type} eq 'none') {
15144:                         $chgtext .= &mt('creation of new users is not permitted, except by a Domain Coordinator.');
15145:                     } elsif ($cancreate{$type} eq 'any') {
15146:                         $chgtext .= &mt('creation of new users is permitted for both institutional and non-institutional usernames.');
15147:                     } elsif ($cancreate{$type} eq 'official') {
15148:                         $chgtext .= &mt('creation of new users is only permitted for institutional usernames.');
15149:                     } elsif ($cancreate{$type} eq 'unofficial') {
15150:                         $chgtext .= &mt('creation of new users is only permitted for non-institutional usernames.');
15151:                     }
15152:                     $resulttext .= '<li>'.$chgtext.'</li>';
15153:                 }
15154:             }
15155:             if (ref($changes{'username_rule'}) eq 'ARRAY') {
15156:                 my ($rules,$ruleorder) = 
15157:                     &Apache::lonnet::inst_userrules($dom,'username');
15158:                 my $chgtext = '<ul>';
15159:                 foreach my $type (@username_rule) {
15160:                     if (ref($rules->{$type}) eq 'HASH') {
15161:                         $chgtext .= '<li>'.$rules->{$type}{'name'}.'</li>';
15162:                     }
15163:                 }
15164:                 $chgtext .= '</ul>';
15165:                 if (@username_rule > 0) {
15166:                     $resulttext .= '<li>'.&mt('Usernames with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';     
15167:                 } else {
15168:                     $resulttext .= '<li>'.&mt('There are now no username formats restricted to verified users in the institutional directory.').'</li>'; 
15169:                 }
15170:             }
15171:             if (ref($changes{'id_rule'}) eq 'ARRAY') {
15172:                 my ($idrules,$idruleorder) = 
15173:                     &Apache::lonnet::inst_userrules($dom,'id');
15174:                 my $chgtext = '<ul>';
15175:                 foreach my $type (@id_rule) {
15176:                     if (ref($idrules->{$type}) eq 'HASH') {
15177:                         $chgtext .= '<li>'.$idrules->{$type}{'name'}.'</li>';
15178:                     }
15179:                 }
15180:                 $chgtext .= '</ul>';
15181:                 if (@id_rule > 0) {
15182:                     $resulttext .= '<li>'.&mt('IDs with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';
15183:                 } else {
15184:                     $resulttext .= '<li>'.&mt('There are now no ID formats restricted to verified users in the institutional directory.').'</li>';
15185:                 }
15186:             }
15187:             my %authname = &authtype_names();
15188:             my %context_title = &context_names();
15189:             if (ref($changes{'authtypes'}) eq 'ARRAY') {
15190:                 my $chgtext = '<ul>';
15191:                 foreach my $type (@{$changes{'authtypes'}}) {
15192:                     my @allowed;
15193:                     $chgtext .= '<li><span class="LC_cusr_emph">'.$context_title{$type}.'</span> - '.&mt('assignable authentication types: ');
15194:                     foreach my $auth (@authtypes) {
15195:                         if ($authhash{$type}{$auth}) {
15196:                             push(@allowed,$authname{$auth});
15197:                         }
15198:                     }
15199:                     if (@allowed > 0) {
15200:                         $chgtext .= join(', ',@allowed).'</li>';
15201:                     } else {
15202:                         $chgtext .= &mt('none').'</li>';
15203:                     }
15204:                 }
15205:                 $chgtext .= '</ul>';
15206:                 $resulttext .= '<li>'.&mt('Authentication types available for assignment to new users').'<br />'.$chgtext;
15207:                 $resulttext .= '</li>';
15208:             }
15209:             $resulttext .= '</ul>';
15210:         } else {
15211:             $resulttext = &mt('No changes made to user creation settings');
15212:         }
15213:     } else {
15214:         $resulttext = '<span class="LC_error">'.
15215:             &mt('An error occurred: [_1]',$putresult).'</span>';
15216:     }
15217:     if ($warningmsg ne '') {
15218:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
15219:     }
15220:     return $resulttext;
15221: }
15222: 
15223: sub modify_selfcreation {
15224:     my ($dom,$lastactref,%domconfig) = @_;
15225:     my ($resulttext,$warningmsg,%curr_usercreation,%curr_usermodify,%curr_inststatus,%changes,%cancreate);
15226:     my (%save_usercreate,%save_usermodify,%save_inststatus,@types,%usertypes);
15227:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
15228:     my ($othertitle,$usertypesref,$typesref) = &Apache::loncommon::sorted_inst_types($dom);
15229:     if (ref($typesref) eq 'ARRAY') {
15230:         @types = @{$typesref};
15231:     }
15232:     if (ref($usertypesref) eq 'HASH') {
15233:         %usertypes = %{$usertypesref};
15234:     }
15235:     $usertypes{'default'} = $othertitle;
15236: #
15237: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usercreation'}.
15238: #
15239:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
15240:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
15241:             if ($key eq 'cancreate') {
15242:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
15243:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
15244:                         if (($item eq 'selfcreate') || ($item eq 'statustocreate') ||
15245:                             ($item eq 'captcha') || ($item eq 'recaptchakeys') ||
15246:                             ($item eq 'recaptchaversion') || ($item eq 'notify') ||
15247:                             ($item eq 'emailusername') || ($item eq 'shibenv') ||
15248:                             ($item eq 'selfcreateprocessing') || ($item eq 'emailverified') ||
15249:                             ($item eq 'emailoptions') || ($item eq 'emaildomain')) {
15250:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
15251:                         } else {
15252:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
15253:                         }
15254:                     }
15255:                 }
15256:             } elsif ($key eq 'email_rule') {
15257:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
15258:             } else {
15259:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
15260:             }
15261:         }
15262:     }
15263: #
15264: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usermodification'}.
15265: #
15266:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
15267:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
15268:             if ($key eq 'selfcreate') {
15269:                 $curr_usermodify{$key} = $domconfig{'usermodification'}{$key};
15270:             } else {
15271:                 $save_usermodify{$key} = $domconfig{'usermodification'}{$key};
15272:             }
15273:         }
15274:     }
15275: #
15276: # Retrieve current domain configuration for institutional status types from $domconfig{'inststatus'}.
15277: #
15278:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
15279:         foreach my $key (keys(%{$domconfig{'inststatus'}})) {
15280:             if ($key eq 'inststatusguest') {
15281:                 $curr_inststatus{$key} = $domconfig{'inststatus'}{$key};
15282:             } else {
15283:                 $save_inststatus{$key} = $domconfig{'inststatus'}{$key};
15284:             }
15285:         }
15286:     }
15287: 
15288:     my @contexts = ('selfcreate');
15289:     @{$cancreate{'selfcreate'}} = ();
15290:     %{$cancreate{'emailusername'}} = ();
15291:     if (@types) {
15292:         @{$cancreate{'statustocreate'}} = ();
15293:     }
15294:     %{$cancreate{'selfcreateprocessing'}} = ();
15295:     %{$cancreate{'shibenv'}} = ();
15296:     %{$cancreate{'emailverified'}} = ();
15297:     %{$cancreate{'emailoptions'}} = ();
15298:     %{$cancreate{'emaildomain'}} = ();
15299:     my %selfcreatetypes = (
15300:                              sso   => 'users authenticated by institutional single sign on',
15301:                              login => 'users authenticated by institutional log-in',
15302:                              email => 'users verified by e-mail',
15303:                           );
15304: #
15305: # Populate $cancreate{'selfcreate'} array reference with types of user, for which self-creation of user accounts
15306: # is permitted.
15307: #
15308: 
15309:     my ($emailrules,$emailruleorder) = &Apache::lonnet::inst_userrules($dom,'email');
15310: 
15311:     my (@statuses,%email_rule);
15312:     foreach my $item ('login','sso','email') {
15313:         if ($item eq 'email') {
15314:             if ($env{'form.cancreate_email'}) {
15315:                 if (@types) {
15316:                     my @poss_statuses = &Apache::loncommon::get_env_multiple('form.selfassign');
15317:                     foreach my $status (@poss_statuses) {
15318:                         if (grep(/^\Q$status\E$/,(@types,'default'))) {
15319:                             push(@statuses,$status);
15320:                         }
15321:                     }
15322:                     $save_inststatus{'inststatusguest'} = \@statuses;
15323:                 } else {
15324:                     push(@statuses,'default');
15325:                 }
15326:                 if (@statuses) {
15327:                     my %curr_rule;
15328:                     if (ref($curr_usercreation{'email_rule'}) eq 'ARRAY') {
15329:                         foreach my $type (@statuses) {
15330:                             $curr_rule{$type} = $curr_usercreation{'email_rule'};
15331:                         }
15332:                     } elsif (ref($curr_usercreation{'email_rule'}) eq 'HASH') {
15333:                         foreach my $type (@statuses) {
15334:                             $curr_rule{$type} = $curr_usercreation{'email_rule'}{$type};
15335:                         }
15336:                     }
15337:                     push(@{$cancreate{'selfcreate'}},'email');
15338:                     push(@contexts,('selfcreateprocessing','emailverified','emailoptions'));
15339:                     my %curremaildom;
15340:                     if (ref($curr_usercreation{'cancreate'}{'emaildomain'}) eq 'HASH') {
15341:                         %curremaildom = %{$curr_usercreation{'cancreate'}{'emaildomain'}};
15342:                     }
15343:                     foreach my $type (@statuses) {
15344:                         if ($env{'form.cancreate_emailprocess_'.$type} =~ /^(?:approval|automatic)$/) {
15345:                             $cancreate{'selfcreateprocessing'}{$type} = $env{'form.cancreate_emailprocess_'.$type};
15346:                         }
15347:                         if ($env{'form.cancreate_usernameoptions_'.$type} =~ /^(?:all|first|free)$/) {
15348:                             $cancreate{'emailverified'}{$type} = $env{'form.cancreate_usernameoptions_'.$type};
15349:                         }
15350:                         if ($env{'form.cancreate_emailoptions_'.$type} =~ /^(any|inst|noninst|custom)$/) {
15351: #
15352: # Retrieve rules (if any) governing types of e-mail address which may be used to verify a username.
15353: #
15354:                             my $chosen = $1;
15355:                             if (($chosen eq 'inst') || ($chosen eq 'noninst')) {
15356:                                 my $emaildom;
15357:                                 if ($env{'form.cancreate_emaildomain_'.$chosen.'_'.$type} =~ /^\@[^\@]+$/) {
15358:                                     $emaildom = $env{'form.cancreate_emaildomain_'.$chosen.'_'.$type};
15359:                                     $cancreate{'emaildomain'}{$type}{$chosen} = $emaildom;
15360:                                     if (ref($curremaildom{$type}) eq 'HASH') {
15361:                                         if (exists($curremaildom{$type}{$chosen})) {
15362:                                             if ($curremaildom{$type}{$chosen} ne $emaildom) {
15363:                                                 push(@{$changes{'cancreate'}},'emaildomain');
15364:                                             }
15365:                                         } elsif ($emaildom ne '') {
15366:                                             push(@{$changes{'cancreate'}},'emaildomain');
15367:                                         }
15368:                                     } elsif ($emaildom ne '') {
15369:                                         push(@{$changes{'cancreate'}},'emaildomain');
15370:                                     }
15371:                                 }
15372:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
15373:                             } elsif ($chosen eq 'custom') {
15374:                                 my @possemail_rules = &Apache::loncommon::get_env_multiple('form.email_rule_'.$type);
15375:                                 $email_rule{$type} = [];
15376:                                 if (ref($emailrules) eq 'HASH') {
15377:                                     foreach my $rule (@possemail_rules) {
15378:                                         if (exists($emailrules->{$rule})) {
15379:                                             push(@{$email_rule{$type}},$rule);
15380:                                         }
15381:                                     }
15382:                                 }
15383:                                 if (@{$email_rule{$type}}) {
15384:                                     $cancreate{'emailoptions'}{$type} = 'custom';
15385:                                     if (ref($curr_rule{$type}) eq 'ARRAY') {
15386:                                         if (@{$curr_rule{$type}} > 0) {
15387:                                             foreach my $rule (@{$curr_rule{$type}}) {
15388:                                                 if (!grep(/^\Q$rule\E$/,@{$email_rule{$type}})) {
15389:                                                     push(@{$changes{'email_rule'}},$type);
15390:                                                 }
15391:                                             }
15392:                                         }
15393:                                         foreach my $type (@{$email_rule{$type}}) {
15394:                                             if (!grep(/^\Q$type\E$/,@{$curr_rule{$type}})) {
15395:                                                 push(@{$changes{'email_rule'}},$type);
15396:                                             }
15397:                                         }
15398:                                     } else {
15399:                                         push(@{$changes{'email_rule'}},$type);
15400:                                     }
15401:                                 }
15402:                             } else {
15403:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
15404:                             }
15405:                         }
15406:                     }
15407:                     if (@types) {
15408:                         if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
15409:                             my @changed = &Apache::loncommon::compare_arrays(\@statuses,$curr_inststatus{'inststatusguest'});
15410:                             if (@changed) {
15411:                                 push(@{$changes{'inststatus'}},'inststatusguest');
15412:                             }
15413:                         } else {
15414:                             push(@{$changes{'inststatus'}},'inststatusguest');
15415:                         }
15416:                     }
15417:                 } else {
15418:                     delete($env{'form.cancreate_email'});
15419:                     if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
15420:                         if (@{$curr_inststatus{'inststatusguest'}} > 0) {
15421:                             push(@{$changes{'inststatus'}},'inststatusguest');
15422:                         }
15423:                     }
15424:                 }
15425:             } else {
15426:                 $save_inststatus{'inststatusguest'} = [];
15427:                 if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
15428:                     if (@{$curr_inststatus{'inststatusguest'}} > 0) {
15429:                         push(@{$changes{'inststatus'}},'inststatusguest');
15430:                     }
15431:                 }
15432:             }
15433:         } else {
15434:             if ($env{'form.cancreate_'.$item}) {
15435:                 push(@{$cancreate{'selfcreate'}},$item);
15436:             }
15437:         }
15438:     }
15439:     my (%userinfo,%savecaptcha);
15440:     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
15441: #
15442: # Populate $cancreate{'emailusername'}{$type} hash ref with information fields (if new user will provide data
15443: # value set to one), if self-creation with e-mail address permitted, where $type is user type: faculty, staff, student etc.
15444: #
15445: 
15446:     if ($env{'form.cancreate_email'}) {
15447:         push(@contexts,'emailusername');
15448:         if (@statuses) {
15449:             foreach my $type (@statuses) {
15450:                 if (ref($infofields) eq 'ARRAY') {
15451:                     foreach my $field (@{$infofields}) {
15452:                         if ($env{'form.canmodify_emailusername_'.$type.'_'.$field} =~ /^(required|optional)$/) {
15453:                             $cancreate{'emailusername'}{$type}{$field} = $1;
15454:                         }
15455:                     }
15456:                 }
15457:             }
15458:         }
15459: #
15460: # Populate $cancreate{'notify'} hash ref with names of Domain Coordinators who are to be notified of
15461: # queued requests for self-creation of account verified by e-mail.
15462: #
15463: 
15464:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.selfcreationnotifyapproval');
15465:         @approvalnotify = sort(@approvalnotify);
15466:         $cancreate{'notify'}{'approval'} = join(',',@approvalnotify);
15467:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
15468:             if (ref($curr_usercreation{'cancreate'}{'notify'}) eq 'HASH') {
15469:                 if ($curr_usercreation{'cancreate'}{'notify'}{'approval'} ne $cancreate{'notify'}{'approval'}) {
15470:                     push(@{$changes{'cancreate'}},'notify');
15471:                 }
15472:             } else {
15473:                 if ($cancreate{'notify'}{'approval'}) {
15474:                     push(@{$changes{'cancreate'}},'notify');
15475:                 }
15476:             }
15477:         } elsif ($cancreate{'notify'}{'approval'}) {
15478:             push(@{$changes{'cancreate'}},'notify');
15479:         }
15480: 
15481:         &process_captcha('cancreate',\%changes,\%savecaptcha,$curr_usercreation{'cancreate'});
15482:     }
15483: #  
15484: # Check if domain default is set appropriately, if self-creation of accounts is to be available for
15485: # institutional log-in.
15486: #
15487:     if (grep(/^login$/,@{$cancreate{'selfcreate'}})) {
15488:         if (!((($domdefaults{'auth_def'} =~/^krb/) && ($domdefaults{'auth_arg_def'} ne '')) || 
15489:                ($domdefaults{'auth_def'} eq 'localauth'))) {
15490:             $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.').' '.
15491:                           &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.');
15492:         }
15493:     }
15494:     my @fields = ('lastname','firstname','middlename','generation',
15495:                   'permanentemail','id');
15496:     my @shibfields = (@fields,'inststatus');
15497:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
15498: #
15499: # Where usernames may created for institutional log-in and/or institutional single sign on:
15500: # (a) populate $cancreate{'statustocreate'} array reference with institutional status types who
15501: # may self-create accounts 
15502: # (b) populate $save_usermodify{'selfcreate'} hash reference with status types, and information fields
15503: # which the user may supply, if institutional data is unavailable.
15504: #
15505:     if (($env{'form.cancreate_login'}) || ($env{'form.cancreate_sso'})) {
15506:         if (@types) {
15507:             @{$cancreate{'statustocreate'}} = &Apache::loncommon::get_env_multiple('form.statustocreate');
15508:             push(@contexts,'statustocreate');
15509:             foreach my $type (@types) {
15510:                 my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$type);
15511:                 foreach my $field (@fields) {
15512:                     if (grep(/^\Q$field\E$/,@modifiable)) {
15513:                         $save_usermodify{'selfcreate'}{$type}{$field} = 1;
15514:                     } else {
15515:                         $save_usermodify{'selfcreate'}{$type}{$field} = 0;
15516:                     }
15517:                 }
15518:             }
15519:             if (ref($curr_usermodify{'selfcreate'}) eq 'HASH') {
15520:                 foreach my $type (@types) {
15521:                     if (ref($curr_usermodify{'selfcreate'}{$type}) eq 'HASH') {
15522:                         foreach my $field (@fields) {
15523:                             if ($save_usermodify{'selfcreate'}{$type}{$field} ne
15524:                                 $curr_usermodify{'selfcreate'}{$type}{$field}) {
15525:                                 push(@{$changes{'selfcreate'}},$type);
15526:                                 last;
15527:                             }
15528:                         }
15529:                     }
15530:                 }
15531:             } else {
15532:                 foreach my $type (@types) {
15533:                     push(@{$changes{'selfcreate'}},$type);
15534:                 }
15535:             }
15536:         }
15537:         foreach my $field (@shibfields) {
15538:             if ($env{'form.shibenv_'.$field} ne '') {
15539:                 $cancreate{'shibenv'}{$field} = $env{'form.shibenv_'.$field};
15540:             }
15541:         }
15542:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
15543:             if (ref($curr_usercreation{'cancreate'}{'shibenv'}) eq 'HASH') {
15544:                 foreach my $field (@shibfields) {
15545:                     if ($env{'form.shibenv_'.$field} ne $curr_usercreation{'cancreate'}{'shibenv'}{$field}) {
15546:                         push(@{$changes{'cancreate'}},'shibenv');
15547:                     }
15548:                 }
15549:             } else {
15550:                 foreach my $field (@shibfields) {
15551:                     if ($env{'form.shibenv_'.$field}) {
15552:                         push(@{$changes{'cancreate'}},'shibenv');
15553:                         last;
15554:                     }
15555:                 }
15556:             }
15557:         }
15558:     }
15559:     foreach my $item (@contexts) {
15560:         if (ref($curr_usercreation{'cancreate'}{$item}) eq 'ARRAY') {
15561:             foreach my $curr (@{$curr_usercreation{'cancreate'}{$item}}) {
15562:                 if (ref($cancreate{$item}) eq 'ARRAY') {
15563:                     if (!grep(/^$curr$/,@{$cancreate{$item}})) {
15564:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
15565:                             push(@{$changes{'cancreate'}},$item);
15566:                         }
15567:                     }
15568:                 }
15569:             }
15570:             if (ref($cancreate{$item}) eq 'ARRAY') {
15571:                 foreach my $type (@{$cancreate{$item}}) {
15572:                     if (!grep(/^$type$/,@{$curr_usercreation{'cancreate'}{$item}})) {
15573:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
15574:                             push(@{$changes{'cancreate'}},$item);
15575:                         }
15576:                     }
15577:                 }
15578:             }
15579:         } elsif (ref($curr_usercreation{'cancreate'}{$item}) eq 'HASH') {
15580:             if (ref($cancreate{$item}) eq 'HASH') {
15581:                 foreach my $type (keys(%{$curr_usercreation{'cancreate'}{$item}})) {
15582:                     if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
15583:                         foreach my $field (keys(%{$curr_usercreation{'cancreate'}{$item}{$type}})) {
15584:                             unless ($curr_usercreation{'cancreate'}{$item}{$type}{$field} eq $cancreate{$item}{$type}{$field}) {
15585:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
15586:                                     push(@{$changes{'cancreate'}},$item);
15587:                                 }
15588:                             }
15589:                         }
15590:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
15591:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
15592:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
15593:                                 push(@{$changes{'cancreate'}},$item);
15594:                             }
15595:                         }
15596:                     }
15597:                 }
15598:                 foreach my $type (keys(%{$cancreate{$item}})) {
15599:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
15600:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
15601:                             if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
15602:                                 unless ($curr_usercreation{'cancreate'}{$item}{$type}{$field} eq $cancreate{$item}{$type}{$field}) {
15603:                                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
15604:                                         push(@{$changes{'cancreate'}},$item);
15605:                                     }
15606:                                 }
15607:                             } else {
15608:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
15609:                                     push(@{$changes{'cancreate'}},$item);
15610:                                 }
15611:                             }
15612:                         }
15613:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
15614:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
15615:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
15616:                                 push(@{$changes{'cancreate'}},$item);
15617:                             }
15618:                         }
15619:                     }
15620:                 }
15621:             }
15622:         } elsif ($curr_usercreation{'cancreate'}{$item}) {
15623:             if (ref($cancreate{$item}) eq 'ARRAY') {
15624:                 if (!grep(/^\Q$curr_usercreation{'cancreate'}{$item}\E$/,@{$cancreate{$item}})) {
15625:                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
15626:                         push(@{$changes{'cancreate'}},$item);
15627:                     }
15628:                 }
15629:             }
15630:         } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
15631:             if (ref($cancreate{$item}) eq 'HASH') {
15632:                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
15633:                     push(@{$changes{'cancreate'}},$item);
15634:                 }
15635:             }
15636:         } elsif ($item eq 'emailusername') {
15637:             if (ref($cancreate{$item}) eq 'HASH') {
15638:                 foreach my $type (keys(%{$cancreate{$item}})) {
15639:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
15640:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
15641:                             if ($cancreate{$item}{$type}{$field}) {
15642:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
15643:                                     push(@{$changes{'cancreate'}},$item);
15644:                                 }
15645:                                 last;
15646:                             }
15647:                         }
15648:                     }
15649:                 }
15650:             }
15651:         }
15652:     }
15653: #
15654: # Populate %save_usercreate hash with updates to self-creation configuration.
15655: #
15656:     $save_usercreate{'cancreate'}{'captcha'} = $savecaptcha{'captcha'};
15657:     $save_usercreate{'cancreate'}{'recaptchakeys'} = $savecaptcha{'recaptchakeys'};
15658:     $save_usercreate{'cancreate'}{'recaptchaversion'} = $savecaptcha{'recaptchaversion'};
15659:     $save_usercreate{'cancreate'}{'selfcreate'} = $cancreate{'selfcreate'};
15660:     if (ref($cancreate{'notify'}) eq 'HASH') {
15661:         $save_usercreate{'cancreate'}{'notify'} = $cancreate{'notify'};
15662:     }
15663:     if (ref($cancreate{'selfcreateprocessing'}) eq 'HASH') {
15664:         $save_usercreate{'cancreate'}{'selfcreateprocessing'} = $cancreate{'selfcreateprocessing'};
15665:     }
15666:     if (ref($cancreate{'emailverified'}) eq 'HASH') {
15667:         $save_usercreate{'cancreate'}{'emailverified'} = $cancreate{'emailverified'};
15668:     }
15669:     if (ref($cancreate{'emailoptions'}) eq 'HASH') {
15670:         $save_usercreate{'cancreate'}{'emailoptions'} = $cancreate{'emailoptions'};
15671:     }
15672:     if (ref($cancreate{'emaildomain'}) eq 'HASH') {
15673:         $save_usercreate{'cancreate'}{'emaildomain'} = $cancreate{'emaildomain'};
15674:     }
15675:     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
15676:         $save_usercreate{'cancreate'}{'statustocreate'} = $cancreate{'statustocreate'};
15677:     }
15678:     if (ref($cancreate{'shibenv'}) eq 'HASH') {
15679:         $save_usercreate{'cancreate'}{'shibenv'} = $cancreate{'shibenv'};
15680:     }
15681:     $save_usercreate{'cancreate'}{'emailusername'} = $cancreate{'emailusername'};
15682:     $save_usercreate{'email_rule'} = \%email_rule;
15683: 
15684:     my %userconfig_hash = (
15685:             usercreation     => \%save_usercreate,
15686:             usermodification => \%save_usermodify,
15687:             inststatus       => \%save_inststatus,
15688:     );
15689: 
15690:     my $putresult = &Apache::lonnet::put_dom('configuration',\%userconfig_hash,
15691:                                              $dom);
15692: #
15693: # Accumulate details of changes to domain configuration for self-creation of usernames in $resulttext
15694: #
15695:     if ($putresult eq 'ok') {
15696:         if (keys(%changes) > 0) {
15697:             $resulttext = &mt('Changes made:').'<ul>';
15698:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
15699:                 my %lt = &selfcreation_types();
15700:                 foreach my $type (@{$changes{'cancreate'}}) {
15701:                     my $chgtext = '';
15702:                     if ($type eq 'selfcreate') {
15703:                         if (@{$cancreate{$type}} == 0) {
15704:                             $chgtext .= &mt('Self creation of a new user account is not permitted.');
15705:                         } else {
15706:                             $chgtext .= &mt('Self-creation of a new account is permitted for:').
15707:                                         '<ul>';
15708:                             foreach my $case (@{$cancreate{$type}}) {
15709:                                 $chgtext .= '<li>'.$selfcreatetypes{$case}.'</li>';
15710:                             }
15711:                             $chgtext .= '</ul>';
15712:                             if (ref($cancreate{$type}) eq 'ARRAY') {
15713:                                 if (grep(/^(login|sso)$/,@{$cancreate{$type}})) {
15714:                                     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
15715:                                         if (@{$cancreate{'statustocreate'}} == 0) {
15716:                                             $chgtext .= '<span class="LC_warning">'.
15717:                                                         &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts via log-in or single sign-on.").
15718:                                                         '</span><br />';
15719:                                         }
15720:                                     }
15721:                                 }
15722:                                 if (grep(/^email$/,@{$cancreate{$type}})) {
15723:                                     if (!@statuses) {
15724:                                         $chgtext .= '<span class="LC_warning">'.
15725:                                                     &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.").
15726:                                                     '</span><br />';
15727: 
15728:                                     }
15729:                                 }
15730:                             }
15731:                         }
15732:                     } elsif ($type eq 'shibenv') {
15733:                         if (keys(%{$cancreate{$type}}) == 0) {
15734:                             $chgtext .= &mt('Shibboleth-autheticated user does not use environment variables to set user information').'<br />'; 
15735:                         } else {
15736:                             $chgtext .= &mt('Shibboleth-autheticated user information set from environment variables, as follows:').
15737:                                         '<ul>';
15738:                             foreach my $field (@shibfields) {
15739:                                 next if ($cancreate{$type}{$field} eq '');
15740:                                 if ($field eq 'inststatus') {
15741:                                     $chgtext .= '<li>'.&mt('Institutional status').' -- '.$cancreate{$type}{$field}.'</li>';
15742:                                 } else {
15743:                                     $chgtext .= '<li>'.$fieldtitles{$field}.' -- '.$cancreate{$type}{$field}.'</li>';
15744:                                 }
15745:                             }
15746:                             $chgtext .= '</ul>';
15747:                         }
15748:                     } elsif ($type eq 'statustocreate') {
15749:                         if ((ref($cancreate{'selfcreate'}) eq 'ARRAY') &&
15750:                             (ref($cancreate{'statustocreate'}) eq 'ARRAY')) {
15751:                             if (@{$cancreate{'selfcreate'}} > 0) {
15752:                                 if (@{$cancreate{'statustocreate'}} == 0) {
15753:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts set to 'None'.");
15754:                                     if (!grep(/^email$/,@{$cancreate{'selfcreate'}})) {
15755:                                         $chgtext .= '<br />'.
15756:                                                     '<span class="LC_warning">'.
15757:                                                     &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts.").
15758:                                                     '</span>';
15759:                                     }
15760:                                 } elsif (keys(%usertypes) > 0) {
15761:                                     if (grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
15762:                                         $chgtext .= &mt('Creation of a new account for an institutional user is restricted to the following institutional affiliation(s):');
15763:                                     } else {
15764:                                         $chgtext .= &mt('Institutional affiliations permitted to create accounts with institutional authentication were set as follows:');
15765:                                     }
15766:                                     $chgtext .= '<ul>';
15767:                                     foreach my $case (@{$cancreate{$type}}) {
15768:                                         if ($case eq 'default') {
15769:                                             $chgtext .= '<li>'.$othertitle.'</li>';
15770:                                         } else {
15771:                                             $chgtext .= '<li>'.$usertypes{$case}.'</li>';
15772:                                         }
15773:                                     }
15774:                                     $chgtext .= '</ul>';
15775:                                     if (!grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
15776:                                         $chgtext .= '<span class="LC_warning">'.
15777:                                                     &mt('However, users authenticated by institutional login/single sign on are not currently permitted to create accounts.').
15778:                                                     '</span>';
15779:                                     }
15780:                                 }
15781:                             } else {
15782:                                 if (@{$cancreate{$type}} == 0) {
15783:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts were set to 'none'.");
15784:                                 } else {
15785:                                     $chgtext .= &mt('Although institutional affiliations permitted to create accounts were changed, self creation of accounts is not currently permitted for any authentication types.');
15786:                                 }
15787:                             }
15788:                             $chgtext .= '<br />';
15789:                         }
15790:                     } elsif ($type eq 'selfcreateprocessing') {
15791:                         my %choices = &Apache::lonlocal::texthash (
15792:                                                                     automatic => 'Automatic approval',
15793:                                                                     approval  => 'Queued for approval',
15794:                                                                   );
15795:                         if (@types) {
15796:                             if (@statuses) {
15797:                                 $chgtext .= &mt('Processing of requests to create account with e-mail verification set as follows:').
15798:                                             '<ul>';
15799:                                 foreach my $status (@statuses) {
15800:                                     if ($status eq 'default') {
15801:                                         $chgtext .= '<li>'.$othertitle.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
15802:                                     } else {
15803:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
15804:                                     }
15805:                                 }
15806:                                 $chgtext .= '</ul>';
15807:                             }
15808:                         } else {
15809:                             $chgtext .= &mt('Processing of requests to create account with e-mail verification set to: "[_1]"',
15810:                                             $choices{$cancreate{'selfcreateprocessing'}{'default'}});
15811:                         }
15812:                     } elsif ($type eq 'emailverified') {
15813:                         my %options = &Apache::lonlocal::texthash (
15814:                                                                     all   => 'Same as e-mail',
15815:                                                                     first => 'Omit @domain',
15816:                                                                     free  => 'Free to choose',
15817:                                                                   );
15818:                         if (@types) {
15819:                             if (@statuses) {
15820:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, username is set as follows:').
15821:                                             '<ul>';
15822:                                 foreach my $status (@statuses) {
15823:                                     if ($status eq 'default') {
15824:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
15825:                                     } else {
15826:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
15827:                                     }
15828:                                 }
15829:                                 $chgtext .= '</ul>';
15830:                             }
15831:                         } else {
15832:                             $chgtext .= &mt("For self-created accounts verified by e-mail address, user's username is: '[_1]'",
15833:                                             $options{$cancreate{'emailverified'}{'default'}});
15834:                         }
15835:                     } elsif ($type eq 'emailoptions') {
15836:                         my %options = &Apache::lonlocal::texthash (
15837:                                                                     any     => 'Any e-mail',
15838:                                                                     inst    => 'Institutional only',
15839:                                                                     noninst => 'Non-institutional only',
15840:                                                                     custom  => 'Custom restrictions',
15841:                                                                   );
15842:                         if (@types) {
15843:                             if (@statuses) {
15844:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, requirements for e-mail address are as follows:').
15845:                                             '<ul>';
15846:                                 foreach my $status (@statuses) {
15847:                                     if ($type eq 'default') {
15848:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
15849:                                     } else {
15850:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
15851:                                     }
15852:                                 }
15853:                                 $chgtext .= '</ul>';
15854:                             }
15855:                         } else {
15856:                             if ($cancreate{'emailoptions'}{'default'} eq 'any') {
15857:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, any e-mail may be used');
15858:                             } else {
15859:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, e-mail restricted to: "[_1]"',
15860:                                                 $options{$cancreate{'emailoptions'}{'default'}});
15861:                             }
15862:                         }
15863:                     } elsif ($type eq 'emaildomain') {
15864:                         my $output;
15865:                         if (@statuses) {
15866:                             foreach my $type (@statuses) {
15867:                                 if (ref($cancreate{'emaildomain'}{$type}) eq 'HASH') {
15868:                                     if ($cancreate{'emailoptions'}{$type} eq 'inst') {
15869:                                         if ($type eq 'default') {
15870:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
15871:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} eq '')) {
15872:                                                 $output = '<li>'.$othertitle.' -- '.&mt('No restriction on e-mail domain').'</li>';
15873:                                             } else {
15874:                                                 $output = '<li>'.$othertitle.' -- '.&mt("User's e-mail address needs to end: [_1]",
15875:                                                                                         $cancreate{'emaildomain'}{$type}{'inst'}).'</li>';
15876:                                             }
15877:                                         } else {
15878:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
15879:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} eq '')) {
15880:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
15881:                                             } else {
15882:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address needs to end: [_1]",
15883:                                                                                               $cancreate{'emaildomain'}{$type}{'inst'}).'</li>';
15884:                                             }
15885:                                         }
15886:                                     } elsif ($cancreate{'emailoptions'}{$type} eq 'noninst') {
15887:                                         if ($type eq 'default') {
15888:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
15889:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
15890:                                                 $output = '<li>'.$othertitle.' -- '.&mt('No restriction on e-mail domain').'</li>';
15891:                                             } else {
15892:                                                 $output = '<li>'.$othertitle.' -- '.&mt("User's e-mail address must not end: [_1]",
15893:                                                                                         $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';
15894:                                             }
15895:                                         } else {
15896:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
15897:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
15898:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
15899:                                             } else {
15900:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address must not end: [_1]",
15901:                                                                                                 $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';
15902:                                             }
15903:                                         }
15904:                                     }
15905:                                 }
15906:                             }
15907:                         }
15908:                         if ($output ne '') {
15909:                             $chgtext .= &mt('For self-created accounts verified by e-mail address:').
15910:                                         '<ul>'.$output.'</ul>';
15911:                         }
15912:                     } elsif ($type eq 'captcha') {
15913:                         if ($savecaptcha{$type} eq 'notused') {
15914:                             $chgtext .= &mt('No CAPTCHA validation in use for self-creation screen.');
15915:                         } else {
15916:                             my %captchas = &captcha_phrases();
15917:                             if ($captchas{$savecaptcha{$type}}) {
15918:                                 $chgtext .= &mt("Validation for self-creation screen set to $captchas{$savecaptcha{$type}}.");
15919:                             } else {
15920:                                 $chgtext .= &mt('Validation for self-creation screen set to unknown type.');
15921:                             }
15922:                         }
15923:                     } elsif ($type eq 'recaptchakeys') {
15924:                         my ($privkey,$pubkey);
15925:                         if (ref($savecaptcha{$type}) eq 'HASH') {
15926:                             $pubkey = $savecaptcha{$type}{'public'};
15927:                             $privkey = $savecaptcha{$type}{'private'};
15928:                         }
15929:                         $chgtext .= &mt('ReCAPTCHA keys changes').'<ul>';
15930:                         if (!$pubkey) {
15931:                             $chgtext .= '<li>'.&mt('Public key deleted').'</li>';
15932:                         } else {
15933:                             $chgtext .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
15934:                         }
15935:                         if (!$privkey) {
15936:                             $chgtext .= '<li>'.&mt('Private key deleted').'</li>';
15937:                         } else {
15938:                             $chgtext .= '<li>'.&mt('Private key set to [_1]',$pubkey).'</li>';
15939:                         }
15940:                         $chgtext .= '</ul>';
15941:                     } elsif ($type eq 'recaptchaversion') {
15942:                         if ($savecaptcha{'captcha'} eq 'recaptcha') {
15943:                             $chgtext .= &mt('ReCAPTCHA set to version [_1]',$savecaptcha{$type});
15944:                         }
15945:                     } elsif ($type eq 'emailusername') {
15946:                         if (ref($cancreate{'emailusername'}) eq 'HASH') {
15947:                             if (@statuses) {
15948:                                 foreach my $type (@statuses) {
15949:                                     if (ref($cancreate{'emailusername'}{$type}) eq 'HASH') {
15950:                                         if (keys(%{$cancreate{'emailusername'}{$type}}) > 0) {
15951:                                             $chgtext .= &mt('When self-creating account with e-mail verification, the following information will be provided by [_1]:',"'$usertypes{$type}'").
15952:                                                     '<ul>';
15953:                                             foreach my $field (@{$infofields}) {
15954:                                                 if ($cancreate{'emailusername'}{$type}{$field}) {
15955:                                                     $chgtext .= '<li>'.$infotitles->{$field}.'</li>';
15956:                                                 }
15957:                                             }
15958:                                             $chgtext .= '</ul>';
15959:                                         } else {
15960:                                             $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
15961:                                         }
15962:                                     } else {
15963:                                         $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
15964:                                     }
15965:                                 }
15966:                             }
15967:                         }
15968:                     } elsif ($type eq 'notify') {
15969:                         my $numapprove = 0;
15970:                         if (ref($changes{'cancreate'}) eq 'ARRAY') {
15971:                             if ((grep(/^notify$/,@{$changes{'cancreate'}})) && (ref($cancreate{'notify'}) eq 'HASH')) {
15972:                                 if ($cancreate{'notify'}{'approval'}) {
15973:                                     $chgtext .= &mt('Notification of username requests requiring approval will be sent to: ').$cancreate{'notify'}{'approval'};
15974:                                     $numapprove ++;
15975:                                 }
15976:                             }
15977:                         }
15978:                         unless ($numapprove) {
15979:                             $chgtext .= &mt('No Domain Coordinators will receive notification of username requests requiring approval.');
15980:                         }
15981:                     }
15982:                     if ($chgtext) {
15983:                         $resulttext .= '<li>'.$chgtext.'</li>';
15984:                     }
15985:                 }
15986:             }
15987:             if ((ref($changes{'email_rule'}) eq 'ARRAY') && (@{$changes{'email_rule'}} > 0)) {
15988:                 my ($emailrules,$emailruleorder) =
15989:                     &Apache::lonnet::inst_userrules($dom,'email');
15990:                 foreach my $type (@{$changes{'email_rule'}}) {
15991:                     if (ref($email_rule{$type}) eq 'ARRAY') {
15992:                         my $chgtext = '<ul>';
15993:                         foreach my $rule (@{$email_rule{$type}}) {
15994:                             if (ref($emailrules->{$rule}) eq 'HASH') {
15995:                                 $chgtext .= '<li>'.$emailrules->{$rule}{'name'}.'</li>';
15996:                             }
15997:                         }
15998:                         $chgtext .= '</ul>';
15999:                         my $typename;
16000:                         if (@types) {
16001:                             if ($type eq 'default') {
16002:                                 $typename = $othertitle;
16003:                             } else {
16004:                                 $typename = $usertypes{$type};
16005:                             }
16006:                             $chgtext .= &mt('(Affiliation: [_1])',$typename);
16007:                         }
16008:                         if (@{$email_rule{$type}} > 0) {
16009:                             $resulttext .= '<li>'.
16010:                                            &mt('Accounts may not be created by users verified by e-mail, for e-mail addresses of the following types: ',
16011:                                                $usertypes{$type}).
16012:                                            $chgtext.
16013:                                            '</li>';
16014:                         } else {
16015:                             $resulttext .= '<li>'.
16016:                                            &mt('There are now no restrictions on e-mail addresses which may be used for verification when a user requests an account.').
16017:                                            '</li>'.
16018:                                            &mt('(Affiliation: [_1])',$typename);
16019:                         }
16020:                     }
16021:                 }
16022:             }
16023:             if (ref($changes{'inststatus'}) eq 'ARRAY') {
16024:                 if (ref($save_inststatus{'inststatusguest'}) eq 'ARRAY') {
16025:                     if (@{$save_inststatus{'inststatusguest'}} > 0) {
16026:                         my $chgtext = '<ul>';
16027:                         foreach my $type (@{$save_inststatus{'inststatusguest'}}) {
16028:                             $chgtext .= '<li>'.$usertypes{$type}.'</li>';
16029:                         }
16030:                         $chgtext .= '</ul>';
16031:                         $resulttext .= '<li>'.
16032:                                        &mt('A user will self-report one of the following affiliations when requesting an account verified by e-mail: ').
16033:                                           $chgtext.
16034:                                        '</li>';
16035:                     } else {
16036:                         $resulttext .= '<li>'.
16037:                                        &mt('No affiliations available for self-reporting when requesting an account verified by e-mail.').
16038:                                        '</li>';
16039:                     }
16040:                 }
16041:             }
16042:             if (ref($changes{'selfcreate'}) eq 'ARRAY') {
16043:                 $resulttext .= '<li>'.&mt('When self-creating institutional account:').'<ul>';
16044:                 my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
16045:                 foreach my $type (@{$changes{'selfcreate'}}) {
16046:                     my $typename = $type;
16047:                     if (keys(%usertypes) > 0) {
16048:                         if ($usertypes{$type} ne '') {
16049:                             $typename = $usertypes{$type};
16050:                         }
16051:                     }
16052:                     my @modifiable;
16053:                     $resulttext .= '<li>'.
16054:                                     &mt('Self-creation of account by users with status: [_1]',
16055:                                         '<span class="LC_cusr_emph">'.$typename.'</span>').
16056:                                     ' - '.&mt('modifiable fields (if institutional data blank): ');
16057:                     foreach my $field (@fields) {
16058:                         if ($save_usermodify{'selfcreate'}{$type}{$field}) {
16059:                             push(@modifiable,'<b>'.$fieldtitles{$field}.'</b>');
16060:                         }
16061:                     }
16062:                     if (@modifiable > 0) {
16063:                         $resulttext .= join(', ',@modifiable);
16064:                     } else {
16065:                         $resulttext .= &mt('none');
16066:                     }
16067:                     $resulttext .= '</li>';
16068:                 }
16069:                 $resulttext .= '</ul></li>';
16070:             }
16071:             $resulttext .= '</ul>';
16072:             my $cachetime = 24*60*60;
16073:             $domdefaults{'inststatusguest'} = $save_inststatus{'inststatusguest'};
16074:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
16075:             if (ref($lastactref) eq 'HASH') {
16076:                 $lastactref->{'domdefaults'} = 1;
16077:             }
16078:         } else {
16079:             $resulttext = &mt('No changes made to self-creation settings');
16080:         }
16081:     } else {
16082:         $resulttext = '<span class="LC_error">'.
16083:             &mt('An error occurred: [_1]',$putresult).'</span>';
16084:     }
16085:     if ($warningmsg ne '') {
16086:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
16087:     }
16088:     return $resulttext;
16089: }
16090: 
16091: sub process_captcha {
16092:     my ($container,$changes,$newsettings,$currsettings) = @_;
16093:     return unless ((ref($changes) eq 'HASH') && (ref($newsettings) eq 'HASH'));
16094:     $newsettings->{'captcha'} = $env{'form.'.$container.'_captcha'};
16095:     unless ($newsettings->{'captcha'} eq 'recaptcha' || $newsettings->{'captcha'} eq 'notused') {
16096:         $newsettings->{'captcha'} = 'original';
16097:     }
16098:     my %current;
16099:     if (ref($currsettings) eq 'HASH') {
16100:         %current = %{$currsettings};
16101:     }
16102:     if ($current{'captcha'} ne $newsettings->{'captcha'}) {
16103:         if ($container eq 'cancreate') {
16104:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
16105:                 push(@{$changes->{'cancreate'}},'captcha');
16106:             } elsif (!defined($changes->{'cancreate'})) {
16107:                 $changes->{'cancreate'} = ['captcha'];
16108:             }
16109:         } elsif ($container eq 'passwords') {
16110:             $changes->{'reset'} = 1;
16111:         } else {
16112:             $changes->{'captcha'} = 1;
16113:         }
16114:     }
16115:     my ($newpub,$newpriv,$currpub,$currpriv,$newversion,$currversion);
16116:     if ($newsettings->{'captcha'} eq 'recaptcha') {
16117:         $newpub = $env{'form.'.$container.'_recaptchapub'};
16118:         $newpriv = $env{'form.'.$container.'_recaptchapriv'};
16119:         $newpub =~ s/[^\w\-]//g;
16120:         $newpriv =~ s/[^\w\-]//g;
16121:         $newsettings->{'recaptchakeys'} = {
16122:                                              public  => $newpub,
16123:                                              private => $newpriv,
16124:                                           };
16125:         $newversion = $env{'form.'.$container.'_recaptchaversion'};
16126:         $newversion =~ s/\D//g;
16127:         if ($newversion ne '2') {
16128:             $newversion = 1;
16129:         }
16130:         $newsettings->{'recaptchaversion'} = $newversion;
16131:     }
16132:     if (ref($current{'recaptchakeys'}) eq 'HASH') {
16133:         $currpub = $current{'recaptchakeys'}{'public'};
16134:         $currpriv = $current{'recaptchakeys'}{'private'};
16135:         unless ($newsettings->{'captcha'} eq 'recaptcha') {
16136:             $newsettings->{'recaptchakeys'} = {
16137:                                                  public  => '',
16138:                                                  private => '',
16139:                                               }
16140:         }
16141:     }
16142:     if ($current{'captcha'} eq 'recaptcha') {
16143:         $currversion = $current{'recaptchaversion'};
16144:         if ($currversion ne '2') {
16145:             $currversion = 1;
16146:         }
16147:     }
16148:     if ($currversion ne $newversion) {
16149:         if ($container eq 'cancreate') {
16150:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
16151:                 push(@{$changes->{'cancreate'}},'recaptchaversion');
16152:             } elsif (!defined($changes->{'cancreate'})) {
16153:                 $changes->{'cancreate'} = ['recaptchaversion'];
16154:             }
16155:         } elsif ($container eq 'passwords') {
16156:             $changes->{'reset'} = 1;
16157:         } else {
16158:             $changes->{'recaptchaversion'} = 1;
16159:         }
16160:     }
16161:     if (($newpub ne $currpub) || ($newpriv ne $currpriv)) {
16162:         if ($container eq 'cancreate') {
16163:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
16164:                 push(@{$changes->{'cancreate'}},'recaptchakeys');
16165:             } elsif (!defined($changes->{'cancreate'})) {
16166:                 $changes->{'cancreate'} = ['recaptchakeys'];
16167:             }
16168:         } elsif ($container eq 'passwords') {
16169:             $changes->{'reset'} = 1;
16170:         } else {
16171:             $changes->{'recaptchakeys'} = 1;
16172:         }
16173:     }
16174:     return;
16175: }
16176: 
16177: sub modify_usermodification {
16178:     my ($dom,%domconfig) = @_;
16179:     my ($resulttext,%curr_usermodification,%changes,%modifyhash);
16180:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
16181:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
16182:             if ($key eq 'selfcreate') {
16183:                 $modifyhash{$key} = $domconfig{'usermodification'}{$key};
16184:             } else {  
16185:                 $curr_usermodification{$key} = $domconfig{'usermodification'}{$key};
16186:             }
16187:         }
16188:     }
16189:     my @contexts = ('author','course');
16190:     my %context_title = (
16191:                            author => 'In author context',
16192:                            course => 'In course context',
16193:                         );
16194:     my @fields = ('lastname','firstname','middlename','generation',
16195:                   'permanentemail','id');
16196:     my %roles = (
16197:                   author => ['ca','aa'],
16198:                   course => ['st','ep','ta','in','cr'],
16199:                 );
16200:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
16201:     foreach my $context (@contexts) {
16202:         foreach my $role (@{$roles{$context}}) {
16203:             my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$role);
16204:             foreach my $item (@fields) {
16205:                 if (grep(/^\Q$item\E$/,@modifiable)) {
16206:                     $modifyhash{$context}{$role}{$item} = 1;
16207:                 } else {
16208:                     $modifyhash{$context}{$role}{$item} = 0;
16209:                 }
16210:             }
16211:         }
16212:         if (ref($curr_usermodification{$context}) eq 'HASH') {
16213:             foreach my $role (@{$roles{$context}}) {
16214:                 if (ref($curr_usermodification{$context}{$role}) eq 'HASH') {
16215:                     foreach my $field (@fields) {
16216:                         if ($modifyhash{$context}{$role}{$field} ne 
16217:                                 $curr_usermodification{$context}{$role}{$field}) {
16218:                             push(@{$changes{$context}},$role);
16219:                             last;
16220:                         }
16221:                     }
16222:                 }
16223:             }
16224:         } else {
16225:             foreach my $context (@contexts) {
16226:                 foreach my $role (@{$roles{$context}}) {
16227:                     push(@{$changes{$context}},$role);
16228:                 }
16229:             }
16230:         }
16231:     }
16232:     my %usermodification_hash =  (
16233:                                    usermodification => \%modifyhash,
16234:                                  );
16235:     my $putresult = &Apache::lonnet::put_dom('configuration',
16236:                                              \%usermodification_hash,$dom);
16237:     if ($putresult eq 'ok') {
16238:         if (keys(%changes) > 0) {
16239:             $resulttext = &mt('Changes made: ').'<ul>';
16240:             foreach my $context (@contexts) {
16241:                 if (ref($changes{$context}) eq 'ARRAY') {
16242:                     $resulttext .= '<li>'.$context_title{$context}.':<ul>';
16243:                     if (ref($changes{$context}) eq 'ARRAY') {
16244:                         foreach my $role (@{$changes{$context}}) {
16245:                             my $rolename;
16246:                             if ($role eq 'cr') {
16247:                                 $rolename = &mt('Custom');
16248:                             } else {
16249:                                 $rolename = &Apache::lonnet::plaintext($role);
16250:                             }
16251:                             my @modifiable;
16252:                             $resulttext .= '<li><span class="LC_cusr_emph">'.&mt('Target user with [_1] role',$rolename).'</span> - '.&mt('modifiable fields: ');
16253:                             foreach my $field (@fields) {
16254:                                 if ($modifyhash{$context}{$role}{$field}) {
16255:                                     push(@modifiable,$fieldtitles{$field});
16256:                                 }
16257:                             }
16258:                             if (@modifiable > 0) {
16259:                                 $resulttext .= join(', ',@modifiable);
16260:                             } else {
16261:                                 $resulttext .= &mt('none'); 
16262:                             }
16263:                             $resulttext .= '</li>';
16264:                         }
16265:                         $resulttext .= '</ul></li>';
16266:                     }
16267:                 }
16268:             }
16269:             $resulttext .= '</ul>';
16270:         } else {
16271:             $resulttext = &mt('No changes made to user modification settings');
16272:         }
16273:     } else {
16274:         $resulttext = '<span class="LC_error">'.
16275:             &mt('An error occurred: [_1]',$putresult).'</span>';
16276:     }
16277:     return $resulttext;
16278: }
16279: 
16280: sub modify_defaults {
16281:     my ($dom,$lastactref,%domconfig) = @_;
16282:     my ($resulttext,$mailmsgtxt,%newvalues,%changes,@errors);
16283:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
16284:     my @items = ('auth_def','auth_arg_def','lang_def','timezone_def','datelocale_def',
16285:                  'portal_def');
16286:     my @authtypes = ('internal','krb4','krb5','localauth');
16287:     foreach my $item (@items) {
16288:         $newvalues{$item} = $env{'form.'.$item};
16289:         if ($item eq 'auth_def') {
16290:             if ($newvalues{$item} ne '') {
16291:                 if (!grep(/^\Q$newvalues{$item}\E$/,@authtypes)) {
16292:                     push(@errors,$item);
16293:                 }
16294:             }
16295:         } elsif ($item eq 'lang_def') {
16296:             if ($newvalues{$item} ne '') {
16297:                 if ($newvalues{$item} =~ /^(\w+)/) {
16298:                     my $langcode = $1;
16299:                     if ($langcode ne 'x_chef') {
16300:                         if (code2language($langcode) eq '') {
16301:                             push(@errors,$item);
16302:                         }
16303:                     }
16304:                 } else {
16305:                     push(@errors,$item);
16306:                 }
16307:             }
16308:         } elsif ($item eq 'timezone_def') {
16309:             if ($newvalues{$item} ne '') {
16310:                 if (!DateTime::TimeZone->is_valid_name($newvalues{$item})) {
16311:                     push(@errors,$item);   
16312:                 }
16313:             }
16314:         } elsif ($item eq 'datelocale_def') {
16315:             if ($newvalues{$item} ne '') {
16316:                 my @datelocale_ids = DateTime::Locale->ids();
16317:                 if (!grep(/^\Q$newvalues{$item}\E$/,@datelocale_ids)) {
16318:                     push(@errors,$item);
16319:                 }
16320:             }
16321:         } elsif ($item eq 'portal_def') {
16322:             if ($newvalues{$item} ne '') {
16323:                 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])\/?$/) {
16324:                     push(@errors,$item);
16325:                 }
16326:             }
16327:         }
16328:         if (grep(/^\Q$item\E$/,@errors)) {
16329:             $newvalues{$item} = $domdefaults{$item};
16330:         } elsif ($domdefaults{$item} ne $newvalues{$item}) {
16331:             $changes{$item} = 1;
16332:         }
16333:         $domdefaults{$item} = $newvalues{$item};
16334:     }
16335:     my %staticdefaults = (
16336:                            'intauth_cost'   => 10,
16337:                            'intauth_check'  => 0,
16338:                            'intauth_switch' => 0,
16339:                          );
16340:     foreach my $item ('intauth_cost','intauth_check','intauth_switch') {
16341:         if (exists($domdefaults{$item})) {
16342:             $newvalues{$item} = $domdefaults{$item};
16343:         } else {
16344:             $newvalues{$item} = $staticdefaults{$item};
16345:         }
16346:     }
16347:     my %defaults_hash = (
16348:                          defaults => \%newvalues,
16349:                         );
16350:     my $title = &defaults_titles();
16351: 
16352:     my $currinststatus;
16353:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
16354:         $currinststatus = $domconfig{'inststatus'};
16355:     } else {
16356:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
16357:         $currinststatus = {
16358:                              inststatustypes => $usertypes,
16359:                              inststatusorder => $types,
16360:                              inststatusguest => [],
16361:                           };
16362:     }
16363:     my @todelete = &Apache::loncommon::get_env_multiple('form.inststatus_delete');
16364:     my @allpos;
16365:     my %alltypes;
16366:     my @inststatusguest;
16367:     if (ref($currinststatus) eq 'HASH') {
16368:         if (ref($currinststatus->{'inststatusguest'}) eq 'ARRAY') {
16369:             foreach my $type (@{$currinststatus->{'inststatusguest'}}) {
16370:                 unless (grep(/^\Q$type\E$/,@todelete)) {
16371:                     push(@inststatusguest,$type);
16372:                 }
16373:             }
16374:         }
16375:     }
16376:     my ($currtitles,$currorder);
16377:     if (ref($currinststatus) eq 'HASH') {
16378:         if (ref($currinststatus->{'inststatusorder'}) eq 'ARRAY') {
16379:             foreach my $type (@{$currinststatus->{'inststatusorder'}}) {
16380:                 if (ref($currinststatus->{inststatustypes}) eq 'HASH') {
16381:                     if ($currinststatus->{inststatustypes}->{$type} ne '') {
16382:                         $currtitles .= $currinststatus->{inststatustypes}->{$type}.',';
16383:                     }
16384:                 }
16385:                 unless (grep(/^\Q$type\E$/,@todelete)) { 
16386:                     my $position = $env{'form.inststatus_pos_'.$type};
16387:                     $position =~ s/\D+//g;
16388:                     $allpos[$position] = $type;
16389:                     $alltypes{$type} = $env{'form.inststatus_title_'.$type};
16390:                     $alltypes{$type} =~ s/`//g;
16391:                 }
16392:             }
16393:             $currorder = join(',',@{$currinststatus->{'inststatusorder'}});
16394:             $currtitles =~ s/,$//;
16395:         }
16396:     }
16397:     if ($env{'form.addinststatus'}) {
16398:         my $newtype = $env{'form.addinststatus'};
16399:         $newtype =~ s/\W//g;
16400:         unless (exists($alltypes{$newtype})) {
16401:             $alltypes{$newtype} = $env{'form.addinststatus_title'};
16402:             $alltypes{$newtype} =~ s/`//g; 
16403:             my $position = $env{'form.addinststatus_pos'};
16404:             $position =~ s/\D+//g;
16405:             if ($position ne '') {
16406:                 $allpos[$position] = $newtype;
16407:             }
16408:         }
16409:     }
16410:     my @orderedstatus;
16411:     foreach my $type (@allpos) {
16412:         unless (($type eq '') || (grep(/^\Q$type\E$/,@orderedstatus))) {
16413:             push(@orderedstatus,$type);
16414:         }
16415:     }
16416:     foreach my $type (keys(%alltypes)) {
16417:         unless (grep(/^\Q$type\E$/,@orderedstatus)) {
16418:             delete($alltypes{$type});
16419:         }
16420:     }
16421:     $defaults_hash{'inststatus'} = {
16422:                                      inststatustypes => \%alltypes,
16423:                                      inststatusorder => \@orderedstatus,
16424:                                      inststatusguest => \@inststatusguest,
16425:                                    };
16426:     if (ref($defaults_hash{'inststatus'}) eq 'HASH') {
16427:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
16428:             $domdefaults{$item} = $defaults_hash{'inststatus'}{$item};
16429:         }
16430:     }
16431:     if ($currorder ne join(',',@orderedstatus)) {
16432:         $changes{'inststatus'}{'inststatusorder'} = 1;
16433:     }
16434:     my $newtitles;
16435:     foreach my $item (@orderedstatus) {
16436:         $newtitles .= $alltypes{$item}.',';
16437:     }
16438:     $newtitles =~ s/,$//;
16439:     if ($currtitles ne $newtitles) {
16440:         $changes{'inststatus'}{'inststatustypes'} = 1;
16441:     }
16442:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaults_hash,
16443:                                              $dom);
16444:     if ($putresult eq 'ok') {
16445:         if (keys(%changes) > 0) {
16446:             $resulttext = &mt('Changes made:').'<ul>';
16447:             my $version = &Apache::lonnet::get_server_loncaparev($dom);
16448:             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";
16449:             foreach my $item (sort(keys(%changes))) {
16450:                 if ($item eq 'inststatus') {
16451:                     if (ref($changes{'inststatus'}) eq 'HASH') {
16452:                         if (@orderedstatus) {
16453:                             $resulttext .= '<li>'.&mt('Institutional user status types set to:').' ';
16454:                             foreach my $type (@orderedstatus) { 
16455:                                 $resulttext .= $alltypes{$type}.', ';
16456:                             }
16457:                             $resulttext =~ s/, $//;
16458:                             $resulttext .= '</li>';
16459:                         } else {
16460:                             $resulttext .= '<li>'.&mt('Institutional user status types deleted').'</li>';
16461:                         }
16462:                     }
16463:                 } else {
16464:                     my $value = $env{'form.'.$item};
16465:                     if ($value eq '') {
16466:                         $value = &mt('none');
16467:                     } elsif ($item eq 'auth_def') {
16468:                         my %authnames = &authtype_names();
16469:                         my %shortauth = (
16470:                                           internal   => 'int',
16471:                                           krb4       => 'krb4',
16472:                                           krb5       => 'krb5',
16473:                                           localauth  => 'loc',
16474:                         );
16475:                         $value = $authnames{$shortauth{$value}};
16476:                     }
16477:                     $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$title->{$item},$value).'</li>';
16478:                     $mailmsgtext .= "$title->{$item} set to $value\n";  
16479:                 }
16480:             }
16481:             $resulttext .= '</ul>';
16482:             $mailmsgtext .= "\n";
16483:             my $cachetime = 24*60*60;
16484:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
16485:             if (ref($lastactref) eq 'HASH') {
16486:                 $lastactref->{'domdefaults'} = 1;
16487:             }
16488:             if ($changes{'auth_def'} || $changes{'auth_arg_def'} || $changes{'lang_def'} || $changes{'datelocale_def'}) {
16489:                 my $notify = 1;
16490:                 if (ref($domconfig{'contacts'}) eq 'HASH') {
16491:                     if ($domconfig{'contacts'}{'reportupdates'} == 0) {
16492:                         $notify = 0;
16493:                     }
16494:                 }
16495:                 if ($notify) {
16496:                     &Apache::lonmsg::sendemail('installrecord@loncapa.org',
16497:                                                "LON-CAPA Domain Settings Change - $dom",
16498:                                                $mailmsgtext);
16499:                 }
16500:             }
16501:         } else {
16502:             $resulttext = &mt('No changes made to default authentication/language/timezone settings');
16503:         }
16504:     } else {
16505:         $resulttext = '<span class="LC_error">'.
16506:             &mt('An error occurred: [_1]',$putresult).'</span>';
16507:     }
16508:     if (@errors > 0) {
16509:         $resulttext .= '<br />'.&mt('The following were left unchanged because the values entered were invalid:');
16510:         foreach my $item (@errors) {
16511:             $resulttext .= ' "'.$title->{$item}.'",';
16512:         }
16513:         $resulttext =~ s/,$//;
16514:     }
16515:     return $resulttext;
16516: }
16517: 
16518: sub modify_scantron {
16519:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
16520:     my ($resulttext,%confhash,%changes,$errors);
16521:     my $custom = 'custom.tab';
16522:     my $default = 'default.tab';
16523:     my $servadm = $r->dir_config('lonAdmEMail');
16524:     my ($configuserok,$author_ok,$switchserver) =
16525:         &config_check($dom,$confname,$servadm);
16526:     if ($env{'form.scantronformat.filename'} ne '') {
16527:         my $error;
16528:         if ($configuserok eq 'ok') {
16529:             if ($switchserver) {
16530:                 $error = &mt("Upload of bubblesheet format file is not permitted to this server: [_1]",$switchserver);
16531:             } else {
16532:                 if ($author_ok eq 'ok') {
16533:                     my ($result,$scantronurl) =
16534:                         &publishlogo($r,'upload','scantronformat',$dom,
16535:                                      $confname,'scantron','','',$custom);
16536:                     if ($result eq 'ok') {
16537:                         $confhash{'scantron'}{'scantronformat'} = $scantronurl;
16538:                         $changes{'scantronformat'} = 1;
16539:                     } else {
16540:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$custom,$result);
16541:                     }
16542:                 } else {
16543:                     $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);
16544:                 }
16545:             }
16546:         } else {
16547:             $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);
16548:         }
16549:         if ($error) {
16550:             &Apache::lonnet::logthis($error);
16551:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
16552:         }
16553:     }
16554:     if (ref($domconfig{'scantron'}) eq 'HASH') {
16555:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
16556:             if ($env{'form.scantronformat_del'}) {
16557:                 $confhash{'scantron'}{'scantronformat'} = '';
16558:                 $changes{'scantronformat'} = 1;
16559:             } else {
16560:                 $confhash{'scantron'}{'scantronformat'} = $domconfig{'scantron'}{'scantronformat'};
16561:             }
16562:         }
16563:     }
16564:     my @options = ('hdr','pad','rem');
16565:     my @fields = &scantroncsv_fields();
16566:     my %titles = &scantronconfig_titles();
16567:     my @formats = &Apache::loncommon::get_env_multiple('form.scantronconfig');
16568:     my ($newdat,$currdat,%newcol,%currcol);
16569:     if (grep(/^dat$/,@formats)) {
16570:         $confhash{'scantron'}{config}{dat} = 1;
16571:         $newdat = 1;
16572:     } else {
16573:         $newdat = 0;
16574:     }
16575:     if (grep(/^csv$/,@formats)) {
16576:         my %bynum;
16577:         foreach my $field (@fields) {
16578:             if ($env{'form.scantronconfig_csv_'.$field} =~ /^(\d+)$/) {
16579:                 my $posscol = $1;
16580:                 if (($posscol < 20) && (!$bynum{$posscol})) {
16581:                     $confhash{'scantron'}{config}{csv}{fields}{$field} = $posscol;
16582:                     $bynum{$posscol} = $field;
16583:                     $newcol{$field} = $posscol;
16584:                 }
16585:             }
16586:         }
16587:         if (keys(%newcol)) {
16588:             foreach my $option (@options) {
16589:                 if ($env{'form.scantroncsv_'.$option}) {
16590:                     $confhash{'scantron'}{config}{csv}{options}{$option} = 1;
16591:                 }
16592:             }
16593:         }
16594:     }
16595:     $currdat = 1;
16596:     if (ref($domconfig{'scantron'}) eq 'HASH') {
16597:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
16598:             unless (exists($domconfig{'scantron'}{'config'}{'dat'})) {
16599:                 $currdat = 0;
16600:             }
16601:             if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
16602:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
16603:                     %currcol = %{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}};
16604:                 }
16605:             }
16606:         }
16607:     }
16608:     if ($currdat != $newdat) {
16609:         $changes{'config'} = 1;
16610:     } else {
16611:         foreach my $field (@fields) {
16612:             if ($currcol{$field} ne '') {
16613:                 if ($currcol{$field} ne $newcol{$field}) {
16614:                     $changes{'config'} = 1;
16615:                     last;
16616:                 }
16617:             } elsif ($newcol{$field} ne '') {
16618:                 $changes{'config'} = 1;
16619:                 last;
16620:             }
16621:         }
16622:     }
16623:     if (keys(%confhash) > 0) {
16624:         my $putresult = &Apache::lonnet::put_dom('configuration',\%confhash,
16625:                                                  $dom);
16626:         if ($putresult eq 'ok') {
16627:             if (keys(%changes) > 0) {
16628:                 if (ref($confhash{'scantron'}) eq 'HASH') {
16629:                     $resulttext = &mt('Changes made:').'<ul>';
16630:                     if ($changes{'scantronformat'}) {
16631:                         if ($confhash{'scantron'}{'scantronformat'} eq '') {
16632:                             $resulttext .= '<li>'.&mt('[_1] bubblesheet format file removed; [_2] file will be used for courses in this domain.',$custom,$default).'</li>';
16633:                         } else {
16634:                             $resulttext .= '<li>'.&mt('Custom bubblesheet format file ([_1]) uploaded for use with courses in this domain.',$custom).'</li>';
16635:                         }
16636:                     }
16637:                     if ($changes{'config'}) {
16638:                         if (ref($confhash{'scantron'}{'config'}) eq 'HASH') {
16639:                             if ($confhash{'scantron'}{'config'}{'dat'}) {
16640:                                 $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .dat format').'</li>';
16641:                             }
16642:                             if (ref($confhash{'scantron'}{'config'}{'csv'}) eq 'HASH') {
16643:                                 if (ref($confhash{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
16644:                                     if (keys(%{$confhash{'scantron'}{'config'}{'csv'}{'fields'}})) {
16645:                                         $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .csv format, with following fields/column numbers supported:').'<ul>';
16646:                                         foreach my $field (@fields) {
16647:                                             if ($confhash{'scantron'}{'config'}{'csv'}{'fields'}{$field} ne '') {
16648:                                                 my $showcol = $confhash{'scantron'}{'config'}{'csv'}{'fields'}{$field} + 1;
16649:                                                 $resulttext .= '<li>'.$titles{$field}.': '.$showcol.'</li>';
16650:                                             }
16651:                                         }
16652:                                         $resulttext .= '</ul></li>';
16653:                                         if (ref($confhash{'scantron'}{'config'}{'csv'}{'options'}) eq 'HASH') {
16654:                                             if (keys(%{$confhash{'scantron'}{'config'}{'csv'}{'options'}})) {
16655:                                                 $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .csv format, with following options:').'<ul>';
16656:                                                 foreach my $option (@options) {
16657:                                                     if ($confhash{'scantron'}{'config'}{'csv'}{'options'}{$option} ne '') {
16658:                                                         $resulttext .= '<li>'.$titles{$option}.'</li>';
16659:                                                     }
16660:                                                 }
16661:                                                 $resulttext .= '</ul></li>';
16662:                                             }
16663:                                         }
16664:                                     }
16665:                                 }
16666:                             }
16667:                         } else {
16668:                             $resulttext .= '<li>'.&mt('No bubblesheet data upload formats set -- will default to assuming .dat format').'</li>';
16669:                         }
16670:                     }
16671:                     $resulttext .= '</ul>';
16672:                 } else {
16673:                     $resulttext = &mt('Changes made to bubblesheet format file.');
16674:                 }
16675:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
16676:                 if (ref($lastactref) eq 'HASH') {
16677:                     $lastactref->{'domainconfig'} = 1;
16678:                 }
16679:             } else {
16680:                 $resulttext = &mt('No changes made to bubblesheet format settings');
16681:             }
16682:         } else {
16683:             $resulttext = '<span class="LC_error">'.
16684:                 &mt('An error occurred: [_1]',$putresult).'</span>';
16685:         }
16686:     } else {
16687:         $resulttext = &mt('No changes made to bubblesheet format settings');
16688:     }
16689:     if ($errors) {
16690:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
16691:                        $errors.'</ul>';
16692:     }
16693:     return $resulttext;
16694: }
16695: 
16696: sub modify_coursecategories {
16697:     my ($dom,$lastactref,%domconfig) = @_;
16698:     my ($resulttext,%deletions,%reorderings,%needreordering,%adds,%changes,$errors,
16699:         $cathash);
16700:     my @deletecategory = &Apache::loncommon::get_env_multiple('form.deletecategory');
16701:     my @catitems = ('unauth','auth');
16702:     my @cattypes = ('std','domonly','codesrch','none');
16703:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
16704:         $cathash = $domconfig{'coursecategories'}{'cats'};
16705:         if ($domconfig{'coursecategories'}{'togglecats'} ne $env{'form.togglecats'}) {
16706:             $changes{'togglecats'} = 1;
16707:             $domconfig{'coursecategories'}{'togglecats'} = $env{'form.togglecats'};
16708:         }
16709:         if ($domconfig{'coursecategories'}{'categorize'} ne $env{'form.categorize'}) {
16710:             $changes{'categorize'} = 1;
16711:             $domconfig{'coursecategories'}{'categorize'} = $env{'form.categorize'};
16712:         }
16713:         if ($domconfig{'coursecategories'}{'togglecatscomm'} ne $env{'form.togglecatscomm'}) {
16714:             $changes{'togglecatscomm'} = 1;
16715:             $domconfig{'coursecategories'}{'togglecatscomm'} = $env{'form.togglecatscomm'};
16716:         }
16717:         if ($domconfig{'coursecategories'}{'categorizecomm'} ne $env{'form.categorizecomm'}) {
16718:             $changes{'categorizecomm'} = 1;
16719:             $domconfig{'coursecategories'}{'categorizecomm'} = $env{'form.categorizecomm'};
16720:         }
16721:         foreach my $item (@catitems) {
16722:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
16723:                 if ($domconfig{'coursecategories'}{$item} ne $env{'form.coursecat_'.$item}) {
16724:                     $changes{$item} = 1;
16725:                     $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
16726:                 }
16727:             }
16728:         }
16729:     } else {
16730:         $changes{'togglecats'} = 1;
16731:         $changes{'categorize'} = 1;
16732:         $changes{'togglecatscomm'} = 1;
16733:         $changes{'categorizecomm'} = 1;
16734:         $domconfig{'coursecategories'} = {
16735:                                              togglecats => $env{'form.togglecats'},
16736:                                              categorize => $env{'form.categorize'},
16737:                                              togglecatscomm => $env{'form.togglecatscomm'},
16738:                                              categorizecomm => $env{'form.categorizecomm'},
16739:                                          };
16740:         foreach my $item (@catitems) {
16741:             if ($env{'form.coursecat_'.$item} ne 'std') {
16742:                 $changes{$item} = 1;
16743:             }
16744:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
16745:                 $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
16746:             }
16747:         }
16748:     }
16749:     if (ref($cathash) eq 'HASH') {
16750:         if (($domconfig{'coursecategories'}{'cats'}{'instcode::0'} ne '')  && ($env{'form.instcode'} == 0)) {
16751:             push (@deletecategory,'instcode::0');
16752:         }
16753:         if (($domconfig{'coursecategories'}{'cats'}{'communities::0'} ne '')  && ($env{'form.communities'} == 0)) {
16754:             push(@deletecategory,'communities::0');
16755:         }
16756:     }
16757:     my (@predelcats,@predeltrails,%predelallitems,%sort_by_deltrail);
16758:     if (ref($cathash) eq 'HASH') {
16759:         if (@deletecategory > 0) {
16760:             #FIXME Need to remove category from all courses using a deleted category 
16761:             &Apache::loncommon::extract_categories($cathash,\@predelcats,\@predeltrails,\%predelallitems);
16762:             foreach my $item (@deletecategory) {
16763:                 if ($domconfig{'coursecategories'}{'cats'}{$item} ne '') {
16764:                     delete($domconfig{'coursecategories'}{'cats'}{$item});
16765:                     $deletions{$item} = 1;
16766:                     &recurse_cat_deletes($item,$cathash,\%deletions);
16767:                 }
16768:             }
16769:         }
16770:         foreach my $item (keys(%{$cathash})) {
16771:             my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
16772:             if ($cathash->{$item} ne $env{'form.'.$item}) {
16773:                 $reorderings{$item} = 1;
16774:                 $domconfig{'coursecategories'}{'cats'}{$item} = $env{'form.'.$item};
16775:             }
16776:             if ($env{'form.addcategory_name_'.$item} ne '') {
16777:                 my $newcat = $env{'form.addcategory_name_'.$item};
16778:                 my $newdepth = $depth+1;
16779:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
16780:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos_'.$item};
16781:                 $adds{$newitem} = 1; 
16782:             }
16783:             if ($env{'form.subcat_'.$item} ne '') {
16784:                 my $newcat = $env{'form.subcat_'.$item};
16785:                 my $newdepth = $depth+1;
16786:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
16787:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = 0;
16788:                 $adds{$newitem} = 1;
16789:             }
16790:         }
16791:     }
16792:     if ($env{'form.instcode'} eq '1') {
16793:         if (ref($cathash) eq 'HASH') {
16794:             my $newitem = 'instcode::0';
16795:             if ($cathash->{$newitem} eq '') {  
16796:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
16797:                 $adds{$newitem} = 1;
16798:             }
16799:         } else {
16800:             my $newitem = 'instcode::0';
16801:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
16802:             $adds{$newitem} = 1;
16803:         }
16804:     }
16805:     if ($env{'form.communities'} eq '1') {
16806:         if (ref($cathash) eq 'HASH') {
16807:             my $newitem = 'communities::0';
16808:             if ($cathash->{$newitem} eq '') {
16809:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
16810:                 $adds{$newitem} = 1;
16811:             }
16812:         } else {
16813:             my $newitem = 'communities::0';
16814:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
16815:             $adds{$newitem} = 1;
16816:         }
16817:     }
16818:     if ($env{'form.addcategory_name'} ne '') {
16819:         if (($env{'form.addcategory_name'} ne 'instcode') &&
16820:             ($env{'form.addcategory_name'} ne 'communities')) {
16821:             my $newitem = &escape($env{'form.addcategory_name'}).'::0';
16822:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos'};
16823:             $adds{$newitem} = 1;
16824:         }
16825:     }
16826:     my $putresult;
16827:     if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
16828:         if (keys(%deletions) > 0) {
16829:             foreach my $key (keys(%deletions)) {
16830:                 if ($predelallitems{$key} ne '') {
16831:                     $sort_by_deltrail{$predelallitems{$key}} = $predeltrails[$predelallitems{$key}];
16832:                 }
16833:             }
16834:         }
16835:         my (@chkcats,@chktrails,%chkallitems);
16836:         &Apache::loncommon::extract_categories($domconfig{'coursecategories'}{'cats'},\@chkcats,\@chktrails,\%chkallitems);
16837:         if (ref($chkcats[0]) eq 'ARRAY') {
16838:             my $depth = 0;
16839:             my $chg = 0;
16840:             for (my $i=0; $i<@{$chkcats[0]}; $i++) {
16841:                 my $name = $chkcats[0][$i];
16842:                 my $item;
16843:                 if ($name eq '') {
16844:                     $chg ++;
16845:                 } else {
16846:                     $item = &escape($name).'::0';
16847:                     if ($chg) {
16848:                         $domconfig{'coursecategories'}{'cats'}{$item} -= $chg;
16849:                     }
16850:                     $depth ++; 
16851:                     &recurse_check(\@chkcats,$domconfig{'coursecategories'}{'cats'},$depth,$name);
16852:                     $depth --;
16853:                 }
16854:             }
16855:         }
16856:     }
16857:     if ((keys(%changes) > 0) || (keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
16858:         $putresult = &Apache::lonnet::put_dom('configuration',\%domconfig,$dom);
16859:         if ($putresult eq 'ok') {
16860:             my %title = (
16861:                          togglecats     => 'Show/Hide a course in catalog',
16862:                          categorize     => 'Assign a category to a course',
16863:                          togglecatscomm => 'Show/Hide a community in catalog',
16864:                          categorizecomm => 'Assign a category to a community',
16865:                         );
16866:             my %level = (
16867:                          dom  => 'set in Domain ("Modify Course/Community")',
16868:                          crs  => 'set in Course ("Course Configuration")',
16869:                          comm => 'set in Community ("Community Configuration")',
16870:                          none     => 'No catalog',
16871:                          std      => 'Standard catalog',
16872:                          domonly  => 'Domain-only catalog',
16873:                          codesrch => 'Code search form',
16874:                         );
16875:             $resulttext = &mt('Changes made:').'<ul>';
16876:             if ($changes{'togglecats'}) {
16877:                 $resulttext .= '<li>'.&mt("$title{'togglecats'} $level{$env{'form.togglecats'}}").'</li>'; 
16878:             }
16879:             if ($changes{'categorize'}) {
16880:                 $resulttext .= '<li>'.&mt("$title{'categorize'} $level{$env{'form.categorize'}}").'</li>';
16881:             }
16882:             if ($changes{'togglecatscomm'}) {
16883:                 $resulttext .= '<li>'.&mt("$title{'togglecatscomm'} $level{$env{'form.togglecatscomm'}}").'</li>';
16884:             }
16885:             if ($changes{'categorizecomm'}) {
16886:                 $resulttext .= '<li>'.&mt("$title{'categorizecomm'} $level{$env{'form.categorizecomm'}}").'</li>';
16887:             }
16888:             if ($changes{'unauth'}) {
16889:                 $resulttext .= '<li>'.&mt('Catalog type for unauthenticated users set to "'.$level{$env{'form.coursecat_unauth'}}.'"').'</li>';
16890:             }
16891:             if ($changes{'auth'}) {
16892:                 $resulttext .= '<li>'.&mt('Catalog type for authenticated users set to "'.$level{$env{'form.coursecat_auth'}}.'"').'</li>';
16893:             }
16894:             if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
16895:                 my $cathash;
16896:                 if (ref($domconfig{'coursecategories'}) eq 'HASH') {
16897:                     $cathash = $domconfig{'coursecategories'}{'cats'};
16898:                 } else {
16899:                     $cathash = {};
16900:                 } 
16901:                 my (@cats,@trails,%allitems);
16902:                     &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,\%allitems);
16903:                 if (keys(%deletions) > 0) {
16904:                     $resulttext .= '<li>'.&mt('Deleted categories:').'<ul>';
16905:                     foreach my $predeltrail (sort {$a <=> $b } (keys(%sort_by_deltrail))) { 
16906:                         $resulttext .= '<li>'.$predeltrails[$predeltrail].'</li>';
16907:                     }
16908:                     $resulttext .= '</ul></li>';
16909:                 }
16910:                 if (keys(%reorderings) > 0) {
16911:                     my %sort_by_trail;
16912:                     $resulttext .= '<li>'.&mt('Reordered categories:').'<ul>';
16913:                     foreach my $key (keys(%reorderings)) {
16914:                         if ($allitems{$key} ne '') {
16915:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
16916:                         }
16917:                     }
16918:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
16919:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
16920:                     }
16921:                     $resulttext .= '</ul></li>';
16922:                 }
16923:                 if (keys(%adds) > 0) {
16924:                     my %sort_by_trail;
16925:                     $resulttext .= '<li>'.&mt('Added categories:').'<ul>';
16926:                     foreach my $key (keys(%adds)) {
16927:                         if ($allitems{$key} ne '') {
16928:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
16929:                         }
16930:                     }
16931:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
16932:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
16933:                     }
16934:                     $resulttext .= '</ul></li>';
16935:                 }
16936:                 &Apache::lonnet::do_cache_new('cats',$dom,$cathash,3600);
16937:                 if (ref($lastactref) eq 'HASH') {
16938:                     $lastactref->{'cats'} = 1;
16939:                 }
16940:             }
16941:             $resulttext .= '</ul>';
16942:             if ($changes{'unauth'} || $changes{'auth'}) {
16943:                 my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
16944:                 if ($changes{'auth'}) {
16945:                     $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
16946:                 }
16947:                 if ($changes{'unauth'}) {
16948:                     $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
16949:                 }
16950:                 my $cachetime = 24*60*60;
16951:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
16952:                 if (ref($lastactref) eq 'HASH') {
16953:                     $lastactref->{'domdefaults'} = 1;
16954:                 }
16955:             }
16956:         } else {
16957:             $resulttext = '<span class="LC_error">'.
16958:                           &mt('An error occurred: [_1]',$putresult).'</span>';
16959:         }
16960:     } else {
16961:         $resulttext = &mt('No changes made to course and community categories');
16962:     }
16963:     return $resulttext;
16964: }
16965: 
16966: sub modify_serverstatuses {
16967:     my ($dom,%domconfig) = @_;
16968:     my ($resulttext,%changes,%currserverstatus,%newserverstatus);
16969:     if (ref($domconfig{'serverstatuses'}) eq 'HASH') {
16970:         %currserverstatus = %{$domconfig{'serverstatuses'}};
16971:     }
16972:     my @pages = &serverstatus_pages();
16973:     foreach my $type (@pages) {
16974:         $newserverstatus{$type}{'namedusers'} = '';
16975:         $newserverstatus{$type}{'machines'} = '';
16976:         if (defined($env{'form.'.$type.'_namedusers'})) {
16977:             my @users = split(/,/,$env{'form.'.$type.'_namedusers'});
16978:             my @okusers;
16979:             foreach my $user (@users) {
16980:                 my ($uname,$udom) = split(/:/,$user);
16981:                 if (($udom =~ /^$match_domain$/) &&   
16982:                     (&Apache::lonnet::domain($udom)) &&
16983:                     ($uname =~ /^$match_username$/)) {
16984:                     if (!grep(/^\Q$user\E/,@okusers)) {
16985:                         push(@okusers,$user);
16986:                     }
16987:                 }
16988:             }
16989:             if (@okusers > 0) {
16990:                  @okusers = sort(@okusers);
16991:                  $newserverstatus{$type}{'namedusers'} = join(',',@okusers);
16992:             }
16993:         }
16994:         if (defined($env{'form.'.$type.'_machines'})) {
16995:             my @machines = split(/,/,$env{'form.'.$type.'_machines'});
16996:             my @okmachines;
16997:             foreach my $ip (@machines) {
16998:                 my @parts = split(/\./,$ip);
16999:                 next if (@parts < 4);
17000:                 my $badip = 0;
17001:                 for (my $i=0; $i<4; $i++) {
17002:                     if (!(($parts[$i] >= 0) && ($parts[$i] <= 255))) {
17003:                         $badip = 1;
17004:                         last;
17005:                     }
17006:                 }
17007:                 if (!$badip) {
17008:                     push(@okmachines,$ip);     
17009:                 }
17010:             }
17011:             @okmachines = sort(@okmachines);
17012:             $newserverstatus{$type}{'machines'} = join(',',@okmachines);
17013:         }
17014:     }
17015:     my %serverstatushash =  (
17016:                                 serverstatuses => \%newserverstatus,
17017:                             );
17018:     foreach my $type (@pages) {
17019:         foreach my $setting ('namedusers','machines') {
17020:             my (@current,@new);
17021:             if (ref($currserverstatus{$type}) eq 'HASH') {
17022:                 if ($currserverstatus{$type}{$setting} ne '') { 
17023:                     @current = split(/,/,$currserverstatus{$type}{$setting});
17024:                 }
17025:             }
17026:             if ($newserverstatus{$type}{$setting} ne '') {
17027:                 @new = split(/,/,$newserverstatus{$type}{$setting});
17028:             }
17029:             if (@current > 0) {
17030:                 if (@new > 0) {
17031:                     foreach my $item (@current) {
17032:                         if (!grep(/^\Q$item\E$/,@new)) {
17033:                             $changes{$type}{$setting} = 1;
17034:                             last;
17035:                         }
17036:                     }
17037:                     foreach my $item (@new) {
17038:                         if (!grep(/^\Q$item\E$/,@current)) {
17039:                             $changes{$type}{$setting} = 1;
17040:                             last;
17041:                         }
17042:                     }
17043:                 } else {
17044:                     $changes{$type}{$setting} = 1;
17045:                 }
17046:             } elsif (@new > 0) {
17047:                 $changes{$type}{$setting} = 1;
17048:             }
17049:         }
17050:     }
17051:     if (keys(%changes) > 0) {
17052:         my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
17053:         my $putresult = &Apache::lonnet::put_dom('configuration',
17054:                                                  \%serverstatushash,$dom);
17055:         if ($putresult eq 'ok') {
17056:             $resulttext .= &mt('Changes made:').'<ul>';
17057:             foreach my $type (@pages) {
17058:                 if (ref($changes{$type}) eq 'HASH') {
17059:                     $resulttext .= '<li>'.$titles->{$type}.'<ul>';
17060:                     if ($changes{$type}{'namedusers'}) {
17061:                         if ($newserverstatus{$type}{'namedusers'} eq '') {
17062:                             $resulttext .= '<li>'.&mt("Access terminated for all specific (named) users").'</li>'."\n";
17063:                         } else {
17064:                             $resulttext .= '<li>'.&mt("Access available for the following specified users: ").$newserverstatus{$type}{'namedusers'}.'</li>'."\n";
17065:                         }
17066:                     }
17067:                     if ($changes{$type}{'machines'}) {
17068:                         if ($newserverstatus{$type}{'machines'} eq '') {
17069:                             $resulttext .= '<li>'.&mt("Access terminated for all specific IP addresses").'</li>'."\n";
17070:                         } else {
17071:                             $resulttext .= '<li>'.&mt("Access available for the following specified IP addresses: ").$newserverstatus{$type}{'machines'}.'</li>'."\n";
17072:                         }
17073: 
17074:                     }
17075:                     $resulttext .= '</ul></li>';
17076:                 }
17077:             }
17078:             $resulttext .= '</ul>';
17079:         } else {
17080:             $resulttext = '<span class="LC_error">'.
17081:                           &mt('An error occurred saving access settings for server status pages: [_1].',$putresult).'</span>';
17082: 
17083:         }
17084:     } else {
17085:         $resulttext = &mt('No changes made to access to server status pages');
17086:     }
17087:     return $resulttext;
17088: }
17089: 
17090: sub modify_helpsettings {
17091:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
17092:     my ($resulttext,$errors,%changes,%helphash);
17093:     my %defaultchecked = ('submitbugs' => 'on');
17094:     my @offon = ('off','on');
17095:     my @toggles = ('submitbugs');
17096:     my %current = ('submitbugs' => '',
17097:                    'adhoc'      => {},
17098:                   );
17099:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
17100:         %current = %{$domconfig{'helpsettings'}};
17101:     }
17102:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
17103:     foreach my $item (@toggles) {
17104:         if ($defaultchecked{$item} eq 'on') { 
17105:             if ($current{$item} eq '') {
17106:                 if ($env{'form.'.$item} eq '0') {
17107:                     $changes{$item} = 1;
17108:                 }
17109:             } elsif ($current{$item} ne $env{'form.'.$item}) {
17110:                 $changes{$item} = 1;
17111:             }
17112:         } elsif ($defaultchecked{$item} eq 'off') {
17113:             if ($current{$item} eq '') {
17114:                 if ($env{'form.'.$item} eq '1') {
17115:                     $changes{$item} = 1;
17116:                 }
17117:             } elsif ($current{$item} ne $env{'form.'.$item}) {
17118:                 $changes{$item} = 1;
17119:             }
17120:         }
17121:         if (($env{'form.'.$item} eq '0') || ($env{'form.'.$item} eq '1')) {
17122:             $helphash{'helpsettings'}{$item} = $env{'form.'.$item};
17123:         }
17124:     }
17125:     my $maxnum = $env{'form.helproles_maxnum'};
17126:     my $confname = $dom.'-domainconfig';
17127:     my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
17128:     my (@allpos,%newsettings,%changedprivs,$newrole);
17129:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
17130:     my @accesstypes = ('all','dh','da','none','status','inc','exc');
17131:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh','da']);
17132:     my %lt = &Apache::lonlocal::texthash(
17133:                     s      => 'system',
17134:                     d      => 'domain',
17135:                     order  => 'Display order',
17136:                     access => 'Role usage',
17137:                     all    => 'All with domain helpdesk or helpdesk assistant role',
17138:                     dh     => 'All with domain helpdesk role',
17139:                     da     => 'All with domain helpdesk assistant role',
17140:                     none   => 'None',
17141:                     status => 'Determined based on institutional status',
17142:                     inc    => 'Include all, but exclude specific personnel',
17143:                     exc    => 'Exclude all, but include specific personnel',
17144:     );
17145:     for (my $num=0; $num<=$maxnum; $num++) {
17146:         my ($prefix,$identifier,$rolename,%curr);
17147:         if ($num == $maxnum) {
17148:             next unless ($env{'form.newcusthelp'} == $maxnum);
17149:             $identifier = 'custhelp'.$num;
17150:             $prefix = 'helproles_'.$num;
17151:             $rolename = $env{'form.custhelpname'.$num};
17152:             $rolename=~s/[^A-Za-z0-9]//gs;
17153:             next if ($rolename eq '');
17154:             next if (exists($existing{'rolesdef_'.$rolename}));
17155:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
17156:             my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
17157:                                                      $newprivs{'c'},$confname,$dom);
17158:             if ($result ne 'ok') {
17159:                 $errors .= '<li><span class="LC_error">'.
17160:                            &mt('An error occurred storing the new custom role: [_1]',
17161:                            $result).'</span></li>';
17162:                 next;
17163:             } else {
17164:                 $changedprivs{$rolename} = \%newprivs;
17165:                 $newrole = $rolename;
17166:             }
17167:         } else {
17168:             $prefix = 'helproles_'.$num;
17169:             $rolename = $env{'form.'.$prefix};
17170:             next if ($rolename eq '');
17171:             next unless (exists($existing{'rolesdef_'.$rolename}));
17172:             $identifier = 'custhelp'.$num;
17173:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
17174:             my %currprivs;
17175:             ($currprivs{'s'},$currprivs{'d'},$currprivs{'c'}) =
17176:                 split(/\_/,$existing{'rolesdef_'.$rolename});
17177:             foreach my $level ('c','d','s') {
17178:                 if ($newprivs{$level} ne $currprivs{$level}) {
17179:                     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
17180:                                                              $newprivs{'c'},$confname,$dom);
17181:                     if ($result ne 'ok') {
17182:                         $errors .= '<li><span class="LC_error">'.
17183:                                    &mt('An error occurred storing privileges for existing role [_1]: [_2]',
17184:                                        $rolename,$result).'</span></li>';
17185:                     } else {
17186:                         $changedprivs{$rolename} = \%newprivs;
17187:                     }
17188:                     last;
17189:                 }
17190:             }
17191:             if (ref($current{'adhoc'}) eq 'HASH') {
17192:                 if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
17193:                     %curr = %{$current{'adhoc'}{$rolename}};
17194:                 }
17195:             }
17196:         }
17197:         my $newpos = $env{'form.'.$prefix.'_pos'};
17198:         $newpos =~ s/\D+//g;
17199:         $allpos[$newpos] = $rolename;
17200:         my $newdesc = $env{'form.'.$prefix.'_desc'};
17201:         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'desc'} = $newdesc;
17202:         if ($curr{'desc'}) {
17203:             if ($curr{'desc'} ne $newdesc) {
17204:                 $changes{'customrole'}{$rolename}{'desc'} = 1;
17205:                 $newsettings{$rolename}{'desc'} = $newdesc;
17206:             }
17207:         } elsif ($newdesc ne '') {
17208:             $changes{'customrole'}{$rolename}{'desc'} = 1;
17209:             $newsettings{$rolename}{'desc'} = $newdesc;
17210:         }
17211:         my $access = $env{'form.'.$prefix.'_access'};
17212:         if (grep(/^\Q$access\E$/,@accesstypes)) {
17213:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = $access;
17214:             if ($access eq 'status') {
17215:                 my @statuses = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_status');
17216:                 if (scalar(@statuses) == 0) {
17217:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'none';
17218:                 } else {
17219:                     my (@shownstatus,$numtypes);
17220:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
17221:                     if (ref($types) eq 'ARRAY') {
17222:                         $numtypes = scalar(@{$types});
17223:                         foreach my $type (sort(@statuses)) {
17224:                             if ($type eq 'default') {
17225:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
17226:                             } elsif (grep(/^\Q$type\E$/,@{$types})) {
17227:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
17228:                                 push(@shownstatus,$usertypes->{$type});
17229:                             }
17230:                         }
17231:                     }
17232:                     if (grep(/^default$/,@statuses)) {
17233:                         push(@shownstatus,$othertitle);
17234:                     }
17235:                     if (scalar(@shownstatus) == 1+$numtypes) {
17236:                         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'all';
17237:                         delete($helphash{'helpsettings'}{'adhoc'}{$rolename}{'status'});
17238:                     } else {
17239:                         $newsettings{$rolename}{'status'} = join(' '.&mt('or').' ',@shownstatus);
17240:                         if (ref($curr{'status'}) eq 'ARRAY') {
17241:                             my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
17242:                             if (@diffs) {
17243:                                 $changes{'customrole'}{$rolename}{$access} = 1;
17244:                             }
17245:                         } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
17246:                             $changes{'customrole'}{$rolename}{$access} = 1;
17247:                         }
17248:                     }
17249:                 }
17250:             } elsif (($access eq 'inc') || ($access eq 'exc')) {
17251:                 my @personnel = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_staff_'.$access);
17252:                 my @newspecstaff;
17253:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
17254:                 foreach my $person (sort(@personnel)) {
17255:                     if ($domhelpdesk{$person}) {
17256:                         push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$person);
17257:                     }
17258:                 }
17259:                 if (ref($curr{$access}) eq 'ARRAY') {
17260:                     my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
17261:                     if (@diffs) {
17262:                         $changes{'customrole'}{$rolename}{$access} = 1;
17263:                     }
17264:                 } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
17265:                     $changes{'customrole'}{$rolename}{$access} = 1;
17266:                 }
17267:                 foreach my $person (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
17268:                     my ($uname,$udom) = split(/:/,$person);
17269:                         push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
17270:                 }
17271:                 $newsettings{$rolename}{$access} = join(', ',sort(@newspecstaff));
17272:             }
17273:         } else {
17274:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}= 'all';
17275:         }
17276:         unless ($curr{'access'} eq $access) {
17277:             $changes{'customrole'}{$rolename}{'access'} = 1;
17278:             $newsettings{$rolename}{'access'} = $lt{$helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}};
17279:         }
17280:     }
17281:     if (@allpos > 0) {
17282:         my $idx = 0;
17283:         foreach my $rolename (@allpos) {
17284:             if ($rolename ne '') {
17285:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{'order'} = $idx;
17286:                 if (ref($current{'adhoc'}) eq 'HASH') {
17287:                     if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
17288:                         if ($current{'adhoc'}{$rolename}{'order'} ne $idx) {
17289:                             $changes{'customrole'}{$rolename}{'order'} = 1;
17290:                             $newsettings{$rolename}{'order'} = $idx+1;
17291:                         }
17292:                     }
17293:                 }
17294:                 $idx ++;
17295:             }
17296:         }
17297:     }
17298:     my $putresult;
17299:     if (keys(%changes) > 0) {
17300:         $putresult = &Apache::lonnet::put_dom('configuration',\%helphash,$dom);
17301:         if ($putresult eq 'ok') {
17302:             if (ref($helphash{'helpsettings'}) eq 'HASH') {
17303:                 $domdefaults{'submitbugs'} = $helphash{'helpsettings'}{'submitbugs'};
17304:                 if (ref($helphash{'helpsettings'}{'adhoc'}) eq 'HASH') {
17305:                     $domdefaults{'adhocroles'} = $helphash{'helpsettings'}{'adhoc'};
17306:                 }
17307:             }
17308:             my $cachetime = 24*60*60;
17309:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
17310:             if (ref($lastactref) eq 'HASH') {
17311:                 $lastactref->{'domdefaults'} = 1;
17312:             }
17313:         } else {
17314:             $errors .= '<li><span class="LC_error">'.
17315:                        &mt('An error occurred storing the settings: [_1]',
17316:                            $putresult).'</span></li>';
17317:         }
17318:     }
17319:     if ((keys(%changes) && ($putresult eq 'ok')) || (keys(%changedprivs))) {
17320:         $resulttext = &mt('Changes made:').'<ul>';
17321:         my (%shownprivs,@levelorder);
17322:         @levelorder = ('c','d','s');
17323:         if ((keys(%changes)) && ($putresult eq 'ok')) {
17324:             foreach my $item (sort(keys(%changes))) {
17325:                 if ($item eq 'submitbugs') {
17326:                     $resulttext .= '<li>'.&mt('Display link to: [_1] set to "'.$offon[$env{'form.'.$item}].'".',
17327:                                               &Apache::loncommon::modal_link('http://bugs.loncapa.org',
17328:                                               &mt('LON-CAPA bug tracker'),600,500)).'</li>';
17329:                 } elsif ($item eq 'customrole') {
17330:                     if (ref($changes{'customrole'}) eq 'HASH') {
17331:                         my @keyorder = ('order','desc','access','status','exc','inc');
17332:                         my %keytext = &Apache::lonlocal::texthash(
17333:                                                                    order  => 'Order',
17334:                                                                    desc   => 'Role description',
17335:                                                                    access => 'Role usage',
17336:                                                                    status => 'Allowed institutional types',
17337:                                                                    exc    => 'Allowed personnel',
17338:                                                                    inc    => 'Disallowed personnel',
17339:                         );
17340:                         foreach my $role (sort(keys(%{$changes{'customrole'}}))) {
17341:                             if (ref($changes{'customrole'}{$role}) eq 'HASH') {
17342:                                 if ($role eq $newrole) {
17343:                                     $resulttext .= '<li>'.&mt('New custom role added: [_1]',
17344:                                                               $role).'<ul>';
17345:                                 } else {
17346:                                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
17347:                                                               $role).'<ul>';
17348:                                 }
17349:                                 foreach my $key (@keyorder) {
17350:                                     if ($changes{'customrole'}{$role}{$key}) {
17351:                                         $resulttext .= '<li>'.&mt("[_1] set to: [_2]",
17352:                                                                   $keytext{$key},$newsettings{$role}{$key}).
17353:                                                        '</li>';
17354:                                     }
17355:                                 }
17356:                                 if (ref($changedprivs{$role}) eq 'HASH') {
17357:                                     $shownprivs{$role} = 1;
17358:                                     $resulttext .= '<li>'.&mt('Privileges set to :').'<ul>';
17359:                                     foreach my $level (@levelorder) {
17360:                                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
17361:                                             next if ($item eq '');
17362:                                             my ($priv) = split(/\&/,$item,2);
17363:                                             if (&Apache::lonnet::plaintext($priv)) {
17364:                                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
17365:                                                 unless ($level eq 'c') {
17366:                                                     $resulttext .= ' ('.$lt{$level}.')';
17367:                                                 }
17368:                                                 $resulttext .= '</li>';
17369:                                             }
17370:                                         }
17371:                                     }
17372:                                     $resulttext .= '</ul>';
17373:                                 }
17374:                                 $resulttext .= '</ul></li>';
17375:                             }
17376:                         }
17377:                     }
17378:                 }
17379:             }
17380:         }
17381:         if (keys(%changedprivs)) {
17382:             foreach my $role (sort(keys(%changedprivs))) {
17383:                 unless ($shownprivs{$role}) {
17384:                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
17385:                                               $role).'<ul>'.
17386:                                    '<li>'.&mt('Privileges set to :').'<ul>';
17387:                     foreach my $level (@levelorder) {
17388:                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
17389:                             next if ($item eq '');
17390:                             my ($priv) = split(/\&/,$item,2);
17391:                             if (&Apache::lonnet::plaintext($priv)) {
17392:                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
17393:                                 unless ($level eq 'c') {
17394:                                     $resulttext .= ' ('.$lt{$level}.')';
17395:                                 }
17396:                                 $resulttext .= '</li>';
17397:                             }
17398:                         }
17399:                     }
17400:                     $resulttext .= '</ul></li></ul></li>';
17401:                 }
17402:             }
17403:         }
17404:         $resulttext .= '</ul>';
17405:     } else {
17406:         $resulttext = &mt('No changes made to help settings');
17407:     }
17408:     if ($errors) {
17409:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
17410:                                     $errors.'</ul>';
17411:     }
17412:     return $resulttext;
17413: }
17414: 
17415: sub modify_coursedefaults {
17416:     my ($dom,$lastactref,%domconfig) = @_;
17417:     my ($resulttext,$errors,%changes,%defaultshash);
17418:     my %defaultchecked = (
17419:                            'uselcmath'       => 'on',
17420:                            'usejsme'         => 'on',
17421:                            'inline_chem'     => 'on',
17422:                            'ltiauth'         => 'off',
17423:                          );
17424:     my @toggles = ('uselcmath','usejsme','inline_chem','ltiauth');
17425:     my @numbers = ('anonsurvey_threshold','uploadquota_official','uploadquota_unofficial',
17426:                    'uploadquota_community','uploadquota_textbook','mysqltables_official',
17427:                    'mysqltables_unofficial','mysqltables_community','mysqltables_textbook');
17428:     my @types = ('official','unofficial','community','textbook');
17429:     my %staticdefaults = (
17430:                            anonsurvey_threshold => 10,
17431:                            uploadquota          => 500,
17432:                            postsubmit           => 60,
17433:                            mysqltables          => 172800,
17434:                          );
17435:     my %texoptions = (
17436:                         MathJax  => 'MathJax',
17437:                         mimetex  => &mt('Convert to Images'),
17438:                         tth      => &mt('TeX to HTML'),
17439:                      );
17440:     $defaultshash{'coursedefaults'} = {};
17441: 
17442:     if (ref($domconfig{'coursedefaults'}) ne 'HASH') {
17443:         if ($domconfig{'coursedefaults'} eq '') {
17444:             $domconfig{'coursedefaults'} = {};
17445:         }
17446:     }
17447: 
17448:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
17449:         foreach my $item (@toggles) {
17450:             if ($defaultchecked{$item} eq 'on') {
17451:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
17452:                     ($env{'form.'.$item} eq '0')) {
17453:                     $changes{$item} = 1;
17454:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
17455:                     $changes{$item} = 1;
17456:                 }
17457:             } elsif ($defaultchecked{$item} eq 'off') {
17458:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
17459:                     ($env{'form.'.$item} eq '1')) {
17460:                     $changes{$item} = 1;
17461:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
17462:                     $changes{$item} = 1;
17463:                 }
17464:             }
17465:             $defaultshash{'coursedefaults'}{$item} = $env{'form.'.$item};
17466:         }
17467:         foreach my $item (@numbers) {
17468:             my ($currdef,$newdef);
17469:             $newdef = $env{'form.'.$item};
17470:             if ($item eq 'anonsurvey_threshold') {
17471:                 $currdef = $domconfig{'coursedefaults'}{$item};
17472:                 $newdef =~ s/\D//g;
17473:                 if ($newdef eq '' || $newdef < 1) {
17474:                     $newdef = 1;
17475:                 }
17476:                 $defaultshash{'coursedefaults'}{$item} = $newdef;
17477:             } else {
17478:                 my ($setting,$type) = ($item =~ /^(uploadquota|mysqltables)_(\w+)$/);
17479:                 if (ref($domconfig{'coursedefaults'}{$setting}) eq 'HASH') {
17480:                     $currdef = $domconfig{'coursedefaults'}{$setting}{$type};
17481:                 }
17482:                 $newdef =~ s/[^\w.\-]//g;
17483:                 $defaultshash{'coursedefaults'}{$setting}{$type} = $newdef;
17484:             }
17485:             if ($currdef ne $newdef) {
17486:                 if ($item eq 'anonsurvey_threshold') {
17487:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$item})) {
17488:                         $changes{$item} = 1;
17489:                     }
17490:                 } elsif ($item =~ /^(uploadquota|mysqltables)_/) {
17491:                     my $setting = $1;
17492:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$setting})) {
17493:                         $changes{$setting} = 1;
17494:                     }
17495:                 }
17496:             }
17497:         }
17498:         my $texengine;
17499:         if ($env{'form.texengine'} =~ /^(MathJax|mimetex|tth)$/) {
17500:             $texengine = $env{'form.texengine'};
17501:             my $currdef = $domconfig{'coursedefaults'}{'texengine'};
17502:             if ($currdef eq '') {
17503:                 unless ($texengine eq $Apache::lonnet::deftex) {
17504:                     $changes{'texengine'} = 1;
17505:                 }
17506:             } elsif ($currdef ne $texengine) {
17507:                 $changes{'texengine'} = 1;
17508:             }
17509:         }
17510:         if ($texengine ne '') {
17511:             $defaultshash{'coursedefaults'}{'texengine'} = $texengine;
17512:         }
17513:         my $currclone = $domconfig{'coursedefaults'}{'canclone'};
17514:         my @currclonecode;
17515:         if (ref($currclone) eq 'HASH') {
17516:             if (ref($currclone->{'instcode'}) eq 'ARRAY') {
17517:                 @currclonecode = @{$currclone->{'instcode'}};
17518:             }
17519:         }
17520:         my $newclone;
17521:         if ($env{'form.canclone'} =~ /^(none|domain|instcode)$/) {
17522:             $newclone = $env{'form.canclone'};
17523:         }
17524:         if ($newclone eq 'instcode') {
17525:             my @newcodes = &Apache::loncommon::get_env_multiple('form.clonecode');
17526:             my (%codedefaults,@code_order,@clonecode);
17527:             &Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
17528:                                                     \@code_order);
17529:             foreach my $item (@code_order) {
17530:                 if (grep(/^\Q$item\E$/,@newcodes)) {
17531:                     push(@clonecode,$item);
17532:                 }
17533:             }
17534:             if (@clonecode) {
17535:                 $defaultshash{'coursedefaults'}{'canclone'} = { $newclone => \@clonecode };
17536:                 my @diffs = &Apache::loncommon::compare_arrays(\@currclonecode,\@clonecode);
17537:                 if (@diffs) {
17538:                     $changes{'canclone'} = 1;
17539:                 }
17540:             } else {
17541:                 $newclone eq '';
17542:             }
17543:         } elsif ($newclone ne '') {
17544:             $defaultshash{'coursedefaults'}{'canclone'} = $newclone;
17545:         }
17546:         if ($newclone ne $currclone) {
17547:             $changes{'canclone'} = 1;
17548:         }
17549:         my %credits;
17550:         foreach my $type (@types) {
17551:             unless ($type eq 'community') {
17552:                 $credits{$type} = $env{'form.'.$type.'_credits'};
17553:                 $credits{$type} =~ s/[^\d.]+//g;
17554:             }
17555:         }
17556:         if ((ref($domconfig{'coursedefaults'}{'coursecredits'}) ne 'HASH') &&
17557:             ($env{'form.coursecredits'} eq '1')) {
17558:             $changes{'coursecredits'} = 1;
17559:             foreach my $type (keys(%credits)) {
17560:                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
17561:             }
17562:         } else {
17563:             if ($env{'form.coursecredits'} eq '1') {
17564:                 foreach my $type (@types) {
17565:                     unless ($type eq 'community') {
17566:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type} ne $credits{$type}) {
17567:                             $changes{'coursecredits'} = 1;
17568:                         }
17569:                         $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
17570:                     }
17571:                 }
17572:             } elsif (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
17573:                 foreach my $type (@types) {
17574:                     unless ($type eq 'community') {
17575:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type}) {
17576:                             $changes{'coursecredits'} = 1;
17577:                             last;
17578:                         }
17579:                     }
17580:                 }
17581:             }
17582:         }
17583:         if ($env{'form.postsubmit'} eq '1') {
17584:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'on';
17585:             my %currtimeout;
17586:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
17587:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'off') {
17588:                     $changes{'postsubmit'} = 1;
17589:                 }
17590:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
17591:                     %currtimeout = %{$domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}};
17592:                 }
17593:             } else {
17594:                 $changes{'postsubmit'} = 1;
17595:             }
17596:             foreach my $type (@types) {
17597:                 my $timeout = $env{'form.'.$type.'_timeout'};
17598:                 $timeout =~ s/\D//g;
17599:                 if ($timeout == $staticdefaults{'postsubmit'}) {
17600:                     $timeout = '';
17601:                 } elsif (($timeout eq '') || ($timeout =~ /^0+$/)) {
17602:                     $timeout = '0';
17603:                 }
17604:                 unless ($timeout eq '') {
17605:                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type} = $timeout;
17606:                 }
17607:                 if (exists($currtimeout{$type})) {
17608:                     if ($timeout ne $currtimeout{$type}) {
17609:                         $changes{'postsubmit'} = 1;
17610:                     }
17611:                 } elsif ($timeout ne '') {
17612:                     $changes{'postsubmit'} = 1;
17613:                 }
17614:             }
17615:         } else {
17616:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'off';
17617:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
17618:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'on') {
17619:                     $changes{'postsubmit'} = 1;
17620:                 }
17621:             } else {
17622:                 $changes{'postsubmit'} = 1;
17623:             }
17624:         }
17625:     }
17626:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
17627:                                              $dom);
17628:     if ($putresult eq 'ok') {
17629:         if (keys(%changes) > 0) {
17630:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
17631:             if (($changes{'uploadquota'}) || ($changes{'postsubmit'}) ||
17632:                 ($changes{'coursecredits'}) || ($changes{'uselcmath'}) || ($changes{'usejsme'}) ||
17633:                 ($changes{'canclone'}) || ($changes{'mysqltables'}) || ($changes{'texengine'}) ||
17634:                 ($changes{'inline_chem'}) || ($changes{'ltiauth'})) {
17635:                 foreach my $item ('uselcmath','usejsme','inline_chem','texengine','ltiauth') {
17636:                     if ($changes{$item}) {
17637:                         $domdefaults{$item}=$defaultshash{'coursedefaults'}{$item};
17638:                     }
17639:                 }
17640:                 if ($changes{'coursecredits'}) {
17641:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
17642:                         foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'coursecredits'}})) {
17643:                             $domdefaults{$type.'credits'} =
17644:                                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type};
17645:                         }
17646:                     }
17647:                 }
17648:                 if ($changes{'postsubmit'}) {
17649:                     if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
17650:                         $domdefaults{'postsubmit'} = $defaultshash{'coursedefaults'}{'postsubmit'}{'client'};
17651:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
17652:                             foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}})) {
17653:                                 $domdefaults{$type.'postsubtimeout'} =
17654:                                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
17655:                             }
17656:                         }
17657:                     }
17658:                 }
17659:                 if ($changes{'uploadquota'}) {
17660:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
17661:                         foreach my $type (@types) {
17662:                             $domdefaults{$type.'quota'}=$defaultshash{'coursedefaults'}{'uploadquota'}{$type};
17663:                         }
17664:                     }
17665:                 }
17666:                 if ($changes{'canclone'}) {
17667:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
17668:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
17669:                             my @clonecodes = @{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}};
17670:                             if (@clonecodes) {
17671:                                 $domdefaults{'canclone'} = join('+',@clonecodes);
17672:                             }
17673:                         }
17674:                     } else {
17675:                         $domdefaults{'canclone'}=$defaultshash{'coursedefaults'}{'canclone'};
17676:                     }
17677:                 }
17678:                 my $cachetime = 24*60*60;
17679:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
17680:                 if (ref($lastactref) eq 'HASH') {
17681:                     $lastactref->{'domdefaults'} = 1;
17682:                 }
17683:             }
17684:             $resulttext = &mt('Changes made:').'<ul>';
17685:             foreach my $item (sort(keys(%changes))) {
17686:                 if ($item eq 'uselcmath') {
17687:                     if ($env{'form.'.$item} eq '1') {
17688:                         $resulttext .= '<li>'.&mt('Math preview uses LON-CAPA previewer (javascript), if supported by browser.').'</li>';
17689:                     } else {
17690:                         $resulttext .= '<li>'.&mt('Math preview uses DragMath (Java), if supported by client OS.').'</li>';
17691:                     }
17692:                 } elsif ($item eq 'usejsme') {
17693:                     if ($env{'form.'.$item} eq '1') {
17694:                         $resulttext .= '<li>'.&mt('Molecule editor uses JSME (HTML5), if supported by browser.').'</li>';
17695:                     } else {
17696:                         $resulttext .= '<li>'.&mt('Molecule editor uses JME (Java), if supported by client OS.').'</li>';
17697:                     }
17698:                 } elsif ($item eq 'inline_chem') {
17699:                     if ($env{'form.'.$item} eq '1') {
17700:                         $resulttext .= '<li>'.&mt('Chemical Reaction Response uses inline previewer').'</li>';
17701:                     } else {
17702:                         $resulttext .= '<li>'.&mt('Chemical Reaction Response uses pop-up previewer').'</li>';
17703:                     }
17704:                 } elsif ($item eq 'texengine') {
17705:                     if ($defaultshash{'coursedefaults'}{'texengine'} ne '') {
17706:                         $resulttext .= '<li>'.&mt('Default method to display mathematics set to: "[_1]"',
17707:                                                   $texoptions{$defaultshash{'coursedefaults'}{'texengine'}}).'</li>';
17708:                     }
17709:                 } elsif ($item eq 'anonsurvey_threshold') {
17710:                     $resulttext .= '<li>'.&mt('Responder count required for display of anonymous survey submissions set to [_1].',$defaultshash{'coursedefaults'}{'anonsurvey_threshold'}).'</li>';
17711:                 } elsif ($item eq 'uploadquota') {
17712:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
17713:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded to a course/community via Course Editor set as follows:').'<ul>'.
17714:                                        '<li>'.&mt('Official courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'official'}.'</b>').'</li>'.
17715:                                        '<li>'.&mt('Unofficial courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'unofficial'}.'</b>').'</li>'.
17716:                                        '<li>'.&mt('Textbook courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'textbook'}.'</b>').'</li>'.
17717: 
17718:                                        '<li>'.&mt('Communities: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'community'}.'</b>').'</li>'.
17719:                                        '</ul>'.
17720:                                        '</li>';
17721:                     } else {
17722:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded via Course Editor remains default: [_1] MB',$staticdefaults{'uploadquota'}).'</li>';
17723:                     }
17724:                 } elsif ($item eq 'mysqltables') {
17725:                     if (ref($defaultshash{'coursedefaults'}{'mysqltables'}) eq 'HASH') {
17726:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver').'<ul>'.
17727:                                        '<li>'.&mt('Official courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'official'}.'</b>').'</li>'.
17728:                                        '<li>'.&mt('Unofficial courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'unofficial'}.'</b>').'</li>'.
17729:                                        '<li>'.&mt('Textbook courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'textbook'}.'</b>').'</li>'.
17730:                                        '<li>'.&mt('Communities: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'community'}.'</b>').'</li>'.
17731:                                        '</ul>'.
17732:                                        '</li>';
17733:                     } else {
17734:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver remains default: [_1] s',$staticdefaults{'uploadquota'}).'</li>';
17735:                     }
17736:                 } elsif ($item eq 'postsubmit') {
17737:                     if ($domdefaults{'postsubmit'} eq 'off') {
17738:                         $resulttext .= '<li>'.&mt('Submit button(s) remain enabled on page after student makes submission.');
17739:                     } else {
17740:                         $resulttext .= '<li>'.&mt('Submit button(s) disabled on page after student makes submission').'; ';
17741:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
17742:                             $resulttext .= &mt('durations:').'<ul>';
17743:                             foreach my $type (@types) {
17744:                                 $resulttext .= '<li>';
17745:                                 my $timeout;
17746:                                 if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
17747:                                     $timeout = $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
17748:                                 }
17749:                                 my $display;
17750:                                 if ($timeout eq '0') {
17751:                                     $display = &mt('unlimited');
17752:                                 } elsif ($timeout eq '') {
17753:                                     $display = &mt('[quant,_1,second] (default)',$staticdefaults{'postsubmit'});
17754:                                 } else {
17755:                                     $display = &mt('[quant,_1,second]',$timeout);
17756:                                 }
17757:                                 if ($type eq 'community') {
17758:                                     $resulttext .= &mt('Communities');
17759:                                 } elsif ($type eq 'official') {
17760:                                     $resulttext .= &mt('Official courses');
17761:                                 } elsif ($type eq 'unofficial') {
17762:                                     $resulttext .= &mt('Unofficial courses');
17763:                                 } elsif ($type eq 'textbook') {
17764:                                     $resulttext .= &mt('Textbook courses');
17765:                                 }
17766:                                 $resulttext .= ' -- '.$display.'</li>';
17767:                             }
17768:                             $resulttext .= '</ul>';
17769:                         }
17770:                         $resulttext .= '</li>';
17771:                     }
17772:                 } elsif ($item eq 'coursecredits') {
17773:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
17774:                         if (($domdefaults{'officialcredits'} eq '') &&
17775:                             ($domdefaults{'unofficialcredits'} eq '') &&
17776:                             ($domdefaults{'textbookcredits'} eq '')) {
17777:                             $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
17778:                         } else {
17779:                             $resulttext .= '<li>'.&mt('Student credits can be set per course by a Domain Coordinator, with the following defaults applying:').'<ul>'.
17780:                                            '<li>'.&mt('Official courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'official'}).'</li>'.
17781:                                            '<li>'.&mt('Unofficial courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'unofficial'}).'</li>'.
17782:                                            '<li>'.&mt('Textbook courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'textbook'}).'</li>'.
17783:                                            '</ul>'.
17784:                                            '</li>';
17785:                         }
17786:                     } else {
17787:                         $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
17788:                     }
17789:                 } elsif ($item eq 'canclone') {
17790:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
17791:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
17792:                             my $clonecodes = join(' '.&mt('and').' ',@{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}});
17793:                             $resulttext .= '<li>'.&mt('By default, official courses can be cloned from existing courses with the same: [_1]','<b>'.$clonecodes.'</b>').'</li>';
17794:                         }
17795:                     } elsif ($defaultshash{'coursedefaults'}{'canclone'} eq 'domain') {
17796:                         $resulttext .= '<li>'.&mt('By default, a course requester can clone any course from his/her domain.').'</li>';
17797:                     } else {
17798:                         $resulttext .= '<li>'.&mt('By default, only course owner and coordinators may clone a course.').'</li>';
17799:                     }
17800:                 } elsif ($item eq 'ltiauth') {
17801:                     if ($env{'form.'.$item} eq '1') {
17802:                         $resulttext .= '<li>'.&mt('LTI launch of deep-linked URL need not require re-authentication').'</li>';
17803:                     } else {
17804:                         $resulttext .= '<li>'.&mt('LTI launch of deep-linked URL will require re-authentication').'</li>';
17805:                     }
17806:                 }
17807:             }
17808:             $resulttext .= '</ul>';
17809:         } else {
17810:             $resulttext = &mt('No changes made to course defaults');
17811:         }
17812:     } else {
17813:         $resulttext = '<span class="LC_error">'.
17814:             &mt('An error occurred: [_1]',$putresult).'</span>';
17815:     }
17816:     return $resulttext;
17817: }
17818: 
17819: sub modify_selfenrollment {
17820:     my ($dom,$lastactref,%domconfig) = @_;
17821:     my ($resulttext,$errors,%changes,%selfenrollhash,%ordered);
17822:     my @types = ('official','unofficial','community','textbook');
17823:     my %titles = &tool_titles();
17824:     my %descs = &Apache::lonuserutils::selfenroll_default_descs();
17825:     ($ordered{'admin'},my $titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
17826:     $ordered{'default'} = ['types','registered','approval','limit'];
17827: 
17828:     my (%roles,%shown,%toplevel);
17829:     $roles{'0'} = &Apache::lonnet::plaintext('dc');
17830: 
17831:     if (ref($domconfig{'selfenrollment'}) ne 'HASH') {
17832:         if ($domconfig{'selfenrollment'} eq '') {
17833:             $domconfig{'selfenrollment'} = {};
17834:         }
17835:     }
17836:     %toplevel = (
17837:                   admin      => 'Configuration Rights',
17838:                   default    => 'Default settings',
17839:                   validation => 'Validation of self-enrollment requests',
17840:                 );
17841:     my ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
17842: 
17843:     if (ref($ordered{'admin'}) eq 'ARRAY') {
17844:         foreach my $item (@{$ordered{'admin'}}) {
17845:             foreach my $type (@types) {
17846:                 if ($env{'form.selfenrolladmin_'.$item.'_'.$type}) {
17847:                     $selfenrollhash{'admin'}{$type}{$item} = 1;
17848:                 } else {
17849:                     $selfenrollhash{'admin'}{$type}{$item} = 0;
17850:                 }
17851:                 if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
17852:                     if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
17853:                         if ($selfenrollhash{'admin'}{$type}{$item} ne
17854:                             $domconfig{'selfenrollment'}{'admin'}{$type}{$item})  {
17855:                             push(@{$changes{'admin'}{$type}},$item);
17856:                         }
17857:                     } else {
17858:                         if (!$selfenrollhash{'admin'}{$type}{$item}) {
17859:                             push(@{$changes{'admin'}{$type}},$item);
17860:                         }
17861:                     }
17862:                 } elsif (!$selfenrollhash{'admin'}{$type}{$item}) {
17863:                     push(@{$changes{'admin'}{$type}},$item);
17864:                 }
17865:             }
17866:         }
17867:     }
17868: 
17869:     foreach my $item (@{$ordered{'default'}}) {
17870:         foreach my $type (@types) {
17871:             my $value = $env{'form.selfenrolldefault_'.$item.'_'.$type};
17872:             if ($item eq 'types') {
17873:                 unless (($value eq 'all') || ($value eq 'dom')) {
17874:                     $value = '';
17875:                 }
17876:             } elsif ($item eq 'registered') {
17877:                 unless ($value eq '1') {
17878:                     $value = 0;
17879:                 }
17880:             } elsif ($item eq 'approval') {
17881:                 unless ($value =~ /^[012]$/) {
17882:                     $value = 0;
17883:                 }
17884:             } else {
17885:                 unless (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
17886:                     $value = 'none';
17887:                 }
17888:             }
17889:             $selfenrollhash{'default'}{$type}{$item} = $value;
17890:             if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
17891:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
17892:                     if ($selfenrollhash{'default'}{$type}{$item} ne
17893:                          $domconfig{'selfenrollment'}{'default'}{$type}{$item})  {
17894:                          push(@{$changes{'default'}{$type}},$item);
17895:                     }
17896:                 } else {
17897:                     push(@{$changes{'default'}{$type}},$item);
17898:                 }
17899:             } else {
17900:                 push(@{$changes{'default'}{$type}},$item);
17901:             }
17902:             if ($item eq 'limit') {
17903:                 if (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
17904:                     $env{'form.selfenrolldefault_cap_'.$type} =~ s/\D//g;
17905:                     if ($env{'form.selfenrolldefault_cap_'.$type} ne '') {
17906:                         $selfenrollhash{'default'}{$type}{'cap'} = $env{'form.selfenrolldefault_cap_'.$type};
17907:                     }
17908:                 } else {
17909:                     $selfenrollhash{'default'}{$type}{'cap'} = '';
17910:                 }
17911:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
17912:                     if ($selfenrollhash{'default'}{$type}{'cap'} ne
17913:                          $domconfig{'selfenrollment'}{'admin'}{$type}{'cap'})  {
17914:                          push(@{$changes{'default'}{$type}},'cap');
17915:                     }
17916:                 } elsif ($selfenrollhash{'default'}{$type}{'cap'} ne '') {
17917:                     push(@{$changes{'default'}{$type}},'cap');
17918:                 }
17919:             }
17920:         }
17921:     }
17922: 
17923:     foreach my $item (@{$itemsref}) {
17924:         if ($item eq 'fields') {
17925:             my @changed;
17926:             @{$selfenrollhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.selfenroll_validation_'.$item);
17927:             if (@{$selfenrollhash{'validation'}{$item}} > 0) {
17928:                 @{$selfenrollhash{'validation'}{$item}} = sort(@{$selfenrollhash{'validation'}{$item}});
17929:             }
17930:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
17931:                 if (ref($domconfig{'selfenrollment'}{'validation'}{$item}) eq 'ARRAY') {
17932:                     @changed = &Apache::loncommon::compare_arrays($selfenrollhash{'validation'}{$item},
17933:                                                                   $domconfig{'selfenrollment'}{'validation'}{$item});
17934:                 } else {
17935:                     @changed = @{$selfenrollhash{'validation'}{$item}};
17936:                 }
17937:             } else {
17938:                 @changed = @{$selfenrollhash{'validation'}{$item}};
17939:             }
17940:             if (@changed) {
17941:                 if ($selfenrollhash{'validation'}{$item}) { 
17942:                     $changes{'validation'}{$item} = join(', ',@{$selfenrollhash{'validation'}{$item}});
17943:                 } else {
17944:                     $changes{'validation'}{$item} = &mt('None');
17945:                 }
17946:             }
17947:         } else {
17948:             $selfenrollhash{'validation'}{$item} = $env{'form.selfenroll_validation_'.$item};
17949:             if ($item eq 'markup') {
17950:                if ($env{'form.selfenroll_validation_'.$item}) {
17951:                    $env{'form.selfenroll_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
17952:                }
17953:             }
17954:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
17955:                 if ($domconfig{'selfenrollment'}{'validation'}{$item} ne $selfenrollhash{'validation'}{$item}) {
17956:                     $changes{'validation'}{$item} = $selfenrollhash{'validation'}{$item};
17957:                 }
17958:             }
17959:         }
17960:     }
17961: 
17962:     my $putresult = &Apache::lonnet::put_dom('configuration',{'selfenrollment' => \%selfenrollhash},
17963:                                              $dom);
17964:     if ($putresult eq 'ok') {
17965:         if (keys(%changes) > 0) {
17966:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
17967:             $resulttext = &mt('Changes made:').'<ul>';
17968:             foreach my $key ('admin','default','validation') {
17969:                 if (ref($changes{$key}) eq 'HASH') {
17970:                     $resulttext .= '<li>'.$toplevel{$key}.'<ul>';
17971:                     if ($key eq 'validation') {
17972:                         foreach my $item (@{$itemsref}) {
17973:                             if (exists($changes{$key}{$item})) {
17974:                                 if ($item eq 'markup') {
17975:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
17976:                                                               '<br /><pre>'.$changes{$key}{$item}.'</pre>').'</li>';
17977:                                 } else {  
17978:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
17979:                                                               '<b>'.$changes{$key}{$item}.'</b>').'</li>';
17980:                                 }
17981:                             }
17982:                         }
17983:                     } else {
17984:                         foreach my $type (@types) {
17985:                             if ($type eq 'community') {
17986:                                 $roles{'1'} = &mt('Community personnel');
17987:                             } else {
17988:                                 $roles{'1'} = &mt('Course personnel');
17989:                             }
17990:                             if (ref($changes{$key}{$type}) eq 'ARRAY') {
17991:                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') {
17992:                                     if ($key eq 'admin') {
17993:                                         my @mgrdc = ();
17994:                                         if (ref($ordered{$key}) eq 'ARRAY') {
17995:                                             foreach my $item (@{$ordered{'admin'}}) {
17996:                                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') { 
17997:                                                     if ($selfenrollhash{$key}{$type}{$item} eq '0') {
17998:                                                         push(@mgrdc,$item);
17999:                                                     }
18000:                                                 }
18001:                                             }
18002:                                             if (@mgrdc) {
18003:                                                 $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
18004:                                             } else {
18005:                                                 delete($domdefaults{$type.'selfenrolladmdc'});
18006:                                             }
18007:                                         }
18008:                                     } else {
18009:                                         if (ref($ordered{$key}) eq 'ARRAY') {
18010:                                             foreach my $item (@{$ordered{$key}}) {
18011:                                                 if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
18012:                                                     $domdefaults{$type.'selfenroll'.$item} =
18013:                                                         $selfenrollhash{$key}{$type}{$item};
18014:                                                 }
18015:                                             }
18016:                                         }
18017:                                     }
18018:                                 }
18019:                                 $resulttext .= '<li>'.$titles{$type}.'<ul>';
18020:                                 foreach my $item (@{$ordered{$key}}) {
18021:                                     if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
18022:                                         $resulttext .= '<li>';
18023:                                         if ($key eq 'admin') {
18024:                                             $resulttext .= &mt('[_1] -- management by: [_2]',$titlesref->{$item},
18025:                                                                '<b>'.$roles{$selfenrollhash{'admin'}{$type}{$item}}.'</b>');
18026:                                         } else {
18027:                                             $resulttext .= &mt('[_1] set to: [_2]',$titlesref->{$item},
18028:                                                                '<b>'.$descs{$item}{$selfenrollhash{'default'}{$type}{$item}}.'</b>');
18029:                                         }
18030:                                         $resulttext .= '</li>';
18031:                                     }
18032:                                 }
18033:                                 $resulttext .= '</ul></li>';
18034:                             }
18035:                         }
18036:                         $resulttext .= '</ul></li>'; 
18037:                     }
18038:                 }
18039:             }
18040:             if ((exists($changes{'admin'})) || (exists($changes{'default'}))) {
18041:                 my $cachetime = 24*60*60;
18042:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
18043:                 if (ref($lastactref) eq 'HASH') {
18044:                     $lastactref->{'domdefaults'} = 1;
18045:                 }
18046:             }
18047:             $resulttext .= '</ul>';
18048:         } else {
18049:             $resulttext = &mt('No changes made to self-enrollment settings');
18050:         }
18051:     } else {
18052:         $resulttext = '<span class="LC_error">'.
18053:             &mt('An error occurred: [_1]',$putresult).'</span>';
18054:     }
18055:     return $resulttext;
18056: }
18057: 
18058: sub modify_wafproxy {
18059:     my ($dom,$action,$lastactref,%domconfig) = @_;
18060:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
18061:     my (%othercontrol,%canset,%values,%curralias,%currsaml,%currvalue,@warnings,
18062:         %wafproxy,%changes,%expirecache,%expiresaml);
18063:     foreach my $server (sort(keys(%servers))) {
18064:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
18065:         if ($serverhome eq $server) {
18066:             my $serverdom = &Apache::lonnet::host_domain($server);
18067:             if ($serverdom eq $dom) {
18068:                 $canset{$server} = 1;
18069:             }
18070:         }
18071:     }
18072:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
18073:         %{$values{$dom}} = ();
18074:         if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
18075:             %curralias = %{$domconfig{'wafproxy'}{'alias'}};
18076:         }
18077:         if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
18078:             %currsaml = %{$domconfig{'wafproxy'}{'saml'}};
18079:         }
18080:         foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
18081:             $currvalue{$item} = $domconfig{'wafproxy'}{$item};
18082:         }
18083:     }
18084:     my $output;
18085:     if (keys(%canset)) {
18086:         %{$wafproxy{'alias'}} = ();
18087:         %{$wafproxy{'saml'}} = ();
18088:         foreach my $key (sort(keys(%canset))) {
18089:             if ($env{'form.wafproxy_'.$dom}) {
18090:                 $wafproxy{'alias'}{$key} = $env{'form.wafproxy_alias_'.$key};
18091:                 $wafproxy{'alias'}{$key} =~ s/^\s+|\s+$//g;
18092:                 if ($wafproxy{'alias'}{$key} ne $curralias{$key}) {
18093:                     $changes{'alias'} = 1;
18094:                 }
18095:                 if ($env{'form.wafproxy_alias_saml_'.$key}) {
18096:                     $wafproxy{'saml'}{$key} = 1;
18097:                 }
18098:                 if ($wafproxy{'saml'}{$key} ne $currsaml{$key}) {
18099:                     $changes{'saml'} = 1;
18100:                 }
18101:             } else {
18102:                 $wafproxy{'alias'}{$key} = '';
18103:                 $wafproxy{'saml'}{$key} = '';
18104:                 if ($curralias{$key}) {
18105:                     $changes{'alias'} = 1;
18106:                 }
18107:                 if ($currsaml{$key}) {
18108:                     $changes{'saml'} = 1;
18109:                 }
18110:             }
18111:             if ($wafproxy{'alias'}{$key} eq '') {
18112:                 if ($curralias{$key}) {
18113:                     $expirecache{$key} = 1;
18114:                 }
18115:                 delete($wafproxy{'alias'}{$key});
18116:             }
18117:             if ($wafproxy{'saml'}{$key} eq '') {
18118:                 if ($currsaml{$key}) {
18119:                     $expiresaml{$key} = 1;
18120:                 }
18121:                 delete($wafproxy{'saml'}{$key});
18122:             }
18123:         }
18124:         unless (keys(%{$wafproxy{'alias'}})) {
18125:             delete($wafproxy{'alias'});
18126:         }
18127:         unless (keys(%{$wafproxy{'saml'}})) {
18128:             delete($wafproxy{'saml'});
18129:         }
18130:         # Localization for values in %warn occurs in &mt() calls separately.
18131:         my %warn = (
18132:                      trusted => 'trusted IP range(s)',
18133:                      vpnint => 'internal IP range(s) for VPN sessions(s)',
18134:                      vpnext => 'IP range(s) for backend WAF connections',
18135:                    );
18136:         foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
18137:             my $possible = $env{'form.wafproxy_'.$item};
18138:             $possible =~ s/^\s+|\s+$//g;
18139:             if ($possible ne '') {
18140:                 if ($item eq 'remoteip') {
18141:                     if ($possible =~ /^[mhn]$/) {
18142:                         $wafproxy{$item} = $possible;
18143:                     }
18144:                 } elsif ($item eq 'ipheader') {
18145:                     if ($wafproxy{'remoteip'} eq 'h') {
18146:                         $wafproxy{$item} = $possible;
18147:                     }
18148:                 } elsif ($item eq 'sslopt') {
18149:                     if ($possible =~ /^0|1$/) {
18150:                         $wafproxy{$item} = $possible;
18151:                     }
18152:                 } else {
18153:                     my (@ok,$count);
18154:                     if (($item eq 'vpnint') || ($item eq 'vpnext')) {
18155:                         unless ($env{'form.wafproxy_vpnaccess'}) {
18156:                             $possible = '';
18157:                         }
18158:                     } elsif ($item eq 'trusted') {
18159:                         unless ($wafproxy{'remoteip'} eq 'h') {
18160:                             $possible = '';
18161:                         }
18162:                     }
18163:                     unless ($possible eq '') {
18164:                         $possible =~ s/[\r\n]+/\s/g;
18165:                         $possible =~ s/\s*-\s*/-/g;
18166:                         $possible =~ s/\s+/,/g;
18167:                         $possible =~ s/,+/,/g;
18168:                     }
18169:                     $count = 0;
18170:                     if ($possible ne '') {
18171:                         foreach my $poss (split(/\,/,$possible)) {
18172:                             $count ++;
18173:                             $poss = &validate_ip_pattern($poss);
18174:                             if ($poss ne '') {
18175:                                 push(@ok,$poss);
18176:                             }
18177:                         }
18178:                         my $diff = $count - scalar(@ok);
18179:                         if ($diff) {
18180:                             push(@warnings,'<li>'.
18181:                                  &mt('[quant,_1,IP] invalid and excluded from saved value for [_2]',
18182:                                      $diff,$warn{$item}).
18183:                                  '</li>');
18184:                         }
18185:                         if (@ok) {
18186:                             my @cidr_list;
18187:                             foreach my $item (@ok) {
18188:                                 @cidr_list = &Net::CIDR::cidradd($item,@cidr_list);
18189:                             }
18190:                             $wafproxy{$item} = join(',',@cidr_list);
18191:                         }
18192:                     }
18193:                 }
18194:                 if ($wafproxy{$item} ne $currvalue{$item}) {
18195:                     $changes{$item} = 1;
18196:                 }
18197:             } elsif ($currvalue{$item}) {
18198:                 $changes{$item} = 1;
18199:             }
18200:         }
18201:     } else {
18202:         if (keys(%curralias)) {
18203:             $changes{'alias'} = 1;
18204:         }
18205:         if (keys(%currsaml)) {
18206:             $changes{'saml'} = 1;
18207:         }
18208:         if (keys(%currvalue)) {
18209:             foreach my $key (keys(%currvalue)) {
18210:                 $changes{$key} = 1;
18211:             }
18212:         }
18213:     }
18214:     if (keys(%changes)) {
18215:         my %defaultshash = (
18216:                               wafproxy => \%wafproxy,
18217:                            );
18218:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
18219:                                                  $dom);
18220:         if ($putresult eq 'ok') {
18221:             my $cachetime = 24*60*60;
18222:             my (%domdefaults,$updatedomdefs);
18223:             foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
18224:                 if ($changes{$item}) {
18225:                     unless ($updatedomdefs) {
18226:                         %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
18227:                         $updatedomdefs = 1;
18228:                     }
18229:                     if ($wafproxy{$item}) {
18230:                         $domdefaults{'waf_'.$item} = $wafproxy{$item};
18231:                     } elsif (exists($domdefaults{'waf_'.$item})) {
18232:                         delete($domdefaults{'waf_'.$item});
18233:                     }
18234:                 }
18235:             }
18236:             if ($updatedomdefs) {
18237:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
18238:                 if (ref($lastactref) eq 'HASH') {
18239:                     $lastactref->{'domdefaults'} = 1;
18240:                 }
18241:             }
18242:             if ((exists($wafproxy{'alias'})) || (keys(%expirecache))) {
18243:                 my %updates = %expirecache;
18244:                 foreach my $key (keys(%expirecache)) {
18245:                     &Apache::lonnet::devalidate_cache_new('proxyalias',$key);
18246:                 }
18247:                 if (ref($wafproxy{'alias'}) eq 'HASH') {
18248:                     my $cachetime = 24*60*60;
18249:                     foreach my $key (keys(%{$wafproxy{'alias'}})) {
18250:                         $updates{$key} = 1;
18251:                         &Apache::lonnet::do_cache_new('proxyalias',$key,$wafproxy{'alias'}{$key},
18252:                                                       $cachetime);
18253:                     }
18254:                 }
18255:                 if (ref($lastactref) eq 'HASH') {
18256:                     $lastactref->{'proxyalias'} = \%updates;
18257:                 }
18258:             }
18259:             if ((exists($wafproxy{'saml'})) || (keys(%expiresaml))) {
18260:                 my %samlupdates = %expiresaml;
18261:                 foreach my $key (keys(%expiresaml)) {
18262:                     &Apache::lonnet::devalidate_cache_new('proxysaml',$key);
18263:                 }
18264:                 if (ref($wafproxy{'saml'}) eq 'HASH') {
18265:                     my $cachetime = 24*60*60;
18266:                     foreach my $key (keys(%{$wafproxy{'saml'}})) {
18267:                         $samlupdates{$key} = 1;
18268:                         &Apache::lonnet::do_cache_new('proxysaml',$key,$wafproxy{'saml'}{$key},
18269:                                                       $cachetime);
18270:                     }
18271:                 }
18272:                 if (ref($lastactref) eq 'HASH') {
18273:                     $lastactref->{'proxysaml'} = \%samlupdates;
18274:                 }
18275:             }
18276:             $output = &mt('Changes were made to Web Application Firewall/Reverse Proxy').'<ul>';
18277:             foreach my $item ('alias','saml','remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
18278:                 if ($changes{$item}) {
18279:                     if ($item eq 'alias') {
18280:                         my $numaliased = 0;
18281:                         if (ref($wafproxy{'alias'}) eq 'HASH') {
18282:                             my $shown;
18283:                             if (keys(%{$wafproxy{'alias'}})) {
18284:                                 foreach my $server (sort(keys(%{$wafproxy{'alias'}}))) {
18285:                                     $shown .= '<li>'.&mt('[_1] aliased by [_2]',
18286:                                                          &Apache::lonnet::hostname($server),
18287:                                                          $wafproxy{'alias'}{$server}).'</li>';
18288:                                     $numaliased ++;
18289:                                 }
18290:                                 if ($numaliased) {
18291:                                     $output .= '<li>'.&mt('Aliases for hostnames set to: [_1]',
18292:                                                           '<ul>'.$shown.'</ul>').'</li>';
18293:                                 }
18294:                             }
18295:                         }
18296:                         unless ($numaliased) {
18297:                             $output .= '<li>'.&mt('Aliases deleted for hostnames').'</li>';
18298:                         }
18299:                     } elsif ($item eq 'saml') {
18300:                         my $shown;
18301:                         if (ref($wafproxy{'saml'}) eq 'HASH') {
18302:                             if (keys(%{$wafproxy{'saml'}})) {
18303:                                 $shown = join(', ',sort(keys(%{$wafproxy{'saml'}})));
18304:                             }
18305:                         }
18306:                         if ($shown) {
18307:                             $output .= '<li>'.&mt('Alias used by SSO Auth for: [_1]',
18308:                                                   $shown).'</li>';
18309:                         } else {
18310:                             $output .= '<li>'.&mt('No alias used for SSO Auth').'</li>';
18311:                         }
18312:                     } else {
18313:                         if ($item eq 'remoteip') {
18314:                             my %ip_methods = &remoteip_methods();
18315:                             if ($wafproxy{$item} =~ /^[mh]$/) {
18316:                                 $output .= '<li>'.&mt("Method for determining user's IP set to: [_1]",
18317:                                                       $ip_methods{$wafproxy{$item}}).'</li>';
18318:                             } else {
18319:                                 if (($env{'form.wafproxy_'.$dom}) && (ref($wafproxy{'alias'}) eq 'HASH')) {
18320:                                     $output .= '<li>'.&mt("No method in use to get user's real IP (will report IP used by WAF).").
18321:                                                '</li>';
18322:                                 } else {
18323:                                     $output .= '<li>'.&mt('WAF/Reverse Proxy not in use').'</li>';
18324:                                 }
18325:                             }
18326:                         } elsif ($item eq 'ipheader') {
18327:                             if ($wafproxy{$item}) {
18328:                                 $output .= '<li>'.&mt('Request header with remote IP set to: [_1]',
18329:                                                       $wafproxy{$item}).'</li>';
18330:                             } else {
18331:                                 $output .= '<li>'.&mt('Request header with remote IP deleted').'</li>';
18332:                             }
18333:                         } elsif ($item eq 'trusted') {
18334:                             if ($wafproxy{$item}) {
18335:                                 $output .= '<li>'.&mt('Trusted IP range(s) set to: [_1]',
18336:                                                       $wafproxy{$item}).'</li>';
18337:                             } else {
18338:                                 $output .= '<li>'.&mt('Trusted IP range(s) deleted').'</li>';
18339:                             }
18340:                         } elsif ($item eq 'vpnint') {
18341:                             if ($wafproxy{$item}) {
18342:                                 $output .= '<li>'.&mt('Internal IP Range(s) for VPN sessions set to: [_1]',
18343:                                                        $wafproxy{$item}).'</li>';
18344:                             } else {
18345:                                 $output .= '<li>'.&mt('Internal IP Range(s) for VPN sessions deleted').'</li>';
18346:                             }
18347:                         } elsif ($item eq 'vpnext') {
18348:                             if ($wafproxy{$item}) {
18349:                                 $output .= '<li>'.&mt('IP Range(s) for backend WAF connections set to: [_1]',
18350:                                                        $wafproxy{$item}).'</li>';
18351:                             } else {
18352:                                 $output .= '<li>'.&mt('IP Range(s) for backend WAF connections deleted').'</li>';
18353:                             }
18354:                         } elsif ($item eq 'sslopt') {
18355:                             if ($wafproxy{$item}) {
18356:                                 $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>';
18357:                             } else {
18358:                                 $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>';
18359:                             }
18360:                         }
18361:                     }
18362:                 }
18363:             }
18364:         } else {
18365:             $output = '<span class="LC_error">'.
18366:                       &mt('An error occurred: [_1]',$putresult).'</span>';
18367:         }
18368:     } elsif (keys(%canset)) {
18369:         $output = &mt('No changes made to Web Application Firewall/Reverse Proxy settings');
18370:     }
18371:     if (@warnings) {
18372:         $output .= '<br />'.&mt('Warnings:').'<ul>'.
18373:                        join("\n",@warnings).'</ul>';
18374:     }
18375:     return $output;
18376: }
18377: 
18378: sub validate_ip_pattern {
18379:     my ($pattern) = @_;
18380:     if ($pattern =~ /^([^-]+)\-([^-]+)$/) {
18381:         my ($start,$end) = ($1,$2);
18382:         if ((&Net::CIDR::cidrvalidate($start)) && (&Net::CIDR::cidrvalidate($end))) {
18383:             if (($start !~ m{/}) && ($end !~ m{/})) {
18384:                 return $start.'-'.$end;
18385:             }
18386:         }
18387:     } elsif ($pattern ne '') {
18388:         $pattern = &Net::CIDR::cidrvalidate($pattern);
18389:         if ($pattern ne '') {
18390:             return $pattern;
18391:         }
18392:     }
18393:     return;
18394: }
18395: 
18396: sub modify_usersessions {
18397:     my ($dom,$lastactref,%domconfig) = @_;
18398:     my @hostingtypes = ('version','excludedomain','includedomain');
18399:     my @offloadtypes = ('primary','default');
18400:     my %types = (
18401:                   remote => \@hostingtypes,
18402:                   hosted => \@hostingtypes,
18403:                   spares => \@offloadtypes,
18404:                 );
18405:     my @prefixes = ('remote','hosted','spares');
18406:     my @lcversions = &Apache::lonnet::all_loncaparevs();
18407:     my (%by_ip,%by_location,@intdoms);
18408:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location);
18409:     my @locations = sort(keys(%by_location));
18410:     my (%defaultshash,%changes);
18411:     foreach my $prefix (@prefixes) {
18412:         $defaultshash{'usersessions'}{$prefix} = {};
18413:     }
18414:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
18415:     my $resulttext;
18416:     my %iphost = &Apache::lonnet::get_iphost();
18417:     foreach my $prefix (@prefixes) {
18418:         next if ($prefix eq 'spares');
18419:         foreach my $type (@{$types{$prefix}}) {
18420:             my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
18421:             if ($type eq 'version') {
18422:                 my $value = $env{'form.'.$prefix.'_'.$type};
18423:                 my $okvalue;
18424:                 if ($value ne '') {
18425:                     if (grep(/^\Q$value\E$/,@lcversions)) {
18426:                         $okvalue = $value;
18427:                     }
18428:                 }
18429:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
18430:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
18431:                         if ($domconfig{'usersessions'}{$prefix}{$type} ne '') {
18432:                             if ($inuse == 0) {
18433:                                 $changes{$prefix}{$type} = 1;
18434:                             } else {
18435:                                 if ($okvalue ne $domconfig{'usersessions'}{$prefix}{$type}) {
18436:                                     $changes{$prefix}{$type} = 1;
18437:                                 }
18438:                                 if ($okvalue ne '') {
18439:                                     $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
18440:                                 } 
18441:                             }
18442:                         } else {
18443:                             if (($inuse == 1) && ($okvalue ne '')) {
18444:                                 $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
18445:                                 $changes{$prefix}{$type} = 1;
18446:                             }
18447:                         }
18448:                     } else {
18449:                         if (($inuse == 1) && ($okvalue ne '')) {
18450:                             $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
18451:                             $changes{$prefix}{$type} = 1;
18452:                         }
18453:                     }
18454:                 } else {
18455:                     if (($inuse == 1) && ($okvalue ne '')) {
18456:                         $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
18457:                         $changes{$prefix}{$type} = 1;
18458:                     }
18459:                 }
18460:             } else {
18461:                 my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
18462:                 my @okvals;
18463:                 foreach my $val (@vals) {
18464:                     if ($val =~ /:/) {
18465:                         my @items = split(/:/,$val);
18466:                         foreach my $item (@items) {
18467:                             if (ref($by_location{$item}) eq 'ARRAY') {
18468:                                 push(@okvals,$item);
18469:                             }
18470:                         }
18471:                     } else {
18472:                         if (ref($by_location{$val}) eq 'ARRAY') {
18473:                             push(@okvals,$val);
18474:                         }
18475:                     }
18476:                 }
18477:                 @okvals = sort(@okvals);
18478:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
18479:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
18480:                         if (ref($domconfig{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
18481:                             if ($inuse == 0) {
18482:                                 $changes{$prefix}{$type} = 1; 
18483:                             } else {
18484:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
18485:                                 my @changed = &Apache::loncommon::compare_arrays($domconfig{'usersessions'}{$prefix}{$type},$defaultshash{'usersessions'}{$prefix}{$type});
18486:                                 if (@changed > 0) {
18487:                                     $changes{$prefix}{$type} = 1;
18488:                                 }
18489:                             }
18490:                         } else {
18491:                             if ($inuse == 1) {
18492:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
18493:                                 $changes{$prefix}{$type} = 1;
18494:                             }
18495:                         } 
18496:                     } else {
18497:                         if ($inuse == 1) {
18498:                             $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
18499:                             $changes{$prefix}{$type} = 1;
18500:                         }
18501:                     }
18502:                 } else {
18503:                     if ($inuse == 1) {
18504:                         $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
18505:                         $changes{$prefix}{$type} = 1;
18506:                     }
18507:                 }
18508:             }
18509:         }
18510:     }
18511: 
18512:     my @alldoms = &Apache::lonnet::all_domains();
18513:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
18514:     my %spareid = &current_offloads_to($dom,$domconfig{'usersessions'},\%servers);
18515:     my $savespares;
18516: 
18517:     foreach my $lonhost (sort(keys(%servers))) {
18518:         my $serverhomeID =
18519:             &Apache::lonnet::get_server_homeID($servers{$lonhost});
18520:         my $serverhostname = &Apache::lonnet::hostname($lonhost);
18521:         $defaultshash{'usersessions'}{'spares'}{$lonhost} = {};
18522:         my %spareschg;
18523:         foreach my $type (@{$types{'spares'}}) {
18524:             my @okspares;
18525:             my @checked = &Apache::loncommon::get_env_multiple('form.spare_'.$type.'_'.$lonhost);
18526:             foreach my $server (@checked) {
18527:                 if (&Apache::lonnet::hostname($server) ne '') {
18528:                     unless (&Apache::lonnet::hostname($server) eq $serverhostname) {
18529:                         unless (grep(/^\Q$server\E$/,@okspares)) {
18530:                             push(@okspares,$server);
18531:                         }
18532:                     }
18533:                 }
18534:             }
18535:             my $new = $env{'form.newspare_'.$type.'_'.$lonhost};
18536:             my $newspare;
18537:             if (($new ne '') && (&Apache::lonnet::hostname($new))) {
18538:                 unless (&Apache::lonnet::hostname($new) eq $serverhostname) {
18539:                     $newspare = $new;
18540:                 }
18541:             }
18542:             my @spares;
18543:             if (($newspare ne '') && (!grep(/^\Q$newspare\E$/,@okspares))) {
18544:                 @spares = sort(@okspares,$newspare);
18545:             } else {
18546:                 @spares = sort(@okspares);
18547:             }
18548:             $defaultshash{'usersessions'}{'spares'}{$lonhost}{$type} = \@spares;
18549:             if (ref($spareid{$lonhost}) eq 'HASH') {
18550:                 if (ref($spareid{$lonhost}{$type}) eq 'ARRAY') {
18551:                     my @diffs = &Apache::loncommon::compare_arrays($spareid{$lonhost}{$type},\@spares);
18552:                     if (@diffs > 0) {
18553:                         $spareschg{$type} = 1;
18554:                     }
18555:                 }
18556:             }
18557:         }
18558:         if (keys(%spareschg) > 0) {
18559:             $changes{'spares'}{$lonhost} = \%spareschg;
18560:         }
18561:     }
18562:     $defaultshash{'usersessions'}{'offloadnow'} = {};
18563:     $defaultshash{'usersessions'}{'offloadoth'} = {};
18564:     my @offloadnow = &Apache::loncommon::get_env_multiple('form.offloadnow');
18565:     my @okoffload;
18566:     if (@offloadnow) {
18567:         foreach my $server (@offloadnow) {
18568:             if (&Apache::lonnet::hostname($server) ne '') {
18569:                 unless (grep(/^\Q$server\E$/,@okoffload)) {
18570:                     push(@okoffload,$server);
18571:                 }
18572:             }
18573:         }
18574:         if (@okoffload) {
18575:             foreach my $lonhost (@okoffload) {
18576:                 $defaultshash{'usersessions'}{'offloadnow'}{$lonhost} = 1;
18577:             }
18578:         }
18579:     }
18580:     my @offloadoth = &Apache::loncommon::get_env_multiple('form.offloadoth');
18581:     my @okoffloadoth;
18582:     if (@offloadoth) {
18583:         foreach my $server (@offloadoth) {
18584:             if (&Apache::lonnet::hostname($server) ne '') {
18585:                 unless (grep(/^\Q$server\E$/,@okoffloadoth)) {
18586:                     push(@okoffloadoth,$server);
18587:                 }
18588:             }
18589:         }
18590:         if (@okoffloadoth) {
18591:             foreach my $lonhost (@okoffloadoth) {
18592:                 $defaultshash{'usersessions'}{'offloadoth'}{$lonhost} = 1;
18593:             }
18594:         }
18595:     }
18596:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
18597:         if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
18598:             if (ref($changes{'spares'}) eq 'HASH') {
18599:                 if (keys(%{$changes{'spares'}}) > 0) {
18600:                     $savespares = 1;
18601:                 }
18602:             }
18603:         } else {
18604:             $savespares = 1;
18605:         }
18606:         foreach my $offload ('offloadnow','offloadoth') {
18607:             if (ref($domconfig{'usersessions'}{$offload}) eq 'HASH') {
18608:                 foreach my $lonhost (keys(%{$domconfig{'usersessions'}{$offload}})) {
18609:                     unless ($defaultshash{'usersessions'}{$offload}{$lonhost}) {
18610:                         $changes{$offload} = 1;
18611:                         last;
18612:                     }
18613:                 }
18614:                 unless ($changes{$offload}) {
18615:                     foreach my $lonhost (keys(%{$defaultshash{'usersessions'}{$offload}})) {
18616:                         unless ($domconfig{'usersessions'}{$offload}{$lonhost}) {
18617:                             $changes{$offload} = 1;
18618:                             last;
18619:                         }
18620:                     }
18621:                 }
18622:             } else {
18623:                 if (($offload eq 'offloadnow') && (@okoffload)) {
18624:                      $changes{'offloadnow'} = 1;
18625:                 }
18626:                 if (($offload eq 'offloadoth') && (@okoffloadoth)) {
18627:                     $changes{'offloadoth'} = 1;
18628:                 }
18629:             }
18630:         }
18631:     } else {
18632:         if (@okoffload) {
18633:             $changes{'offloadnow'} = 1;
18634:         }
18635:         if (@okoffloadoth) {
18636:             $changes{'offloadoth'} = 1;
18637:         }
18638:     }
18639:     my $nochgmsg = &mt('No changes made to settings for user session hosting/offloading.');
18640:     if ((keys(%changes) > 0) || ($savespares)) {
18641:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
18642:                                                  $dom);
18643:         if ($putresult eq 'ok') {
18644:             if (ref($defaultshash{'usersessions'}) eq 'HASH') {
18645:                 if (ref($defaultshash{'usersessions'}{'remote'}) eq 'HASH') {
18646:                     $domdefaults{'remotesessions'} = $defaultshash{'usersessions'}{'remote'};
18647:                 }
18648:                 if (ref($defaultshash{'usersessions'}{'hosted'}) eq 'HASH') {
18649:                     $domdefaults{'hostedsessions'} = $defaultshash{'usersessions'}{'hosted'};
18650:                 }
18651:                 if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
18652:                     $domdefaults{'offloadnow'} = $defaultshash{'usersessions'}{'offloadnow'};
18653:                 }
18654:                 if (ref($defaultshash{'usersessions'}{'offloadoth'}) eq 'HASH') {
18655:                     $domdefaults{'offloadoth'} = $defaultshash{'usersessions'}{'offloadoth'};
18656:                 }
18657:             }
18658:             my $cachetime = 24*60*60;
18659:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
18660:             &Apache::lonnet::do_cache_new('usersessions',$dom,$defaultshash{'usersessions'},3600);
18661:             if (ref($lastactref) eq 'HASH') {
18662:                 $lastactref->{'domdefaults'} = 1;
18663:                 $lastactref->{'usersessions'} = 1;
18664:             }
18665:             if (keys(%changes) > 0) {
18666:                 my %lt = &usersession_titles();
18667:                 $resulttext = &mt('Changes made:').'<ul>';
18668:                 foreach my $prefix (@prefixes) {
18669:                     if (ref($changes{$prefix}) eq 'HASH') {
18670:                         $resulttext .= '<li>'.$lt{$prefix}.'<ul>';
18671:                         if ($prefix eq 'spares') {
18672:                             if (ref($changes{$prefix}) eq 'HASH') {
18673:                                 foreach my $lonhost (sort(keys(%{$changes{$prefix}}))) {
18674:                                     $resulttext .= '<li><b>'.$lonhost.'</b> ';
18675:                                     my $lonhostdom = &Apache::lonnet::host_domain($lonhost);
18676:                                     my $cachekey = &escape('spares').':'.&escape($lonhostdom);
18677:                                     &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
18678:                                     if (ref($changes{$prefix}{$lonhost}) eq 'HASH') {
18679:                                         foreach my $type (@{$types{$prefix}}) {
18680:                                             if ($changes{$prefix}{$lonhost}{$type}) {
18681:                                                 my $offloadto = &mt('None');
18682:                                                 if (ref($defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}) eq 'ARRAY') {
18683:                                                     if (@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}} > 0) {   
18684:                                                         $offloadto = join(', ',@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}});
18685:                                                     }
18686:                                                 }
18687:                                                 $resulttext .= &mt('[_1] set to: [_2].','<i>'.$lt{$type}.'</i>',$offloadto).('&nbsp;'x3);
18688:                                             }
18689:                                         }
18690:                                     }
18691:                                     $resulttext .= '</li>';
18692:                                 }
18693:                             }
18694:                         } else {
18695:                             foreach my $type (@{$types{$prefix}}) {
18696:                                 if (defined($changes{$prefix}{$type})) {
18697:                                     my $newvalue;
18698:                                     if (ref($defaultshash{'usersessions'}) eq 'HASH') {
18699:                                         if (ref($defaultshash{'usersessions'}{$prefix})) {
18700:                                             if ($type eq 'version') {
18701:                                                 $newvalue = $defaultshash{'usersessions'}{$prefix}{$type};
18702:                                             } elsif (ref($defaultshash{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
18703:                                                 if (@{$defaultshash{'usersessions'}{$prefix}{$type}} > 0) {
18704:                                                     $newvalue = join(', ',@{$defaultshash{'usersessions'}{$prefix}{$type}});
18705:                                                 }
18706:                                             }
18707:                                         }
18708:                                     }
18709:                                     if ($newvalue eq '') {
18710:                                         if ($type eq 'version') {
18711:                                             $resulttext .= '<li>'.&mt('[_1] set to: off',$lt{$type}).'</li>';
18712:                                         } else {
18713:                                             $resulttext .= '<li>'.&mt('[_1] set to: none',$lt{$type}).'</li>';
18714:                                         }
18715:                                     } else {
18716:                                         if ($type eq 'version') {
18717:                                             $newvalue .= ' '.&mt('(or later)'); 
18718:                                         }
18719:                                         $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$lt{$type},$newvalue).'</li>';
18720:                                     }
18721:                                 }
18722:                             }
18723:                         }
18724:                         $resulttext .= '</ul>';
18725:                     }
18726:                 }
18727:                 if ($changes{'offloadnow'}) {
18728:                     if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
18729:                         if (keys(%{$defaultshash{'usersessions'}{'offloadnow'}}) > 0) {
18730:                             $resulttext .= '<li>'.&mt('Switch any active user on next access, for server(s):').'<ul>';
18731:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadnow'}}))) {
18732:                                 $resulttext .= '<li>'.$lonhost.'</li>';
18733:                             }
18734:                             $resulttext .= '</ul>';
18735:                         } else {
18736:                             $resulttext .= '<li>'.&mt('No servers now set to switch any active user on next access.');
18737:                         }
18738:                     } else {
18739:                         $resulttext .= '<li>'.&mt('No servers now set to switch any active user on next access.').'</li>';
18740:                     }
18741:                 }
18742:                 if ($changes{'offloadoth'}) {
18743:                     if (ref($defaultshash{'usersessions'}{'offloadoth'}) eq 'HASH') {
18744:                         if (keys(%{$defaultshash{'usersessions'}{'offloadoth'}}) > 0) {
18745:                             $resulttext .= '<li>'.&mt('Switch other institutions on next access, for server(s):').'<ul>';
18746:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadoth'}}))) {
18747:                                 $resulttext .= '<li>'.$lonhost.'</li>';
18748:                             }
18749:                             $resulttext .= '</ul>';
18750:                         } else {
18751:                             $resulttext .= '<li>'.&mt('No servers now set to switch other institutions on next access.');
18752:                         }
18753:                     } else {
18754:                         $resulttext .= '<li>'.&mt('No servers now set to switch other institutions on next access.').'</li>';
18755:                     }
18756:                 }
18757:                 $resulttext .= '</ul>';
18758:             } else {
18759:                 $resulttext = $nochgmsg;
18760:             }
18761:         } else {
18762:             $resulttext = '<span class="LC_error">'.
18763:                           &mt('An error occurred: [_1]',$putresult).'</span>';
18764:         }
18765:     } else {
18766:         $resulttext = $nochgmsg;
18767:     }
18768:     return $resulttext;
18769: }
18770: 
18771: sub modify_loadbalancing {
18772:     my ($dom,%domconfig) = @_;
18773:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
18774:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
18775:     my ($othertitle,$usertypes,$types) =
18776:         &Apache::loncommon::sorted_inst_types($dom);
18777:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
18778:     my %libraryservers = &Apache::lonnet::get_servers($dom,'library');
18779:     my @sparestypes = ('primary','default');
18780:     my %typetitles = &sparestype_titles();
18781:     my $resulttext;
18782:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
18783:     if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
18784:         %existing = %{$domconfig{'loadbalancing'}};
18785:     }
18786:     &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
18787:                               \%currtargets,\%currrules,\%currcookies);
18788:     my ($saveloadbalancing,%defaultshash,%changes);
18789:     my ($alltypes,$othertypes,$titles) =
18790:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
18791:     my %ruletitles = &offloadtype_text();
18792:     my @deletions = &Apache::loncommon::get_env_multiple('form.loadbalancing_delete');
18793:     for (my $i=0; $i<$env{'form.loadbalancing_total'}; $i++) {
18794:         my $balancer = $env{'form.loadbalancing_lonhost_'.$i};
18795:         if ($balancer eq '') {
18796:             next;
18797:         }
18798:         if (!exists($servers{$balancer})) {
18799:             if (exists($currbalancer{$balancer})) {
18800:                 push(@{$changes{'delete'}},$balancer);
18801:             }
18802:             next;
18803:         }
18804:         if ((@deletions > 0) && (grep(/^\Q$i\E$/,@deletions))) {
18805:             push(@{$changes{'delete'}},$balancer);
18806:             next;
18807:         }
18808:         if (!exists($currbalancer{$balancer})) {
18809:             push(@{$changes{'add'}},$balancer);
18810:         }
18811:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'} = [];
18812:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'default'} = [];
18813:         $defaultshash{'loadbalancing'}{$balancer}{'rules'} = {};
18814:         unless (ref($domconfig{'loadbalancing'}) eq 'HASH') {
18815:             $saveloadbalancing = 1;
18816:         }
18817:         foreach my $sparetype (@sparestypes) {
18818:             my @targets = &Apache::loncommon::get_env_multiple('form.loadbalancing_target_'.$i.'_'.$sparetype);
18819:             my @offloadto;
18820:             foreach my $target (@targets) {
18821:                 if (($servers{$target}) && ($target ne $balancer)) {
18822:                     if ($sparetype eq 'default') {
18823:                         if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}) eq 'ARRAY') {
18824:                             next if (grep(/^\Q$target\E$/,@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}}));
18825:                         }
18826:                     }
18827:                     unless(grep(/^\Q$target\E$/,@offloadto)) {
18828:                         push(@offloadto,$target);
18829:                     }
18830:                 }
18831:             }
18832:             if ($env{'form.loadbalancing_target_'.$i.'_hosthere'} eq $sparetype) {
18833:                 unless(grep(/^\Q$balancer\E$/,@offloadto)) {
18834:                     push(@offloadto,$balancer);
18835:                 }
18836:             }
18837:             $defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype} = \@offloadto;
18838:         }
18839:         if ($env{'form.loadbalancing_cookie_'.$i}) {
18840:             $defaultshash{'loadbalancing'}{$balancer}{'cookie'} = 1;
18841:             if (exists($currbalancer{$balancer})) {
18842:                 unless ($currcookies{$balancer}) {
18843:                     $changes{'curr'}{$balancer}{'cookie'} = 1;
18844:                 }
18845:             }
18846:         } elsif (exists($currbalancer{$balancer})) {
18847:             if ($currcookies{$balancer}) {
18848:                 $changes{'curr'}{$balancer}{'cookie'} = 1;
18849:             }
18850:         }
18851:         if (ref($currtargets{$balancer}) eq 'HASH') {
18852:             foreach my $sparetype (@sparestypes) {
18853:                 if (ref($currtargets{$balancer}{$sparetype}) eq 'ARRAY') {
18854:                     my @targetdiffs = &Apache::loncommon::compare_arrays($currtargets{$balancer}{$sparetype},$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype});
18855:                     if (@targetdiffs > 0) {
18856:                         $changes{'curr'}{$balancer}{'targets'} = 1;
18857:                     }
18858:                 } elsif (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
18859:                     if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
18860:                         $changes{'curr'}{$balancer}{'targets'} = 1;
18861:                     }
18862:                 }
18863:             }
18864:         } else {
18865:             if (ref($defaultshash{'loadbalancing'}{$balancer}) eq 'HASH') {
18866:                 foreach my $sparetype (@sparestypes) {
18867:                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
18868:                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
18869:                             $changes{'curr'}{$balancer}{'targets'} = 1;
18870:                         }
18871:                     }
18872:                 }
18873:             }
18874:         }
18875:         my $ishomedom;
18876:         if (&Apache::lonnet::host_domain($balancer) eq $dom) {
18877:             $ishomedom = 1;
18878:         }
18879:         if (ref($alltypes) eq 'ARRAY') {
18880:             foreach my $type (@{$alltypes}) {
18881:                 my $rule;
18882:                 unless ((($type eq '_LC_external') || ($type eq '_LC_internetdom')) &&
18883:                          (!$ishomedom)) {
18884:                     $rule = $env{'form.loadbalancing_rules_'.$i.'_'.$type};
18885:                 }
18886:                 if ($rule eq 'specific') {
18887:                     my $specifiedhost = $env{'form.loadbalancing_singleserver_'.$i.'_'.$type};
18888:                     if (exists($servers{$specifiedhost})) {
18889:                         $rule = $specifiedhost;
18890:                     }
18891:                 }
18892:                 $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type} = $rule;
18893:                 if (ref($currrules{$balancer}) eq 'HASH') {
18894:                     if ($rule ne $currrules{$balancer}{$type}) {
18895:                         $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
18896:                     }
18897:                 } elsif ($rule ne '') {
18898:                     $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
18899:                 }
18900:             }
18901:         }
18902:     }
18903:     my $nochgmsg = &mt('No changes made to Load Balancer settings.');
18904:     if ((keys(%changes) > 0) || ($saveloadbalancing)) {
18905:         unless (ref($defaultshash{'loadbalancing'}) eq 'HASH') {
18906:             $defaultshash{'loadbalancing'} = {};
18907:         }
18908:         my $putresult = &Apache::lonnet::put_dom('configuration',
18909:                                                  \%defaultshash,$dom);
18910:         if ($putresult eq 'ok') {
18911:             if (keys(%changes) > 0) {
18912:                 my %toupdate;
18913:                 if (ref($changes{'delete'}) eq 'ARRAY') {
18914:                     foreach my $balancer (sort(@{$changes{'delete'}})) {
18915:                         $resulttext .= '<li>'.&mt('Load Balancing discontinued for: [_1]',$balancer).'</li>';
18916:                         $toupdate{$balancer} = 1;
18917:                     }
18918:                 }
18919:                 if (ref($changes{'add'}) eq 'ARRAY') {
18920:                     foreach my $balancer (sort(@{$changes{'add'}})) {
18921:                         $resulttext .= '<li>'.&mt('Load Balancing enabled for: [_1]',$balancer);
18922:                         $toupdate{$balancer} = 1;
18923:                     }
18924:                 }
18925:                 if (ref($changes{'curr'}) eq 'HASH') {
18926:                     foreach my $balancer (sort(keys(%{$changes{'curr'}}))) {
18927:                         $toupdate{$balancer} = 1;
18928:                         if (ref($changes{'curr'}{$balancer}) eq 'HASH') {
18929:                             if ($changes{'curr'}{$balancer}{'targets'}) {
18930:                                 my %offloadstr;
18931:                                 foreach my $sparetype (@sparestypes) {
18932:                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
18933:                                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
18934:                                             $offloadstr{$sparetype} = join(', ',@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
18935:                                         }
18936:                                     }
18937:                                 }
18938:                                 if (keys(%offloadstr) == 0) {
18939:                                     $resulttext .= '<li>'.&mt("Servers to which Load Balance server offloads set to 'None', by default").'</li>';
18940:                                 } else {
18941:                                     my $showoffload;
18942:                                     foreach my $sparetype (@sparestypes) {
18943:                                         $showoffload .= '<i>'.$typetitles{$sparetype}.'</i>:&nbsp;';
18944:                                         if (defined($offloadstr{$sparetype})) {
18945:                                             $showoffload .= $offloadstr{$sparetype};
18946:                                         } else {
18947:                                             $showoffload .= &mt('None');
18948:                                         }
18949:                                         $showoffload .= ('&nbsp;'x3);
18950:                                     }
18951:                                     $resulttext .= '<li>'.&mt('By default, Load Balancer: [_1] set to offload to - [_2]',$balancer,$showoffload).'</li>';
18952:                                 }
18953:                             }
18954:                         }
18955:                         if (ref($changes{'curr'}{$balancer}{'rules'}) eq 'HASH') {
18956:                             if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH')) {
18957:                                 foreach my $type (@{$alltypes}) {
18958:                                     if ($changes{'curr'}{$balancer}{'rules'}{$type}) {
18959:                                         my $rule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
18960:                                         my $balancetext;
18961:                                         if ($rule eq '') {
18962:                                             $balancetext =  $ruletitles{'default'};
18963:                                         } elsif (($rule eq 'homeserver') || ($rule eq 'externalbalancer') ||
18964:                                                  ($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
18965:                                             if (($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
18966:                                                 foreach my $sparetype (@sparestypes) {
18967:                                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
18968:                                                         map { $toupdate{$_} = 1; } (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
18969:                                                     }
18970:                                                 }
18971:                                                 foreach my $item (@{$alltypes}) {
18972:                                                     next if ($item =~  /^_LC_ipchange/);
18973:                                                     my $hasrule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$item};
18974:                                                     if ($hasrule eq 'homeserver') {
18975:                                                         map { $toupdate{$_} = 1; } (keys(%libraryservers));
18976:                                                     } else {
18977:                                                         unless (($hasrule eq 'default') || ($hasrule eq 'none') || ($hasrule eq 'externalbalancer')) {
18978:                                                             if ($servers{$hasrule}) {
18979:                                                                 $toupdate{$hasrule} = 1;
18980:                                                             }
18981:                                                         }
18982:                                                     }
18983:                                                 }
18984:                                                 if (($rule eq 'balancer') || ($rule eq 'offloadedto')) {
18985:                                                     $balancetext =  $ruletitles{$rule};
18986:                                                 } else {
18987:                                                     my $receiver = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
18988:                                                     $balancetext = $ruletitles{'particular'}.' '.$receiver;
18989:                                                     if ($receiver) {
18990:                                                         $toupdate{$receiver};
18991:                                                     }
18992:                                                 }
18993:                                             } else {
18994:                                                 $balancetext =  $ruletitles{$rule};
18995:                                             }
18996:                                         } else {
18997:                                             $balancetext = &mt('offload to [_1]',$defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type});
18998:                                         }
18999:                                         $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- balancing for [_2] set to - "[_3]"',$balancer,$titles->{$type},$balancetext).'</li>';
19000:                                     }
19001:                                 }
19002:                             }
19003:                         }
19004:                         if ($changes{'curr'}{$balancer}{'cookie'}) {
19005:                             if ($currcookies{$balancer}) {
19006:                                 $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- cookie use disabled',
19007:                                                           $balancer).'</li>';
19008:                             } else {
19009:                                 $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- cookie use enabled',
19010:                                                           $balancer).'</li>';
19011:                             }
19012:                         }
19013:                     }
19014:                 }
19015:                 if (keys(%toupdate)) {
19016:                     my %thismachine;
19017:                     my $updatedhere;
19018:                     my $cachetime = 60*60*24;
19019:                     map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
19020:                     foreach my $lonhost (keys(%toupdate)) {
19021:                         if ($thismachine{$lonhost}) {
19022:                             unless ($updatedhere) {
19023:                                 &Apache::lonnet::do_cache_new('loadbalancing',$dom,
19024:                                                               $defaultshash{'loadbalancing'},
19025:                                                               $cachetime);
19026:                                 $updatedhere = 1;
19027:                             }
19028:                         } else {
19029:                             my $cachekey = &escape('loadbalancing').':'.&escape($dom);
19030:                             &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
19031:                         }
19032:                     }
19033:                 }
19034:                 if ($resulttext ne '') {
19035:                     $resulttext = &mt('Changes made:').'<ul>'.$resulttext.'</ul>';
19036:                 } else {
19037:                     $resulttext = $nochgmsg;
19038:                 }
19039:             } else {
19040:                 $resulttext = $nochgmsg;
19041:             }
19042:         } else {
19043:             $resulttext = '<span class="LC_error">'.
19044:                           &mt('An error occurred: [_1]',$putresult).'</span>';
19045:         }
19046:     } else {
19047:         $resulttext = $nochgmsg;
19048:     }
19049:     return $resulttext;
19050: }
19051: 
19052: sub recurse_check {
19053:     my ($chkcats,$categories,$depth,$name) = @_;
19054:     if (ref($chkcats->[$depth]{$name}) eq 'ARRAY') {
19055:         my $chg = 0;
19056:         for (my $j=0; $j<@{$chkcats->[$depth]{$name}}; $j++) {
19057:             my $category = $chkcats->[$depth]{$name}[$j];
19058:             my $item;
19059:             if ($category eq '') {
19060:                 $chg ++;
19061:             } else {
19062:                 my $deeper = $depth + 1;
19063:                 $item = &escape($category).':'.&escape($name).':'.$depth;
19064:                 if ($chg) {
19065:                     $categories->{$item} -= $chg;
19066:                 }
19067:                 &recurse_check($chkcats,$categories,$deeper,$category);
19068:                 $deeper --;
19069:             }
19070:         }
19071:     }
19072:     return;
19073: }
19074: 
19075: sub recurse_cat_deletes {
19076:     my ($item,$coursecategories,$deletions) = @_;
19077:     my ($deleted,$container,$depth) = map { &unescape($_); } split(/:/,$item);
19078:     my $subdepth = $depth + 1;
19079:     if (ref($coursecategories) eq 'HASH') {
19080:         foreach my $subitem (keys(%{$coursecategories})) {
19081:             my ($child,$parent,$itemdepth) = map { &unescape($_); } split(/:/,$subitem);
19082:             if (($parent eq $deleted) && ($itemdepth == $subdepth)) {
19083:                 delete($coursecategories->{$subitem});
19084:                 $deletions->{$subitem} = 1;
19085:                 &recurse_cat_deletes($subitem,$coursecategories,$deletions);
19086:             }
19087:         }
19088:     }
19089:     return;
19090: }
19091: 
19092: sub active_dc_picker {
19093:     my ($dom,$numinrow,$inputtype,$name,%currhash) = @_;
19094:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
19095:     my @domcoord = keys(%domcoords);
19096:     if (keys(%currhash)) {
19097:         foreach my $dc (keys(%currhash)) {
19098:             unless (exists($domcoords{$dc})) {
19099:                 push(@domcoord,$dc);
19100:             }
19101:         }
19102:     }
19103:     @domcoord = sort(@domcoord);
19104:     my $numdcs = scalar(@domcoord);
19105:     my $rows = 0;
19106:     my $table;
19107:     if ($numdcs > 1) {
19108:         $table = '<table>';
19109:         for (my $i=0; $i<@domcoord; $i++) {
19110:             my $rem = $i%($numinrow);
19111:             if ($rem == 0) {
19112:                 if ($i > 0) {
19113:                     $table .= '</tr>';
19114:                 }
19115:                 $table .= '<tr>';
19116:                 $rows ++;
19117:             }
19118:             my $check = '';
19119:             if ($inputtype eq 'radio') {
19120:                 if (keys(%currhash) == 0) {
19121:                     if (!$i) {
19122:                         $check = ' checked="checked"';
19123:                     }
19124:                 } elsif (exists($currhash{$domcoord[$i]})) {
19125:                     $check = ' checked="checked"';
19126:                 }
19127:             } else {
19128:                 if (exists($currhash{$domcoord[$i]})) {
19129:                     $check = ' checked="checked"';
19130:                 }
19131:             }
19132:             if ($i == @domcoord - 1) {
19133:                 my $colsleft = $numinrow - $rem;
19134:                 if ($colsleft > 1) {
19135:                     $table .= '<td class="LC_left_item" colspan="'.$colsleft.'">';
19136:                 } else {
19137:                     $table .= '<td class="LC_left_item">';
19138:                 }
19139:             } else {
19140:                 $table .= '<td class="LC_left_item">';
19141:             }
19142:             my ($dcname,$dcdom) = split(':',$domcoord[$i]);
19143:             my $user = &Apache::loncommon::plainname($dcname,$dcdom);
19144:             $table .= '<span class="LC_nobreak"><label>'.
19145:                       '<input type="'.$inputtype.'" name="'.$name.'"'.
19146:                       ' value="'.$domcoord[$i].'"'.$check.' />'.$user;
19147:             if ($user ne $dcname.':'.$dcdom) {
19148:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
19149:             }
19150:             $table .= '</label></span></td>';
19151:         }
19152:         $table .= '</tr></table>';
19153:     } elsif ($numdcs == 1) {
19154:         my ($dcname,$dcdom) = split(':',$domcoord[0]);
19155:         my $user = &Apache::loncommon::plainname($dcname,$dcdom);
19156:         if ($inputtype eq 'radio') {
19157:             $table = '<input type="hidden" name="'.$name.'" value="'.$domcoord[0].'" />'.$user;
19158:             if ($user ne $dcname.':'.$dcdom) {
19159:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
19160:             }
19161:         } else {
19162:             my $check;
19163:             if (exists($currhash{$domcoord[0]})) {
19164:                 $check = ' checked="checked"';
19165:             }
19166:             $table = '<span class="LC_nobreak"><label>'.
19167:                      '<input type="checkbox" name="'.$name.'" '.
19168:                      'value="'.$domcoord[0].'"'.$check.' />'.$user;
19169:             if ($user ne $dcname.':'.$dcdom) {
19170:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
19171:             }
19172:             $table .= '</label></span>';
19173:             $rows ++;
19174:         }
19175:     }
19176:     return ($numdcs,$table,$rows);
19177: }
19178: 
19179: sub usersession_titles {
19180:     return &Apache::lonlocal::texthash(
19181:                hosted => 'Hosting of sessions for users from other domains on servers in this domain',
19182:                remote => 'Hosting of sessions for users in this domain on servers in other domains',
19183:                spares => 'Servers offloaded to, when busy',
19184:                version => 'LON-CAPA version requirement',
19185:                excludedomain => 'Allow all, but exclude specific domains',
19186:                includedomain => 'Deny all, but include specific domains',
19187:                primary => 'Primary (checked first)',
19188:                default => 'Default',
19189:            );
19190: }
19191: 
19192: sub id_for_thisdom {
19193:     my (%servers) = @_;
19194:     my %altids;
19195:     foreach my $server (keys(%servers)) {
19196:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
19197:         if ($serverhome ne $server) {
19198:             $altids{$serverhome} = $server;
19199:         }
19200:     }
19201:     return %altids;
19202: }
19203: 
19204: sub count_servers {
19205:     my ($currbalancer,%servers) = @_;
19206:     my (@spares,$numspares);
19207:     foreach my $lonhost (sort(keys(%servers))) {
19208:         next if ($currbalancer eq $lonhost);
19209:         push(@spares,$lonhost);
19210:     }
19211:     if ($currbalancer) {
19212:         $numspares = scalar(@spares);
19213:     } else {
19214:         $numspares = scalar(@spares) - 1;
19215:     }
19216:     return ($numspares,@spares);
19217: }
19218: 
19219: sub lonbalance_targets_js {
19220:     my ($dom,$types,$servers,$settings) = @_;
19221:     my $select = &mt('Select');
19222:     my ($alltargets,$allishome,$allinsttypes,@alltypes);
19223:     if (ref($servers) eq 'HASH') {
19224:         $alltargets = join("','",sort(keys(%{$servers})));
19225:         my @homedoms;
19226:         foreach my $server (sort(keys(%{$servers}))) {
19227:             if (&Apache::lonnet::host_domain($server) eq $dom) {
19228:                 push(@homedoms,'1');
19229:             } else {
19230:                 push(@homedoms,'0');
19231:             }
19232:         }
19233:         $allishome = join("','",@homedoms);
19234:     }
19235:     if (ref($types) eq 'ARRAY') {
19236:         if (@{$types} > 0) {
19237:             @alltypes = @{$types};
19238:         }
19239:     }
19240:     push(@alltypes,'default','_LC_adv','_LC_author','_LC_internetdom','_LC_external');
19241:     $allinsttypes = join("','",@alltypes);
19242:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
19243:     if (ref($settings) eq 'HASH') {
19244:         %existing = %{$settings};
19245:     }
19246:     &get_loadbalancers_config($servers,\%existing,\%currbalancer,
19247:                               \%currtargets,\%currrules,\%currcookies);
19248:     my $balancers = join("','",sort(keys(%currbalancer)));
19249:     return <<"END";
19250: 
19251: <script type="text/javascript">
19252: // <![CDATA[
19253: 
19254: currBalancers = new Array('$balancers');
19255: 
19256: function toggleTargets(balnum) {
19257:     var lonhostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
19258:     var prevhostitem = document.getElementById('loadbalancing_prevlonhost_'+balnum);
19259:     var balancer = lonhostitem.options[lonhostitem.selectedIndex].value;
19260:     var prevbalancer = prevhostitem.value;
19261:     var baltotal = document.getElementById('loadbalancing_total').value;
19262:     prevhostitem.value = balancer;
19263:     if (prevbalancer != '') {
19264:         var prevIdx = currBalancers.indexOf(prevbalancer);
19265:         if (prevIdx != -1) {
19266:             currBalancers.splice(prevIdx,1);
19267:         }
19268:     }
19269:     if (balancer == '') {
19270:         hideSpares(balnum);
19271:     } else {
19272:         var currIdx = currBalancers.indexOf(balancer);
19273:         if (currIdx == -1) {
19274:             currBalancers.push(balancer);
19275:         }
19276:         var homedoms = new Array('$allishome');
19277:         var ishomedom = homedoms[lonhostitem.selectedIndex];
19278:         showSpares(balancer,ishomedom,balnum);
19279:     }
19280:     balancerChange(balnum,baltotal,'change',prevbalancer,balancer);
19281:     return;
19282: }
19283: 
19284: function showSpares(balancer,ishomedom,balnum) {
19285:     var alltargets = new Array('$alltargets');
19286:     var insttypes = new Array('$allinsttypes');
19287:     var offloadtypes = new Array('primary','default');
19288: 
19289:     document.getElementById('loadbalancing_targets_'+balnum).style.display='block';
19290:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='none';
19291:  
19292:     for (var i=0; i<offloadtypes.length; i++) {
19293:         var count = 0;
19294:         for (var j=0; j<alltargets.length; j++) {
19295:             if (alltargets[j] != balancer) {
19296:                 var item = document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+count);
19297:                 item.value = alltargets[j];
19298:                 item.style.textAlign='left';
19299:                 item.style.textFace='normal';
19300:                 document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+count).innerHTML = alltargets[j];
19301:                 if (currBalancers.indexOf(alltargets[j]) == -1) {
19302:                     item.disabled = '';
19303:                 } else {
19304:                     item.disabled = 'disabled';
19305:                     item.checked = false;
19306:                 }
19307:                 count ++;
19308:             }
19309:         }
19310:     }
19311:     for (var k=0; k<insttypes.length; k++) {
19312:         if ((insttypes[k] == '_LC_external') || (insttypes[k] == '_LC_internetdom')) {
19313:             if (ishomedom == 1) {
19314:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
19315:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
19316:             } else {
19317:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
19318:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
19319:             }
19320:         } else {
19321:             document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
19322:             document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
19323:         }
19324:         if ((insttypes[k] != '_LC_external') && 
19325:             ((insttypes[k] != '_LC_internetdom') ||
19326:              ((insttypes[k] == '_LC_internetdom') && (ishomedom == 1)))) {
19327:             var item = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]);
19328:             item.options.length = 0;
19329:             item.options[0] = new Option("","",true,true);
19330:             var idx = 0;
19331:             for (var m=0; m<alltargets.length; m++) {
19332:                 if ((currBalancers.indexOf(alltargets[m]) == -1) && (alltargets[m] != balancer)) {
19333:                     idx ++;
19334:                     item.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
19335:                 }
19336:             }
19337:         }
19338:     }
19339:     return;
19340: }
19341: 
19342: function hideSpares(balnum) {
19343:     var alltargets = new Array('$alltargets');
19344:     var insttypes = new Array('$allinsttypes');
19345:     var offloadtypes = new Array('primary','default');
19346: 
19347:     document.getElementById('loadbalancing_targets_'+balnum).style.display='none';
19348:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='block';
19349: 
19350:     var total = alltargets.length - 1;
19351:     for (var i=0; i<offloadtypes; i++) {
19352:         for (var j=0; j<total; j++) {
19353:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).checked = false;
19354:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).value = '';
19355:            document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+j).innerHTML = '';
19356:         }
19357:     }
19358:     for (var k=0; k<insttypes.length; k++) {
19359:         document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
19360:         document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
19361:         if (insttypes[k] != '_LC_external') {
19362:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).length = 0;
19363:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).options[0] = new Option("","",true,true);
19364:         }
19365:     }
19366:     return;
19367: }
19368: 
19369: function checkOffloads(item,balnum,type) {
19370:     var alltargets = new Array('$alltargets');
19371:     var offloadtypes = new Array('primary','default');
19372:     if (item.checked) {
19373:         var total = alltargets.length - 1;
19374:         var other;
19375:         if (type == offloadtypes[0]) {
19376:             other = offloadtypes[1];
19377:         } else {
19378:             other = offloadtypes[0];
19379:         }
19380:         for (var i=0; i<total; i++) {
19381:             var server = document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).value;
19382:             if (server == item.value) {
19383:                 if (document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked) {
19384:                     document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked = false;
19385:                 }
19386:             }
19387:         }
19388:     }
19389:     return;
19390: }
19391: 
19392: function singleServerToggle(balnum,type) {
19393:     var offloadtoSelIdx = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex;
19394:     if (offloadtoSelIdx == 0) {
19395:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_0').checked = true;
19396:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
19397: 
19398:     } else {
19399:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_2').checked = true;
19400:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
19401:     }
19402:     return;
19403: }
19404: 
19405: function balanceruleChange(formname,balnum,type) {
19406:     if (type == '_LC_external') {
19407:         return;
19408:     }
19409:     var typesRules = getIndicesByName(formname,'loadbalancing_rules_'+balnum+'_'+type);
19410:     for (var i=0; i<typesRules.length; i++) {
19411:         if (formname.elements[typesRules[i]].checked) {
19412:             if (formname.elements[typesRules[i]].value != 'specific') {
19413:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex = 0;
19414:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
19415:             } else {
19416:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
19417:             }
19418:         }
19419:     }
19420:     return;
19421: }
19422: 
19423: function balancerDeleteChange(balnum) {
19424:     var hostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
19425:     var baltotal = document.getElementById('loadbalancing_total').value;
19426:     var addtarget;
19427:     var removetarget;
19428:     var action = 'delete';
19429:     if (document.getElementById('loadbalancing_delete_'+balnum)) {
19430:         var lonhost = hostitem.value;
19431:         var currIdx = currBalancers.indexOf(lonhost);
19432:         if (document.getElementById('loadbalancing_delete_'+balnum).checked) {
19433:             if (currIdx != -1) {
19434:                 currBalancers.splice(currIdx,1);
19435:             }
19436:             addtarget = lonhost;
19437:         } else {
19438:             if (currIdx == -1) {
19439:                 currBalancers.push(lonhost);
19440:             }
19441:             removetarget = lonhost;
19442:             action = 'undelete';
19443:         }
19444:         balancerChange(balnum,baltotal,action,addtarget,removetarget);
19445:     }
19446:     return;
19447: }
19448: 
19449: function balancerChange(balnum,baltotal,action,addtarget,removetarget) {
19450:     if (baltotal > 1) {
19451:         var offloadtypes = new Array('primary','default');
19452:         var alltargets = new Array('$alltargets');
19453:         var insttypes = new Array('$allinsttypes');
19454:         for (var i=0; i<baltotal; i++) {
19455:             if (i != balnum) {
19456:                 for (var j=0; j<offloadtypes.length; j++) {
19457:                     var total = alltargets.length - 1;
19458:                     for (var k=0; k<total; k++) {
19459:                         var serveritem = document.getElementById('loadbalancing_target_'+i+'_'+offloadtypes[j]+'_'+k);
19460:                         var server = serveritem.value;
19461:                         if ((action == 'delete') || (action == 'change' && addtarget != ''))  {
19462:                             if (server == addtarget) {
19463:                                 serveritem.disabled = '';
19464:                             }
19465:                         }
19466:                         if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
19467:                             if (server == removetarget) {
19468:                                 serveritem.disabled = 'disabled';
19469:                                 serveritem.checked = false;
19470:                             }
19471:                         }
19472:                     }
19473:                 }
19474:                 for (var j=0; j<insttypes.length; j++) {
19475:                     if (insttypes[j] != '_LC_external') {
19476:                         if (document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j])) {
19477:                             var singleserver = document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j]);
19478:                             var currSel = singleserver.selectedIndex;
19479:                             var currVal = singleserver.options[currSel].value;
19480:                             if ((action == 'delete') || (action == 'change' && addtarget != '')) {
19481:                                 var numoptions = singleserver.options.length;
19482:                                 var needsnew = 1;
19483:                                 for (var k=0; k<numoptions; k++) {
19484:                                     if (singleserver.options[k] == addtarget) {
19485:                                         needsnew = 0;
19486:                                         break;
19487:                                     }
19488:                                 }
19489:                                 if (needsnew == 1) {
19490:                                     singleserver.options[numoptions] = new Option(addtarget,addtarget,false,false);
19491:                                 }
19492:                             }
19493:                             if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
19494:                                 singleserver.options.length = 0;
19495:                                 if ((currVal) && (currVal != removetarget)) {
19496:                                     singleserver.options[0] = new Option("","",false,false);
19497:                                 } else {
19498:                                     singleserver.options[0] = new Option("","",true,true);
19499:                                 }
19500:                                 var idx = 0;
19501:                                 for (var m=0; m<alltargets.length; m++) {
19502:                                     if (currBalancers.indexOf(alltargets[m]) == -1) {
19503:                                         idx ++;
19504:                                         if (currVal == alltargets[m]) {
19505:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],true,true);
19506:                                         } else {
19507:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
19508:                                         }
19509:                                     }
19510:                                 }
19511:                             }
19512:                         }
19513:                     }
19514:                 }
19515:             }
19516:         }
19517:     }
19518:     return;
19519: }
19520: 
19521: // ]]>
19522: </script>
19523: 
19524: END
19525: }
19526: 
19527: sub new_spares_js {
19528:     my @sparestypes = ('primary','default');
19529:     my $types = join("','",@sparestypes);
19530:     my $select = &mt('Select');
19531:     return <<"END";
19532: 
19533: <script type="text/javascript">
19534: // <![CDATA[
19535: 
19536: function updateNewSpares(formname,lonhost) {
19537:     var types = new Array('$types');
19538:     var include = new Array();
19539:     var exclude = new Array();
19540:     for (var i=0; i<types.length; i++) {
19541:         var spareboxes = getIndicesByName(formname,'spare_'+types[i]+'_'+lonhost);
19542:         for (var j=0; j<spareboxes.length; j++) {
19543:             if (formname.elements[spareboxes[j]].checked) {
19544:                 exclude.push(formname.elements[spareboxes[j]].value);
19545:             } else {
19546:                 include.push(formname.elements[spareboxes[j]].value);
19547:             }
19548:         }
19549:     }
19550:     for (var i=0; i<types.length; i++) {
19551:         var newSpare = document.getElementById('newspare_'+types[i]+'_'+lonhost);
19552:         var selIdx = newSpare.selectedIndex;
19553:         var currnew = newSpare.options[selIdx].value;
19554:         var okSpares = new Array();
19555:         for (var j=0; j<newSpare.options.length; j++) {
19556:             var possible = newSpare.options[j].value;
19557:             if (possible != '') {
19558:                 if (exclude.indexOf(possible) == -1) {
19559:                     okSpares.push(possible);
19560:                 } else {
19561:                     if (currnew == possible) {
19562:                         selIdx = 0;
19563:                     }
19564:                 }
19565:             }
19566:         }
19567:         for (var k=0; k<include.length; k++) {
19568:             if (okSpares.indexOf(include[k]) == -1) {
19569:                 okSpares.push(include[k]);
19570:             }
19571:         }
19572:         okSpares.sort();
19573:         newSpare.options.length = 0;
19574:         if (selIdx == 0) {
19575:             newSpare.options[0] = new Option("$select","",true,true);
19576:         } else {
19577:             newSpare.options[0] = new Option("$select","",false,false);
19578:         }
19579:         for (var m=0; m<okSpares.length; m++) {
19580:             var idx = m+1;
19581:             var selThis = 0;
19582:             if (selIdx != 0) {
19583:                 if (okSpares[m] == currnew) {
19584:                     selThis = 1;
19585:                 }
19586:             }
19587:             if (selThis == 1) {
19588:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],true,true);
19589:             } else {
19590:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],false,false);
19591:             }
19592:         }
19593:     }
19594:     return;
19595: }
19596: 
19597: function checkNewSpares(lonhost,type) {
19598:     var newSpare = document.getElementById('newspare_'+type+'_'+lonhost);
19599:     var chosen =  newSpare.options[newSpare.selectedIndex].value;
19600:     if (chosen != '') { 
19601:         var othertype;
19602:         var othernewSpare;
19603:         if (type == 'primary') {
19604:             othernewSpare = document.getElementById('newspare_default_'+lonhost);
19605:         }
19606:         if (type == 'default') {
19607:             othernewSpare = document.getElementById('newspare_primary_'+lonhost);
19608:         }
19609:         if (othernewSpare.options[othernewSpare.selectedIndex].value == chosen) {
19610:             othernewSpare.selectedIndex = 0;
19611:         }
19612:     }
19613:     return;
19614: }
19615: 
19616: // ]]>
19617: </script>
19618: 
19619: END
19620: 
19621: }
19622: 
19623: sub common_domprefs_js {
19624:     return <<"END";
19625: 
19626: <script type="text/javascript">
19627: // <![CDATA[
19628: 
19629: function getIndicesByName(formname,item) {
19630:     var group = new Array();
19631:     for (var i=0;i<formname.elements.length;i++) {
19632:         if (formname.elements[i].name == item) {
19633:             group.push(formname.elements[i].id);
19634:         }
19635:     }
19636:     return group;
19637: }
19638: 
19639: // ]]>
19640: </script>
19641: 
19642: END
19643: 
19644: }
19645: 
19646: sub recaptcha_js {
19647:     my %lt = &captcha_phrases();
19648:     return <<"END";
19649: 
19650: <script type="text/javascript">
19651: // <![CDATA[
19652: 
19653: function updateCaptcha(caller,context) {
19654:     var privitem;
19655:     var pubitem;
19656:     var privtext;
19657:     var pubtext;
19658:     var versionitem;
19659:     var versiontext;
19660:     if (document.getElementById(context+'_recaptchapub')) {
19661:         pubitem = document.getElementById(context+'_recaptchapub');
19662:     } else {
19663:         return;
19664:     }
19665:     if (document.getElementById(context+'_recaptchapriv')) {
19666:         privitem = document.getElementById(context+'_recaptchapriv');
19667:     } else {
19668:         return;
19669:     }
19670:     if (document.getElementById(context+'_recaptchapubtxt')) {
19671:         pubtext = document.getElementById(context+'_recaptchapubtxt');
19672:     } else {
19673:         return;
19674:     }
19675:     if (document.getElementById(context+'_recaptchaprivtxt')) {
19676:         privtext = document.getElementById(context+'_recaptchaprivtxt');
19677:     } else {
19678:         return;
19679:     }
19680:     if (document.getElementById(context+'_recaptchaversion')) {
19681:         versionitem = document.getElementById(context+'_recaptchaversion');
19682:     } else {
19683:         return;
19684:     }
19685:     if (document.getElementById(context+'_recaptchavertxt')) {
19686:         versiontext = document.getElementById(context+'_recaptchavertxt');
19687:     } else {
19688:         return;
19689:     }
19690:     if (caller.checked) {
19691:         if (caller.value == 'recaptcha') {
19692:             pubitem.type = 'text';
19693:             privitem.type = 'text';
19694:             pubitem.size = '40';
19695:             privitem.size = '40';
19696:             pubtext.innerHTML = "$lt{'pub'}";
19697:             privtext.innerHTML = "$lt{'priv'}";
19698:             versionitem.type = 'text';
19699:             versionitem.size = '3';
19700:             versiontext.innerHTML = "$lt{'ver'}";
19701:         } else {
19702:             pubitem.type = 'hidden';
19703:             privitem.type = 'hidden';
19704:             versionitem.type = 'hidden';
19705:             pubtext.innerHTML = '';
19706:             privtext.innerHTML = '';
19707:             versiontext.innerHTML = '';
19708:         }
19709:     }
19710:     return;
19711: }
19712: 
19713: // ]]>
19714: </script>
19715: 
19716: END
19717: 
19718: }
19719: 
19720: sub toggle_display_js {
19721:     return <<"END";
19722: 
19723: <script type="text/javascript">
19724: // <![CDATA[
19725: 
19726: function toggleDisplay(domForm,caller) {
19727:     if (document.getElementById(caller)) {
19728:         var divitem = document.getElementById(caller);
19729:         var optionsElement = domForm.coursecredits;
19730:         var checkval = 1;
19731:         var dispval = 'block';
19732:         var selfcreateRegExp = /^cancreate_emailverified/;
19733:         if (caller == 'emailoptions') {
19734:             optionsElement = domForm.cancreate_email; 
19735:         }
19736:         if (caller == 'studentsubmission') {
19737:             optionsElement = domForm.postsubmit;
19738:         }
19739:         if (caller == 'cloneinstcode') {
19740:             optionsElement = domForm.canclone;
19741:             checkval = 'instcode';
19742:         }
19743:         if (selfcreateRegExp.test(caller)) {
19744:             optionsElement = domForm.elements[caller];
19745:             checkval = 'other';
19746:             dispval = 'inline'
19747:         }
19748:         if (optionsElement.length) {
19749:             var currval;
19750:             for (var i=0; i<optionsElement.length; i++) {
19751:                 if (optionsElement[i].checked) {
19752:                    currval = optionsElement[i].value;
19753:                 }
19754:             }
19755:             if (currval == checkval) {
19756:                 divitem.style.display = dispval;
19757:             } else {
19758:                 divitem.style.display = 'none';
19759:             }
19760:         }
19761:     }
19762:     return;
19763: }
19764: 
19765: // ]]>
19766: </script>
19767: 
19768: END
19769: 
19770: }
19771: 
19772: sub captcha_phrases {
19773:     return &Apache::lonlocal::texthash (
19774:                  priv => 'Private key',
19775:                  pub  => 'Public key',
19776:                  original  => 'original (CAPTCHA)',
19777:                  recaptcha => 'successor (ReCAPTCHA)',
19778:                  notused   => 'unused',
19779:                  ver => 'ReCAPTCHA version (1 or 2)',
19780:     );
19781: }
19782: 
19783: sub devalidate_remote_domconfs {
19784:     my ($dom,$cachekeys) = @_;
19785:     return unless (ref($cachekeys) eq 'HASH');
19786:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
19787:     my %thismachine;
19788:     map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
19789:     my @posscached = ('domainconfig','domdefaults','ltitools','usersessions',
19790:                       'directorysrch','passwdconf','cats','proxyalias','proxysaml',
19791:                       'ipaccess');
19792:     my %cache_by_lonhost;
19793:     if (exists($cachekeys->{'samllanding'})) {
19794:         if (ref($cachekeys->{'samllanding'}) eq 'HASH') {
19795:             my %landing = %{$cachekeys->{'samllanding'}};
19796:             my %domservers = &Apache::lonnet::get_servers($dom);
19797:             if (keys(%domservers)) {
19798:                 foreach my $server (keys(%domservers)) {
19799:                     my @cached;
19800:                     next if ($thismachine{$server});
19801:                     if ($landing{$server}) {
19802:                         push(@cached,&escape('samllanding').':'.&escape($server));
19803:                     }
19804:                     if (@cached) {
19805:                         $cache_by_lonhost{$server} = \@cached;
19806:                     }
19807:                 }
19808:             }
19809:         }
19810:     }
19811:     if (keys(%servers)) {
19812:         foreach my $server (keys(%servers)) {
19813:             next if ($thismachine{$server});
19814:             my @cached;
19815:             foreach my $name (@posscached) {
19816:                 if ($cachekeys->{$name}) {
19817:                     if (($name eq 'proxyalias') || ($name eq 'proxysaml')) {
19818:                         if (ref($cachekeys->{$name}) eq 'HASH') {
19819:                             foreach my $key (keys(%{$cachekeys->{$name}})) {
19820:                                 push(@cached,&escape($name).':'.&escape($key));
19821:                             }
19822:                         }
19823:                     } else {
19824:                         push(@cached,&escape($name).':'.&escape($dom));
19825:                     }
19826:                 }
19827:             }
19828:             if ((exists($cache_by_lonhost{$server})) &&
19829:                 (ref($cache_by_lonhost{$server}) eq 'ARRAY')) {
19830:                 push(@cached,@{$cache_by_lonhost{$server}});
19831:             }
19832:             if (@cached) {
19833:                 &Apache::lonnet::remote_devalidate_cache($server,\@cached);
19834:             }
19835:         }
19836:     }
19837:     return;
19838: }
19839: 
19840: 1;

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