File:  [LON-CAPA] / loncom / interface / domainprefs.pm
Revision 1.160.6.118.2.1: download - view: text, annotated - select for diffs
Thu Dec 30 03:45:13 2021 UTC (2 years, 4 months ago) by raeburn
Branches: version_2_11_4_msu
- For 2.11.4 (modified)
  Include changes in 1.267, 1.273, 1.296, 1.297, 1.298, 1.307, 1.308,
                     1.318, 1.319 (modified), 1.322, 1.323, 1.324.

    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.1 2021/12/30 03:45:13 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','wafproxy','ipaccess'],$dom);
  222:     if (ref($domconfig{'ltitools'}) eq 'HASH') {
  223:         my %encconfig =
  224:             &Apache::lonnet::get_dom('encconfig',['ltitools'],$dom,undef,1);
  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:     my @prefs_order = ('rolecolors','login','ipaccess','defaults','wafproxy','passwords',
  236:                        'quotas','autoenroll','autoupdate','autocreate','directorysrch',
  237:                        'contacts','usercreation','selfcreation','usermodification',
  238:                        'scantron','requestcourses','requestauthor','coursecategories',
  239:                        'serverstatuses','helpsettings','coursedefaults',
  240:                        'ltitools','selfenrollment','usersessions');
  241:     my %existing;
  242:     if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
  243:         %existing = %{$domconfig{'loadbalancing'}};
  244:     }
  245:     if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
  246:         push(@prefs_order,'loadbalancing');
  247:     }
  248:     my %prefs = (
  249:         'rolecolors' =>
  250:                    { text => 'Default color schemes',
  251:                      help => 'Domain_Configuration_Color_Schemes',
  252:                      header => [{col1 => 'Student Settings',
  253:                                  col2 => '',},
  254:                                 {col1 => 'Coordinator Settings',
  255:                                  col2 => '',},
  256:                                 {col1 => 'Author Settings',
  257:                                  col2 => '',},
  258:                                 {col1 => 'Administrator Settings',
  259:                                  col2 => '',}],
  260:                       print => \&print_rolecolors,
  261:                       modify => \&modify_rolecolors,
  262:                     },
  263:         'login' =>
  264:                     { text => 'Log-in page options',
  265:                       help => 'Domain_Configuration_Login_Page',
  266:                       header => [{col1 => 'Log-in Page Items',
  267:                                   col2 => '',},
  268:                                  {col1 => 'Log-in Help',
  269:                                   col2 => 'Value'},
  270:                                  {col1 => 'Custom HTML in document head',
  271:                                   col2 => 'Value'},
  272:                                  {col1 => 'SSO',
  273:                                   col2 => 'Dual login: SSO and non-SSO options'},
  274:                                 ],
  275:                       print => \&print_login,
  276:                       modify => \&modify_login,
  277:                     },
  278:         'defaults' => 
  279:                     { text => 'Default authentication/language/timezone/portal/types',
  280:                       help => 'Domain_Configuration_LangTZAuth',
  281:                       header => [{col1 => 'Setting',
  282:                                   col2 => 'Value'},
  283:                                  {col1 => 'Institutional user types',
  284:                                   col2 => 'Name displayed'}],
  285:                       print => \&print_defaults,
  286:                       modify => \&modify_defaults,
  287:                     },
  288:         'wafproxy' =>
  289:                     { text => 'Web Application Firewall/Reverse Proxy',
  290:                       help => 'Domain_Configuration_WAF_Proxy',
  291:                       header => [{col1 => 'Domain(s)',
  292:                                   col2 => 'Servers and WAF/Reverse Proxy alias(es)',
  293:                                  },
  294:                                  {col1 => 'Domain(s)',
  295:                                   col2 => 'WAF Configuration',}],
  296:                       print => \&print_wafproxy,
  297:                       modify => \&modify_wafproxy,
  298:                     },
  299:         'passwords' =>
  300:                     { text => 'Passwords (Internal authentication)',
  301:                       help => 'Domain_Configuration_Passwords',
  302:                       header => [{col1 => 'Resetting Forgotten Password',
  303:                                   col2 => 'Settings'},
  304:                                  {col1 => 'Encryption of Stored Passwords (Internal Auth)',
  305:                                   col2 => 'Settings'},
  306:                                  {col1 => 'Rules for LON-CAPA Passwords',
  307:                                   col2 => 'Settings'},
  308:                                  {col1 => 'Course Owner Changing Student Passwords',
  309:                                   col2 => 'Settings'}],
  310:                       print => \&print_passwords,
  311:                       modify => \&modify_passwords,
  312:                     },
  313:         'quotas' => 
  314:                     { text => 'Blogs, personal web pages, webDAV/quotas, portfolios',
  315:                       help => 'Domain_Configuration_Quotas',
  316:                       header => [{col1 => 'User affiliation',
  317:                                   col2 => 'Available tools',
  318:                                   col3 => 'Quotas, MB; (Authoring requires role)',}],
  319:                       print => \&print_quotas,
  320:                       modify => \&modify_quotas,
  321:                     },
  322:         'autoenroll' =>
  323:                    { text => 'Auto-enrollment settings',
  324:                      help => 'Domain_Configuration_Auto_Enrollment',
  325:                      header => [{col1 => 'Configuration setting',
  326:                                  col2 => 'Value(s)'}],
  327:                      print => \&print_autoenroll,
  328:                      modify => \&modify_autoenroll,
  329:                    },
  330:         'autoupdate' => 
  331:                    { text => 'Auto-update settings',
  332:                      help => 'Domain_Configuration_Auto_Updates',
  333:                      header => [{col1 => 'Setting',
  334:                                  col2 => 'Value',},
  335:                                 {col1 => 'Setting',
  336:                                  col2 => 'Affiliation'},
  337:                                 {col1 => 'User population',
  338:                                  col2 => 'Updatable user data'}],
  339:                      print => \&print_autoupdate,
  340:                      modify => \&modify_autoupdate,
  341:                   },
  342:         'autocreate' => 
  343:                   { text => 'Auto-course creation settings',
  344:                      help => 'Domain_Configuration_Auto_Creation',
  345:                      header => [{col1 => 'Configuration Setting',
  346:                                  col2 => 'Value',}],
  347:                      print => \&print_autocreate,
  348:                      modify => \&modify_autocreate,
  349:                   },
  350:         'directorysrch' => 
  351:                   { text => 'Directory searches',
  352:                     help => 'Domain_Configuration_InstDirectory_Search',
  353:                     header => [{col1 => 'Institutional Directory Setting',
  354:                                 col2 => 'Value',},
  355:                                {col1 => 'LON-CAPA Directory Setting',
  356:                                 col2 => 'Value',}],
  357:                     print => \&print_directorysrch,
  358:                     modify => \&modify_directorysrch,
  359:                   },
  360:         'contacts' =>
  361:                   { text => 'E-mail addresses and helpform',
  362:                     help => 'Domain_Configuration_Contact_Info',
  363:                     header => [{col1 => 'Default e-mail addresses',
  364:                                 col2 => 'Value',},
  365:                                {col1 => 'Recipient(s) for notifications',
  366:                                 col2 => 'Value',},
  367:                                {col1 => 'Nightly status check e-mail',
  368:                                 col2 => 'Settings',},
  369:                                {col1 => 'Ask helpdesk form settings',
  370:                                 col2 => 'Value',},],
  371:                     print => \&print_contacts,
  372:                     modify => \&modify_contacts,
  373:                   },
  374:         'usercreation' => 
  375:                   { text => 'User creation',
  376:                     help => 'Domain_Configuration_User_Creation',
  377:                     header => [{col1 => 'Format rule type',
  378:                                 col2 => 'Format rules in force'},
  379:                                {col1 => 'User account creation',
  380:                                 col2 => 'Usernames which may be created',},
  381:                                {col1 => 'Context',
  382:                                 col2 => 'Assignable authentication types'}],
  383:                     print => \&print_usercreation,
  384:                     modify => \&modify_usercreation,
  385:                   },
  386:         'selfcreation' => 
  387:                   { text => 'Users self-creating accounts',
  388:                     help => 'Domain_Configuration_Self_Creation', 
  389:                     header => [{col1 => 'Self-creation with institutional username',
  390:                                 col2 => 'Enabled?'},
  391:                                {col1 => 'Institutional user type (login/SSO self-creation)',
  392:                                 col2 => 'Information user can enter'},
  393:                                {col1 => 'Self-creation with e-mail verification',
  394:                                 col2 => 'Settings'}],
  395:                     print => \&print_selfcreation,
  396:                     modify => \&modify_selfcreation,
  397:                   },
  398:         'usermodification' =>
  399:                   { text => 'User modification',
  400:                     help => 'Domain_Configuration_User_Modification',
  401:                     header => [{col1 => 'Target user has role',
  402:                                 col2 => 'User information updatable in author context'},
  403:                                {col1 => 'Target user has role',
  404:                                 col2 => 'User information updatable in course context'}],
  405:                     print => \&print_usermodification,
  406:                     modify => \&modify_usermodification,
  407:                   },
  408:         'scantron' =>
  409:                   { text => 'Bubblesheet format',
  410:                     help => 'Domain_Configuration_Scantron_Format',
  411:                     header => [ {col1 => 'Bubblesheet format file',
  412:                                  col2 => ''},
  413:                                 {col1 => 'Bubblesheet data upload formats',
  414:                                  col2 => 'Settings'}],
  415:                     print => \&print_scantron,
  416:                     modify => \&modify_scantron,
  417:                   },
  418:         'requestcourses' => 
  419:                  {text => 'Request creation of courses',
  420:                   help => 'Domain_Configuration_Request_Courses',
  421:                   header => [{col1 => 'User affiliation',
  422:                               col2 => 'Availability/Processing of requests',},
  423:                              {col1 => 'Setting',
  424:                               col2 => 'Value'},
  425:                              {col1 => 'Available textbooks',
  426:                               col2 => ''},
  427:                              {col1 => 'Available templates',
  428:                               col2 => ''},
  429:                              {col1 => 'Validation (not official courses)',
  430:                               col2 => 'Value'},],
  431:                   print => \&print_quotas,
  432:                   modify => \&modify_quotas,
  433:                  },
  434:         'requestauthor' =>
  435:                  {text => 'Request Authoring Space',
  436:                   help => 'Domain_Configuration_Request_Author',
  437:                   header => [{col1 => 'User affiliation',
  438:                               col2 => 'Availability/Processing of requests',},
  439:                              {col1 => 'Setting',
  440:                               col2 => 'Value'}],
  441:                   print => \&print_quotas,
  442:                   modify => \&modify_quotas,
  443:                  },
  444:         'coursecategories' =>
  445:                   { text => 'Cataloging of courses/communities',
  446:                     help => 'Domain_Configuration_Cataloging_Courses',
  447:                     header => [{col1 => 'Catalog type/availability',
  448:                                 col2 => '',},
  449:                                {col1 => 'Category settings for standard catalog',
  450:                                 col2 => '',},
  451:                                {col1 => 'Categories',
  452:                                 col2 => '',
  453:                                }],
  454:                     print => \&print_coursecategories,
  455:                     modify => \&modify_coursecategories,
  456:                   },
  457:         'serverstatuses' =>
  458:                  {text   => 'Access to server status pages',
  459:                   help   => 'Domain_Configuration_Server_Status',
  460:                   header => [{col1 => 'Status Page',
  461:                               col2 => 'Other named users',
  462:                               col3 => 'Specific IPs',
  463:                             }],
  464:                   print => \&print_serverstatuses,
  465:                   modify => \&modify_serverstatuses,
  466:                  },
  467:         'helpsettings' =>
  468:                  {text   => 'Support settings',
  469:                   help   => 'Domain_Configuration_Help_Settings',
  470:                   header => [{col1 => 'Help Page Settings (logged-in users)',
  471:                               col2 => 'Value'},
  472:                              {col1 => 'Helpdesk Roles',
  473:                               col2 => 'Settings'},],
  474:                   print  => \&print_helpsettings,
  475:                   modify => \&modify_helpsettings,
  476:                  },
  477:         'coursedefaults' => 
  478:                  {text => 'Course/Community defaults',
  479:                   help => 'Domain_Configuration_Course_Defaults',
  480:                   header => [{col1 => 'Defaults which can be overridden in each course by a CC',
  481:                               col2 => 'Value',},
  482:                              {col1 => 'Defaults which can be overridden for each course by a DC',
  483:                               col2 => 'Value',},],
  484:                   print => \&print_coursedefaults,
  485:                   modify => \&modify_coursedefaults,
  486:                  },
  487:         'selfenrollment' => 
  488:                  {text   => 'Self-enrollment in Course/Community',
  489:                   help   => 'Domain_Configuration_Selfenrollment',
  490:                   header => [{col1 => 'Configuration Rights',
  491:                               col2 => 'Configured by Course Personnel or Domain Coordinator?'},
  492:                              {col1 => 'Defaults',
  493:                               col2 => 'Value'},
  494:                              {col1 => 'Self-enrollment validation (optional)',
  495:                               col2 => 'Value'},],
  496:                   print => \&print_selfenrollment,
  497:                   modify => \&modify_selfenrollment,
  498:                  },
  499:         'usersessions' =>
  500:                  {text  => 'User session hosting/offloading',
  501:                   help  => 'Domain_Configuration_User_Sessions',
  502:                   header => [{col1 => 'Domain server',
  503:                               col2 => 'Servers to offload sessions to when busy'},
  504:                              {col1 => 'Hosting of users from other domains',
  505:                               col2 => 'Rules'},
  506:                              {col1 => "Hosting domain's own users elsewhere",
  507:                               col2 => 'Rules'}],
  508:                   print => \&print_usersessions,
  509:                   modify => \&modify_usersessions,
  510:                  },
  511:         'loadbalancing' =>
  512:                  {text  => 'Dedicated Load Balancer(s)',
  513:                   help  => 'Domain_Configuration_Load_Balancing',
  514:                   header => [{col1 => 'Balancers',
  515:                               col2 => 'Default destinations',
  516:                               col3 => 'User affiliation',
  517:                               col4 => 'Overrides'},
  518:                             ],
  519:                   print => \&print_loadbalancing,
  520:                   modify => \&modify_loadbalancing,
  521:                  },
  522:         'ltitools' =>
  523:                  {text => 'External Tools (LTI)',
  524:                   help => 'Domain_Configuration_LTI_Tools',
  525:                   header => [{col1 => 'Setting',
  526:                               col2 => 'Value',}],
  527:                   print => \&print_ltitools,
  528:                   modify => \&modify_ltitools,
  529:                  },
  530:          'ipaccess' =>
  531:                        {text => 'IP-based access control',
  532:                         help => 'Domain_Configuration_IP_Access',
  533:                         header => [{col1 => 'Setting',
  534:                                     col2 => 'Value'},],
  535:                         print  => \&print_ipaccess,
  536:                         modify => \&modify_ipaccess,
  537:                        },
  538:     );
  539:     if (keys(%servers) > 1) {
  540:         $prefs{'login'}  = { text   => 'Log-in page options',
  541:                              help   => 'Domain_Configuration_Login_Page',
  542:                             header => [{col1 => 'Log-in Service',
  543:                                         col2 => 'Server Setting',},
  544:                                        {col1 => 'Log-in Page Items',
  545:                                         col2 => ''},
  546:                                        {col1 => 'Log-in Help',
  547:                                         col2 => 'Value'},
  548:                                        {col1 => 'Custom HTML in document head',
  549:                                         col2 => 'Value'},
  550:                                        {col1 => 'SSO',
  551:                                         col2 => 'Dual login: SSO and non-SSO options'},
  552:                                       ],
  553:                             print => \&print_login,
  554:                             modify => \&modify_login,
  555:                            };
  556:     }
  557: 
  558:     my @roles = ('student','coordinator','author','admin');
  559:     my @actions = &Apache::loncommon::get_env_multiple('form.actions');
  560:     &Apache::lonhtmlcommon::add_breadcrumb
  561:     ({href=>"javascript:changePage(document.$phase,'pickactions')",
  562:       text=>"Settings to display/modify"});
  563:     my $confname = $dom.'-domainconfig';
  564: 
  565:     if ($phase eq 'process') {
  566:         my $result = &Apache::lonconfigsettings::make_changes($r,$dom,$phase,$context,\@prefs_order,
  567:                                                               \%prefs,\%domconfig,$confname,\@roles);
  568:         if ((ref($result) eq 'HASH') && (keys(%{$result}))) {
  569:             $r->rflush();
  570:             &devalidate_remote_domconfs($dom,$result);
  571:         }
  572:     } elsif ($phase eq 'display') {
  573:         my $js = &recaptcha_js().
  574:                  &toggle_display_js();
  575:         if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
  576:             my ($othertitle,$usertypes,$types) =
  577:                 &Apache::loncommon::sorted_inst_types($dom);
  578:             $js .= &lonbalance_targets_js($dom,$types,\%servers,
  579:                                           $domconfig{'loadbalancing'}).
  580:                    &new_spares_js().
  581:                    &common_domprefs_js().
  582:                    &Apache::loncommon::javascript_array_indexof();
  583:         }
  584:         if (grep(/^requestcourses$/,@actions)) {
  585:             my $javascript_validations;
  586:             my $coursebrowserjs=&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}); 
  587:             $js .= <<END;
  588: <script type="text/javascript">
  589: $javascript_validations
  590: </script>
  591: $coursebrowserjs
  592: END
  593:         } elsif (grep(/^ipaccess$/,@actions)) {
  594:             $js .= &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
  595:         }
  596:         if (grep(/^selfcreation$/,@actions)) {
  597:             $js .= &selfcreate_javascript();
  598:         }
  599:         if (grep(/^contacts$/,@actions)) {
  600:             $js .= &contacts_javascript();
  601:         }
  602:         if (grep(/^scantron$/,@actions)) {
  603:             $js .= &scantron_javascript();
  604:         }
  605:         &Apache::lonconfigsettings::display_settings($r,$dom,$phase,$context,\@prefs_order,\%prefs,\%domconfig,$confname,$js);
  606:     } else {
  607: # check if domconfig user exists for the domain.
  608:         my $servadm = $r->dir_config('lonAdmEMail');
  609:         my ($configuserok,$author_ok,$switchserver) =
  610:             &config_check($dom,$confname,$servadm);
  611:         unless ($configuserok eq 'ok') {
  612:             &Apache::lonconfigsettings::print_header($r,$phase,$context);
  613:             $r->print(&mt('The domain configuration user "[_1]" has yet to be created.',
  614:                           $confname).
  615:                       '<br />'
  616:             );
  617:             if ($switchserver) {
  618:                 $r->print(&mt('Ordinarily, that domain configuration user is created when the ./UPDATE script is run to install LON-CAPA for the first time.').
  619:                           '<br />'.
  620:                           &mt('However, that does not apply when new domains are added to a multi-domain server, and ./UPDATE has not been run recently.').
  621:                           '<br />'.
  622:                           &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).
  623:                           '<br />'.
  624:                           &mt('To do that now, use the following link: [_1]',$switchserver)
  625:                 );
  626:             } else {
  627:                 $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.').
  628:                           '<br />'.
  629:                           &mt('Once that is done, you will be able to use the web-based "Set domain configuration" to configure the domain')
  630:                 );
  631:             }
  632:             $r->print(&Apache::loncommon::end_page());
  633:             return OK;
  634:         }
  635:         if (keys(%domconfig) == 0) {
  636:             my $primarylibserv = &Apache::lonnet::domain($dom,'primary');
  637:             my @ids=&Apache::lonnet::current_machine_ids();
  638:             if (!grep(/^\Q$primarylibserv\E$/,@ids)) {
  639:                 my %designhash = &Apache::loncommon::get_domainconf($dom);
  640:                 my @loginimages = ('img','logo','domlogo','login');
  641:                 my $custom_img_count = 0;
  642:                 foreach my $img (@loginimages) {
  643:                     if ($designhash{$dom.'.login.'.$img} ne '') {
  644:                         $custom_img_count ++;
  645:                     }
  646:                 }
  647:                 foreach my $role (@roles) {
  648:                     if ($designhash{$dom.'.'.$role.'.img'} ne '') {
  649:                         $custom_img_count ++;
  650:                     }
  651:                 }
  652:                 if ($custom_img_count > 0) {
  653:                     &Apache::lonconfigsettings::print_header($r,$phase,$context);
  654:                     my $switch_server = &check_switchserver($dom,$confname);
  655:                     $r->print(
  656:     &mt('Domain configuration settings have yet to be saved for this domain via the web-based domain preferences interface.').'<br />'.
  657:     &mt("While this remains so, you must switch to the domain's primary library server in order to update settings.").'<br /><br />'.
  658:     &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 />'.
  659:     &mt("However, you will still need to switch to the domain's primary library server to upload new images or logos.").'<br /><br />');
  660:                     if ($switch_server) {
  661:                         $r->print($switch_server.' '.&mt('to primary library server for domain: [_1]',$dom));
  662:                     }
  663:                     $r->print(&Apache::loncommon::end_page());
  664:                     return OK;
  665:                 }
  666:             }
  667:         }
  668:         &Apache::lonconfigsettings::display_choices($r,$phase,$context,\@prefs_order,\%prefs);
  669:     }
  670:     return OK;
  671: }
  672: 
  673: sub process_changes {
  674:     my ($r,$dom,$confname,$action,$roles,$values,$lastactref) = @_;
  675:     my %domconfig;
  676:     if (ref($values) eq 'HASH') {
  677:         %domconfig = %{$values};
  678:     }
  679:     my $output;
  680:     if ($action eq 'login') {
  681:         $output = &modify_login($r,$dom,$confname,$lastactref,%domconfig);
  682:     } elsif ($action eq 'rolecolors') {
  683:         $output = &modify_rolecolors($r,$dom,$confname,$roles,
  684:                                      $lastactref,%domconfig);
  685:     } elsif ($action eq 'quotas') {
  686:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  687:     } elsif ($action eq 'autoenroll') {
  688:         $output = &modify_autoenroll($dom,$lastactref,%domconfig);
  689:     } elsif ($action eq 'autoupdate') {
  690:         $output = &modify_autoupdate($dom,%domconfig);
  691:     } elsif ($action eq 'autocreate') {
  692:         $output = &modify_autocreate($dom,%domconfig);
  693:     } elsif ($action eq 'directorysrch') {
  694:         $output = &modify_directorysrch($dom,$lastactref,%domconfig);
  695:     } elsif ($action eq 'usercreation') {
  696:         $output = &modify_usercreation($dom,%domconfig);
  697:     } elsif ($action eq 'selfcreation') {
  698:         $output = &modify_selfcreation($dom,$lastactref,%domconfig);
  699:     } elsif ($action eq 'usermodification') {
  700:         $output = &modify_usermodification($dom,%domconfig);
  701:     } elsif ($action eq 'contacts') {
  702:         $output = &modify_contacts($dom,$lastactref,%domconfig);
  703:     } elsif ($action eq 'defaults') {
  704:         $output = &modify_defaults($dom,$lastactref,%domconfig);
  705:     } elsif ($action eq 'scantron') {
  706:         $output = &modify_scantron($r,$dom,$confname,$lastactref,%domconfig);
  707:     } elsif ($action eq 'coursecategories') {
  708:         $output = &modify_coursecategories($dom,$lastactref,%domconfig);
  709:     } elsif ($action eq 'serverstatuses') {
  710:         $output = &modify_serverstatuses($dom,%domconfig);
  711:     } elsif ($action eq 'requestcourses') {
  712:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  713:     } elsif ($action eq 'requestauthor') {
  714:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  715:     } elsif ($action eq 'helpsettings') {
  716:         $output = &modify_helpsettings($r,$dom,$confname,$lastactref,%domconfig);
  717:     } elsif ($action eq 'coursedefaults') {
  718:         $output = &modify_coursedefaults($dom,$lastactref,%domconfig);
  719:     } elsif ($action eq 'selfenrollment') {
  720:         $output = &modify_selfenrollment($dom,$lastactref,%domconfig)
  721:     } elsif ($action eq 'usersessions') {
  722:         $output = &modify_usersessions($dom,$lastactref,%domconfig);
  723:     } elsif ($action eq 'loadbalancing') {
  724:         $output = &modify_loadbalancing($dom,%domconfig);
  725:     } elsif ($action eq 'passwords') {
  726:         $output = &modify_passwords($r,$dom,$confname,$lastactref,%domconfig);
  727:     } elsif ($action eq 'ltitools') {
  728:         $output = &modify_ltitools($r,$dom,$action,$lastactref,%domconfig);
  729:     } elsif ($action eq 'wafproxy') {
  730:         $output = &modify_wafproxy($dom,$action,$lastactref,%domconfig);
  731:     } elsif ($action eq 'ipaccess') {
  732:         $output = &modify_ipaccess($dom,$lastactref,%domconfig);
  733:     }
  734:     return $output;
  735: }
  736: 
  737: sub print_config_box {
  738:     my ($r,$dom,$confname,$phase,$action,$item,$settings) = @_;
  739:     my $rowtotal = 0;
  740:     my $output;
  741:     if ($action eq 'coursecategories') {
  742:         $output = &coursecategories_javascript($settings);
  743:     } elsif ($action eq 'defaults') {
  744:         $output = &defaults_javascript($settings); 
  745:     } elsif ($action eq 'passwords') {
  746:         $output = &passwords_javascript();
  747:     } elsif ($action eq 'helpsettings') {
  748:         my (%privs,%levelscurrent);
  749:         my %full=();
  750:         my %levels=(
  751:                      course => {},
  752:                      domain => {},
  753:                      system => {},
  754:                    );
  755:         my $context = 'domain';
  756:         my $crstype = 'Course';
  757:         my $formname = 'display';
  758:         &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
  759:         my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
  760:         $output =
  761:             &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,\%full,
  762:                                                       \@templateroles);
  763:     } elsif ($action eq 'ltitools') {
  764:         $output .= &ltitools_javascript($settings);
  765:     } elsif ($action eq 'wafproxy') {
  766:         $output .= &wafproxy_javascript($dom);
  767:     } elsif ($action eq 'autoupdate') {
  768:         $output .= &autoupdate_javascript();
  769:     } elsif ($action eq 'autoenroll') {
  770:         $output .= &autoenroll_javascript();
  771:     } elsif ($action eq 'login') {
  772:         $output .= &saml_javascript();
  773:     } elsif ($action eq 'ipaccess') {
  774:         $output .= &ipaccess_javascript($settings);
  775:     }
  776:     $output .=
  777:          '<table class="LC_nested_outer">
  778:           <tr>
  779:            <th class="LC_left_item LC_middle"><span class="LC_nobreak">'.
  780:            &mt($item->{text}).'&nbsp;'.
  781:            &Apache::loncommon::help_open_topic($item->{'help'}).'</span></th>'."\n".
  782:           '</tr>';
  783:     $rowtotal ++;
  784:     my $numheaders = 1;
  785:     if (ref($item->{'header'}) eq 'ARRAY') {
  786:         $numheaders = scalar(@{$item->{'header'}});
  787:     }
  788:     if ($numheaders > 1) {
  789:         my $colspan = '';
  790:         my $rightcolspan = '';
  791:         my $leftnobr = '';  
  792:         if (($action eq 'rolecolors') || ($action eq 'defaults') ||
  793:             ($action eq 'directorysrch') ||
  794:             (($action eq 'login') && ($numheaders < 5))) {
  795:             $colspan = ' colspan="2"';
  796:         }
  797:         if ($action eq 'usersessions') {
  798:             $rightcolspan = ' colspan="3"'; 
  799:         }
  800:         if ($action eq 'passwords') {
  801:             $leftnobr = ' LC_nobreak';
  802:         }
  803:         $output .= '
  804:           <tr>
  805:            <td>
  806:             <table class="LC_nested">
  807:              <tr class="LC_info_row">
  808:               <td class="LC_left_item'.$leftnobr.'"'.$colspan.'>'.&mt($item->{'header'}->[0]->{'col1'}).'</td>
  809:               <td class="LC_right_item"'.$rightcolspan.'>'.&mt($item->{'header'}->[0]->{'col2'}).'</td>
  810:              </tr>';
  811:         $rowtotal ++;
  812:         if (($action eq 'autoupdate') || ($action eq 'usercreation') || ($action eq 'selfcreation') ||
  813:             ($action eq 'usermodification') || ($action eq 'defaults') || ($action eq 'coursedefaults') ||
  814:             ($action eq 'selfenrollment') || ($action eq 'usersessions') || ($action eq 'directorysrch') ||
  815:             ($action eq 'helpsettings') || ($action eq 'contacts') || ($action eq 'wafproxy')) {
  816:             $output .= $item->{'print'}->('top',$dom,$settings,\$rowtotal);
  817:         } elsif ($action eq 'passwords') {
  818:             $output .= $item->{'print'}->('top',$dom,$confname,$settings,\$rowtotal);
  819:         } elsif ($action eq 'coursecategories') {
  820:             $output .= $item->{'print'}->('top',$dom,$item,$settings,\$rowtotal);
  821:         } elsif ($action eq 'scantron') {
  822:             $output .= $item->{'print'}->($r,'top',$dom,$confname,$settings,\$rowtotal);
  823:         } elsif ($action eq 'login') {
  824:             if ($numheaders == 5) {
  825:                 $colspan = ' colspan="2"';
  826:                 $output .= &print_login('service',$dom,$confname,$phase,$settings,\$rowtotal);
  827:             } else {
  828:                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal);
  829:             }
  830:         } elsif (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
  831:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
  832:         } elsif ($action eq 'rolecolors') {
  833:             $output .= &print_rolecolors($phase,'student',$dom,$confname,$settings,\$rowtotal);
  834:         }
  835:         $output .= '
  836:            </table>
  837:           </td>
  838:          </tr>
  839:          <tr>
  840:            <td>
  841:             <table class="LC_nested">
  842:              <tr class="LC_info_row">
  843:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col1'}).'</td>
  844:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col2'}).'</td>
  845:              </tr>';
  846:             $rowtotal ++;
  847:         if (($action eq 'autoupdate') || ($action eq 'usercreation') ||
  848:             ($action eq 'selfcreation') || ($action eq 'selfenrollment') ||
  849:             ($action eq 'usersessions') || ($action eq 'coursecategories') ||
  850:             ($action eq 'contacts') || ($action eq 'passwords')) {
  851:             if ($action eq 'coursecategories') {
  852:                 $output .= &print_coursecategories('middle',$dom,$item,$settings,\$rowtotal);
  853:                 $colspan = ' colspan="2"';
  854:             } elsif ($action eq 'passwords') {
  855:                 $output .= $item->{'print'}->('middle',$dom,$confname,$settings,\$rowtotal);
  856:             } else {
  857:                 $output .= $item->{'print'}->('middle',$dom,$settings,\$rowtotal);
  858:             }
  859:             $output .= '
  860:            </table>
  861:           </td>
  862:          </tr>
  863:          <tr>
  864:            <td>
  865:             <table class="LC_nested">
  866:              <tr class="LC_info_row">
  867:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
  868:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
  869:              </tr>'."\n";
  870:             if ($action eq 'coursecategories') {
  871:                 $output .= &print_coursecategories('bottom',$dom,$item,$settings,\$rowtotal);
  872:             } elsif (($action eq 'contacts') || ($action eq 'passwords')) {
  873:                 if ($action eq 'passwords') {
  874:                     $output .= $item->{'print'}->('lower',$dom,$confname,$settings,\$rowtotal);
  875:                 } else {
  876:                     $output .= $item->{'print'}->('lower',$dom,$settings,\$rowtotal);
  877:                 }
  878:                 $output .= '
  879:              </tr>
  880:             </table>
  881:            </td>
  882:           </tr>
  883:           <tr>
  884:            <td>
  885:             <table class="LC_nested">
  886:              <tr class="LC_info_row">
  887:               <td class="LC_left_item'.$leftnobr.'"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
  888:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td></tr>'."\n";
  889:                 if ($action eq 'passwords') {
  890:                     $output .= $item->{'print'}->('bottom',$dom,$confname,$settings,\$rowtotal);
  891:                 } else {
  892:                     $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
  893:                 }
  894:                 $output .= '
  895:             </table>
  896:           </td>
  897:          </tr>
  898:          <tr>';
  899:             } else {
  900:                 $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
  901:             }
  902:             $rowtotal ++;
  903:         } elsif (($action eq 'usermodification') || ($action eq 'coursedefaults') ||
  904:                  ($action eq 'defaults') || ($action eq 'directorysrch') ||
  905:                  ($action eq 'helpsettings') || ($action eq 'wafproxy')) {
  906:             $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
  907:         } elsif ($action eq 'scantron') {
  908:             $output .= $item->{'print'}->($r,'bottom',$dom,$confname,$settings,\$rowtotal);
  909:         } elsif ($action eq 'login') {
  910:             if ($numheaders == 5) {
  911:                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal).'
  912:            </table>
  913:           </td>
  914:          </tr>
  915:          <tr>
  916:            <td>
  917:             <table class="LC_nested">
  918:              <tr class="LC_info_row">
  919:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
  920:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td></tr>'.
  921:                        &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
  922:                 $rowtotal ++;
  923:             } else {
  924:                 $output .= &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
  925:             }
  926:             $output .= '
  927:            </table>
  928:           </td>
  929:          </tr>
  930:          <tr>
  931:            <td>
  932:             <table class="LC_nested">
  933:              <tr class="LC_info_row">';
  934:             if ($numheaders == 5) {
  935:                 $output .= '
  936:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
  937:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
  938:              </tr>';
  939:             } else {
  940:                 $output .= '
  941:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
  942:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
  943:              </tr>';
  944:             }
  945:             $rowtotal ++;
  946:             $output .= &print_login('headtag',$dom,$confname,$phase,$settings,\$rowtotal).'
  947:            </table>
  948:           </td>
  949:          </tr>
  950:          <tr>
  951:            <td>
  952:             <table class="LC_nested">
  953:              <tr class="LC_info_row">';
  954:             if ($numheaders == 5) {
  955:                 $output .= '
  956:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[4]->{'col1'}).'</td>
  957:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[4]->{'col2'}).'</td>
  958:              </tr>';
  959:             } else {
  960:                 $output .= '
  961:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
  962:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
  963:              </tr>';
  964:             }
  965:             $rowtotal ++;
  966:             $output .= &print_login('saml',$dom,$confname,$phase,$settings,\$rowtotal);
  967:         } elsif ($action eq 'requestcourses') {
  968:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
  969:             $rowtotal ++;
  970:             $output .= &print_studentcode($settings,\$rowtotal).'
  971:            </table>
  972:           </td>
  973:          </tr>
  974:          <tr>
  975:            <td>
  976:             <table class="LC_nested">
  977:              <tr class="LC_info_row">
  978:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
  979:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td> </tr>'.
  980:                        &textbookcourses_javascript($settings).
  981:                        &print_textbookcourses($dom,'textbooks',$settings,\$rowtotal).'
  982:             </table>
  983:            </td>
  984:           </tr>
  985:          <tr>
  986:            <td>
  987:             <table class="LC_nested">
  988:              <tr class="LC_info_row">
  989:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
  990:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td> </tr>'.
  991:                        &print_textbookcourses($dom,'templates',$settings,\$rowtotal).'
  992:             </table>
  993:            </td>
  994:           </tr>
  995:           <tr>
  996:            <td>
  997:             <table class="LC_nested">
  998:              <tr class="LC_info_row">
  999:               <td class="LC_left_item"'.$colspan.' valign="top">'.&mt($item->{'header'}->[4]->{'col1'}).'</td>
 1000:               <td class="LC_right_item" valign="top">'.&mt($item->{'header'}->[4]->{'col2'}).'</td>
 1001:              </tr>'.
 1002:             &print_validation_rows('requestcourses',$dom,$settings,\$rowtotal);
 1003:         } elsif ($action eq 'requestauthor') {
 1004:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
 1005:             $rowtotal ++;
 1006:         } elsif ($action eq 'rolecolors') {
 1007:             $output .= &print_rolecolors($phase,'coordinator',$dom,$confname,$settings,\$rowtotal).'
 1008:            </table>
 1009:           </td>
 1010:          </tr>
 1011:          <tr>
 1012:            <td>
 1013:             <table class="LC_nested">
 1014:              <tr class="LC_info_row">
 1015:               <td class="LC_left_item"'.$colspan.' valign="top">'.
 1016:                &mt($item->{'header'}->[2]->{'col1'}).'</td>
 1017:               <td class="LC_right_item" valign="top">'.
 1018:                &mt($item->{'header'}->[2]->{'col2'}).'</td>
 1019:              </tr>'.
 1020:             &print_rolecolors($phase,'author',$dom,$confname,$settings,\$rowtotal).'
 1021:            </table>
 1022:           </td>
 1023:          </tr>
 1024:          <tr>
 1025:            <td>
 1026:             <table class="LC_nested">
 1027:              <tr class="LC_info_row">
 1028:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1029:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
 1030:              </tr>'.
 1031:             &print_rolecolors($phase,'admin',$dom,$confname,$settings,\$rowtotal);
 1032:             $rowtotal += 2;
 1033:         }
 1034:     } else {
 1035:         $output .= '
 1036:           <tr>
 1037:            <td>
 1038:             <table class="LC_nested">
 1039:              <tr class="LC_info_row">';
 1040:         if ($action eq 'login') {
 1041:             $output .= '  
 1042:               <td class="LC_left_item" colspan="2">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
 1043:         } elsif ($action eq 'serverstatuses') {
 1044:             $output .= '
 1045:               <td class="LC_left_item" valign="top">'.&mt($item->{'header'}->[0]->{'col1'}).
 1046:               '<br />('.&mt('Automatic access for Dom. Coords.').')</td>';
 1047: 
 1048:         } else {
 1049:             $output .= '
 1050:               <td class="LC_left_item" valign="top">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
 1051:         }
 1052:         if (defined($item->{'header'}->[0]->{'col3'})) {
 1053:             $output .= '<td class="LC_left_item" valign="top">'.
 1054:                        &mt($item->{'header'}->[0]->{'col2'});
 1055:             if ($action eq 'serverstatuses') {
 1056:                 $output .= '<br />(<tt>'.&mt('user1:domain1,user2:domain2 etc.').'</tt>)';
 1057:             } 
 1058:         } else {
 1059:             $output .= '<td class="LC_right_item" valign="top">'.
 1060:                        &mt($item->{'header'}->[0]->{'col2'});
 1061:         }
 1062:         $output .= '</td>';
 1063:         if ($item->{'header'}->[0]->{'col3'}) {
 1064:             if (defined($item->{'header'}->[0]->{'col4'})) {
 1065:                 $output .= '<td class="LC_left_item" valign="top">'.
 1066:                             &mt($item->{'header'}->[0]->{'col3'});
 1067:             } else {
 1068:                 $output .= '<td class="LC_right_item" valign="top">'.
 1069:                            &mt($item->{'header'}->[0]->{'col3'});
 1070:             }
 1071:             if ($action eq 'serverstatuses') {
 1072:                 $output .= '<br />(<tt>'.&mt('IP1,IP2 etc.').'</tt>)';
 1073:             }
 1074:             $output .= '</td>';
 1075:         }
 1076:         if ($item->{'header'}->[0]->{'col4'}) {
 1077:             $output .= '<td class="LC_right_item" valign="top">'.
 1078:                        &mt($item->{'header'}->[0]->{'col4'});
 1079:         }
 1080:         $output .= '</tr>';
 1081:         $rowtotal ++;
 1082:         if ($action eq 'quotas') {
 1083:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
 1084:         } elsif (($action eq 'autoenroll') || ($action eq 'autocreate') || 
 1085:                  ($action eq 'serverstatuses') || ($action eq 'loadbalancing') ||
 1086:                  ($action eq 'ltitools') || ($action eq 'ipaccess')) {
 1087:             $output .= $item->{'print'}->($dom,$settings,\$rowtotal);
 1088:         }
 1089:     }
 1090:     $output .= '
 1091:    </table>
 1092:   </td>
 1093:  </tr>
 1094: </table><br />';
 1095:     return ($output,$rowtotal);
 1096: }
 1097: 
 1098: sub print_login {
 1099:     my ($caller,$dom,$confname,$phase,$settings,$rowtotal) = @_;
 1100:     my ($css_class,$datatable,$switchserver,%lt);
 1101:     my %choices = &login_choices();
 1102:     if (($caller eq 'help') || ($caller eq 'headtag') || ($caller eq 'saml')) {
 1103:         %lt = &login_file_options();
 1104:         $switchserver = &check_switchserver($dom,$confname);
 1105:     }
 1106: 
 1107:     if ($caller eq 'service') {
 1108:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 1109:         my $choice = $choices{'disallowlogin'};
 1110:         $css_class = ' class="LC_odd_row"';
 1111:         $datatable .= '<tr'.$css_class.'><td>'.$choice.'</td>'.
 1112:                       '<td align="right"><table><tr><th>'.$choices{'hostid'}.'</th>'.
 1113:                       '<th>'.$choices{'server'}.'</th>'.
 1114:                       '<th>'.$choices{'serverpath'}.'</th>'.
 1115:                       '<th>'.$choices{'custompath'}.'</th>'.
 1116:                       '<th><span class="LC_nobreak">'.$choices{'exempt'}.'</span></th></tr>'."\n";
 1117:         my %disallowed;
 1118:         if (ref($settings) eq 'HASH') {
 1119:             if (ref($settings->{'loginvia'}) eq 'HASH') {
 1120:                %disallowed = %{$settings->{'loginvia'}};
 1121:             }
 1122:         }
 1123:         foreach my $lonhost (sort(keys(%servers))) {
 1124:             my $direct = 'selected="selected"';
 1125:             if (ref($disallowed{$lonhost}) eq 'HASH') {
 1126:                 if ($disallowed{$lonhost}{'server'} ne '') {
 1127:                     $direct = '';
 1128:                 }
 1129:             }
 1130:             $datatable .= '<tr><td>'.$servers{$lonhost}.'</td>'.
 1131:                           '<td><select name="'.$lonhost.'_server">'.
 1132:                           '<option value=""'.$direct.'>'.$choices{'directlogin'}.
 1133:                           '</option>';
 1134:             foreach my $hostid (sort(keys(%servers))) {
 1135:                 next if ($servers{$hostid} eq $servers{$lonhost});
 1136:                 my $selected = '';
 1137:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
 1138:                     if ($hostid eq $disallowed{$lonhost}{'server'}) {
 1139:                         $selected = 'selected="selected"';
 1140:                     }
 1141:                 }
 1142:                 $datatable .= '<option value="'.$hostid.'"'.$selected.'>'.
 1143:                               $servers{$hostid}.'</option>';
 1144:             }
 1145:             $datatable .= '</select></td>'.
 1146:                           '<td><select name="'.$lonhost.'_serverpath">';
 1147:             foreach my $path ('','/','/adm/login','/adm/roles','custom') {
 1148:                 my $pathname = $path;
 1149:                 if ($path eq 'custom') {
 1150:                     $pathname = &mt('Custom Path').' ->';
 1151:                 }
 1152:                 my $selected = '';
 1153:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
 1154:                     if ($path eq $disallowed{$lonhost}{'serverpath'}) {
 1155:                         $selected = 'selected="selected"';
 1156:                     }
 1157:                 } elsif ($path eq '') {
 1158:                     $selected = 'selected="selected"';
 1159:                 }
 1160:                 $datatable .= '<option value="'.$path.'"'.$selected.'>'.$pathname.'</option>';
 1161:             }
 1162:             $datatable .= '</select></td>';
 1163:             my ($custom,$exempt);
 1164:             if (ref($disallowed{$lonhost}) eq 'HASH') {
 1165:                 $custom = $disallowed{$lonhost}{'custompath'};
 1166:                 $exempt = $disallowed{$lonhost}{'exempt'};
 1167:             }
 1168:             $datatable .= '<td><input type="text" name="'.$lonhost.'_custompath" size="6" value="'.$custom.'" /></td>'.
 1169:                           '<td><input type="text" name="'.$lonhost.'_exempt" size="8" value="'.$exempt.'" /></td>'.
 1170:                           '</tr>';
 1171:         }
 1172:         $datatable .= '</table></td></tr>';
 1173:         return $datatable;
 1174:     } elsif ($caller eq 'page') {
 1175:         my %defaultchecked = ( 
 1176:                                'coursecatalog' => 'on',
 1177:                                'helpdesk'      => 'on',
 1178:                                'adminmail'     => 'off',
 1179:                                'newuser'       => 'off',
 1180:                              );
 1181:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
 1182:         my (%checkedon,%checkedoff);
 1183:         foreach my $item (@toggles) {
 1184:             if ($defaultchecked{$item} eq 'on') { 
 1185:                 $checkedon{$item} = ' checked="checked" ';
 1186:                 $checkedoff{$item} = ' ';
 1187:             } elsif ($defaultchecked{$item} eq 'off') {
 1188:                 $checkedoff{$item} = ' checked="checked" ';
 1189:                 $checkedon{$item} = ' ';
 1190:             }
 1191:         }
 1192:         my @images = ('img','logo','domlogo','login');
 1193:         my @logintext = ('textcol','bgcol');
 1194:         my @bgs = ('pgbg','mainbg','sidebg');
 1195:         my @links = ('link','alink','vlink');
 1196:         my %designhash = &Apache::loncommon::get_domainconf($dom);
 1197:         my %defaultdesign = %Apache::loncommon::defaultdesign;
 1198:         my (%is_custom,%designs);
 1199:         my %defaults = (
 1200:                        font => $defaultdesign{'login.font'},
 1201:                        );
 1202:         foreach my $item (@images) {
 1203:             $defaults{$item} = $defaultdesign{'login.'.$item};
 1204:             $defaults{'showlogo'}{$item} = 1;
 1205:         }
 1206:         foreach my $item (@bgs) {
 1207:             $defaults{'bgs'}{$item} = $defaultdesign{'login.'.$item};
 1208:         }
 1209:         foreach my $item (@logintext) {
 1210:             $defaults{'logintext'}{$item} = $defaultdesign{'login.'.$item};
 1211:         }
 1212:         foreach my $item (@links) {
 1213:             $defaults{'links'}{$item} = $defaultdesign{'login.'.$item};
 1214:         }
 1215:         if (ref($settings) eq 'HASH') {
 1216:             foreach my $item (@toggles) {
 1217:                 if ($settings->{$item} eq '1') {
 1218:                     $checkedon{$item} =  ' checked="checked" ';
 1219:                     $checkedoff{$item} = ' ';
 1220:                 } elsif ($settings->{$item} eq '0') {
 1221:                     $checkedoff{$item} =  ' checked="checked" ';
 1222:                     $checkedon{$item} = ' ';
 1223:                 }
 1224:             }
 1225:             foreach my $item (@images) {
 1226:                 if (defined($settings->{$item})) {
 1227:                     $designs{$item} = $settings->{$item};
 1228:                     $is_custom{$item} = 1;
 1229:                 }
 1230:                 if (defined($settings->{'showlogo'}{$item})) {
 1231:                     $designs{'showlogo'}{$item} = $settings->{'showlogo'}{$item};
 1232:                 }
 1233:             }
 1234:             foreach my $item (@logintext) {
 1235:                 if ($settings->{$item} ne '') {
 1236:                     $designs{'logintext'}{$item} = $settings->{$item};
 1237:                     $is_custom{$item} = 1;
 1238:                 }
 1239:             }
 1240:             if ($settings->{'font'} ne '') {
 1241:                 $designs{'font'} = $settings->{'font'};
 1242:                 $is_custom{'font'} = 1;
 1243:             }
 1244:             foreach my $item (@bgs) {
 1245:                 if ($settings->{$item} ne '') {
 1246:                     $designs{'bgs'}{$item} = $settings->{$item};
 1247:                     $is_custom{$item} = 1;
 1248:                 }
 1249:             }
 1250:             foreach my $item (@links) {
 1251:                 if ($settings->{$item} ne '') {
 1252:                     $designs{'links'}{$item} = $settings->{$item};
 1253:                     $is_custom{$item} = 1;
 1254:                 }
 1255:             }
 1256:         } else {
 1257:             if ($designhash{$dom.'.login.font'} ne '') {
 1258:                 $designs{'font'} = $designhash{$dom.'.login.font'};
 1259:                 $is_custom{'font'} = 1;
 1260:             }
 1261:             foreach my $item (@images) {
 1262:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1263:                     $designs{$item} = $designhash{$dom.'.login.'.$item};
 1264:                     $is_custom{$item} = 1;
 1265:                 }
 1266:             }
 1267:             foreach my $item (@bgs) {
 1268:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1269:                     $designs{'bgs'}{$item} = $designhash{$dom.'.login.'.$item};
 1270:                     $is_custom{$item} = 1;
 1271:                 }
 1272:             }
 1273:             foreach my $item (@links) {
 1274:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1275:                     $designs{'links'}{$item} = $designhash{$dom.'.login.'.$item};
 1276:                     $is_custom{$item} = 1;
 1277:                 }
 1278:             }
 1279:         }
 1280:         my %alt_text = &Apache::lonlocal::texthash  ( img => 'Log-in banner',
 1281:                                                       logo => 'Institution Logo',
 1282:                                                       domlogo => 'Domain Logo',
 1283:                                                       login => 'Login box');
 1284:         my $itemcount = 1;
 1285:         foreach my $item (@toggles) {
 1286:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1287:             $datatable .=  
 1288:                 '<tr'.$css_class.'><td colspan="2">'.$choices{$item}.
 1289:                 '</td><td>'.
 1290:                 '<span class="LC_nobreak"><label><input type="radio" name="'.
 1291:                 $item.'"'.$checkedon{$item}.' value="1" />'.&mt('Yes').
 1292:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'"'.
 1293:                 $checkedoff{$item}.' value="0" />'.&mt('No').'</label></span></td>'.
 1294:                 '</tr>';
 1295:             $itemcount ++;
 1296:         }
 1297:         $datatable .= &display_color_options($dom,$confname,$phase,'login',$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal,\@logintext);
 1298:         $datatable .= '</tr></table></td></tr>';
 1299:     } elsif ($caller eq 'help') {
 1300:         my ($defaulturl,$defaulttype,%url,%type,%langchoices);
 1301:         my $itemcount = 1;
 1302:         $defaulturl = '/adm/loginproblems.html';
 1303:         $defaulttype = 'default';
 1304:         %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
 1305:         my @currlangs;
 1306:         if (ref($settings) eq 'HASH') {
 1307:             if (ref($settings->{'helpurl'}) eq 'HASH') {
 1308:                 foreach my $key (sort(keys(%{$settings->{'helpurl'}}))) {
 1309:                     next if ($settings->{'helpurl'}{$key} eq '');
 1310:                     $url{$key} = $settings->{'helpurl'}{$key}.'?inhibitmenu=yes';
 1311:                     $type{$key} = 'custom';
 1312:                     unless ($key eq 'nolang') {
 1313:                         push(@currlangs,$key);
 1314:                     }
 1315:                 }
 1316:             } elsif ($settings->{'helpurl'} ne '') {
 1317:                 $type{'nolang'} = 'custom';
 1318:                 $url{'nolang'} = $settings->{'helpurl'}.'?inhibitmenu=yes';
 1319:             }
 1320:         }
 1321:         foreach my $lang ('nolang',sort(@currlangs)) {
 1322:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1323:             $datatable .= '<tr'.$css_class.'>';
 1324:             if ($url{$lang} eq '') {
 1325:                 $url{$lang} = $defaulturl;
 1326:             }
 1327:             if ($type{$lang} eq '') {
 1328:                 $type{$lang} = $defaulttype;
 1329:             }
 1330:             $datatable .= '<td colspan="2"><span class="LC_nobreak">';
 1331:             if ($lang eq 'nolang') {
 1332:                 $datatable .= &mt('Log-in help page if no specific language file: [_1]',
 1333:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1334:             } else {
 1335:                 $datatable .= &mt('Log-in help page for language: [_1] is [_2]',
 1336:                                   $langchoices{$lang},
 1337:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1338:             }
 1339:             $datatable .= '</span></td>'."\n".
 1340:                           '<td class="LC_left_item">';
 1341:             if ($type{$lang} eq 'custom') {
 1342:                 $datatable .= '<span class="LC_nobreak"><label>'.
 1343:                               '<input type="checkbox" name="loginhelpurl_del" value="'.$lang.'" />'.
 1344:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1345:             } else {
 1346:                 $datatable .= $lt{'upl'};
 1347:             }
 1348:             $datatable .='<br />';
 1349:             if ($switchserver) {
 1350:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1351:             } else {
 1352:                 $datatable .= '<input type="file" name="loginhelpurl_'.$lang.'" />';
 1353:             }
 1354:             $datatable .= '</td></tr>';
 1355:             $itemcount ++;
 1356:         }
 1357:         my @addlangs;
 1358:         foreach my $lang (sort(keys(%langchoices))) {
 1359:             next if ((grep(/^\Q$lang\E$/,@currlangs)) || ($lang eq 'x_chef'));
 1360:             push(@addlangs,$lang);
 1361:         }
 1362:         if (@addlangs > 0) {
 1363:             my %toadd;
 1364:             map { $toadd{$_} = $langchoices{$_} ; } @addlangs;
 1365:             $toadd{''} = &mt('Select');
 1366:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1367:             $datatable .= '<tr'.$css_class.'><td class="LC_left_item" colspan="2">'.
 1368:                           &mt('Add log-in help page for a specific language:').'&nbsp;'.
 1369:                           &Apache::loncommon::select_form('','loginhelpurl_add_lang',\%toadd).
 1370:                           '</td><td class="LC_left_item">'.$lt{'upl'}.'<br />';
 1371:             if ($switchserver) {
 1372:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1373:             } else {
 1374:                 $datatable .= '<input type="file" name="loginhelpurl_add_file" />';
 1375:             }
 1376:             $datatable .= '</td></tr>';
 1377:             $itemcount ++;
 1378:         }
 1379:         $datatable .= &captcha_choice('login',$settings,$itemcount);
 1380:     } elsif ($caller eq 'headtag') {
 1381:         my %domservers = &Apache::lonnet::get_servers($dom);
 1382:         my $choice = $choices{'headtag'};
 1383:         $css_class = ' class="LC_odd_row"';
 1384:         $datatable .= '<tr'.$css_class.'><td colspan="2">'.$choice.'</td>'.
 1385:                       '<td align="left"><table><tr><th>'.$choices{'hostid'}.'</th>'.
 1386:                       '<th>'.$choices{'current'}.'</th>'.
 1387:                       '<th>'.$choices{'action'}.'</th>'.
 1388:                       '<th>'.$choices{'exempt'}.'</th></tr>'."\n";
 1389:         my (%currurls,%currexempt);
 1390:         if (ref($settings) eq 'HASH') {
 1391:             if (ref($settings->{'headtag'}) eq 'HASH') {
 1392:                 foreach my $lonhost (keys(%{$settings->{'headtag'}})) {
 1393:                     if (ref($settings->{'headtag'}{$lonhost}) eq 'HASH') {
 1394:                         $currurls{$lonhost} = $settings->{'headtag'}{$lonhost}{'url'};
 1395:                         $currexempt{$lonhost} = $settings->{'headtag'}{$lonhost}{'exempt'};
 1396:                     }
 1397:                 }
 1398:             }
 1399:         }
 1400:         foreach my $lonhost (sort(keys(%domservers))) {
 1401:             my $exempt = &check_exempt_addresses($currexempt{$lonhost});
 1402:             $datatable .= '<tr><td>'.$domservers{$lonhost}.'</td>';
 1403:             if ($currurls{$lonhost}) {
 1404:                 $datatable .= '<td class="LC_right_item"><a href="'.
 1405:                               "javascript:void(open('$currurls{$lonhost}?inhibitmenu=yes','Custom_HeadTag',
 1406:                               'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
 1407:                               '">'.$lt{'curr'}.'</a></td>'.
 1408:                               '<td><span class="LC_nobreak"><label>'.
 1409:                               '<input type="checkbox" name="loginheadtag_del" value="'.$lonhost.'" />'.
 1410:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1411:             } else {
 1412:                 $datatable .= '<td class="LC_right_item">'.$lt{'none'}.'</td><td>'.$lt{'upl'};
 1413:             }
 1414:             $datatable .='<br />';
 1415:             if ($switchserver) {
 1416:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1417:             } else {
 1418:                 $datatable .= '<input type="file" name="loginheadtag_'.$lonhost.'" />';
 1419:             }
 1420:             $datatable .= '</td><td><input type="text" name="loginheadtagexempt_'.$lonhost.'" value="'.$exempt.'" /></td></tr>';
 1421:         }
 1422:         $datatable .= '</table></td></tr>';
 1423:     } elsif ($caller eq 'saml') {
 1424:         my %domservers = &Apache::lonnet::get_servers($dom);
 1425:         $datatable .= '<tr><td colspan="3" style="text-align: left">'.
 1426:                       '<table><tr><th>'.$choices{'hostid'}.'</th>'.
 1427:                       '<th>'.$choices{'samllanding'}.'</th>'.
 1428:                       '<th>'.$choices{'samloptions'}.'</th></tr>'."\n";
 1429:         my (%saml,%samltext,%samlimg,%samlalt,%samlurl,%samltitle,%samlnotsso,%styleon,%styleoff);
 1430:         foreach my $lonhost (keys(%domservers)) {
 1431:             $samlurl{$lonhost} = '/adm/sso';
 1432:             $styleon{$lonhost} = 'display:none';
 1433:             $styleoff{$lonhost} = '';
 1434:         }
 1435:         if (ref($settings->{'saml'}) eq 'HASH') {
 1436:             foreach my $lonhost (keys(%{$settings->{'saml'}})) {
 1437:                 if (ref($settings->{'saml'}{$lonhost}) eq 'HASH') {
 1438:                     $saml{$lonhost} = 1;
 1439:                     $samltext{$lonhost} = $settings->{'saml'}{$lonhost}{'text'};
 1440:                     $samlimg{$lonhost} = $settings->{'saml'}{$lonhost}{'img'};
 1441:                     $samlalt{$lonhost} = $settings->{'saml'}{$lonhost}{'alt'};
 1442:                     $samlurl{$lonhost} = $settings->{'saml'}{$lonhost}{'url'};
 1443:                     $samltitle{$lonhost} = $settings->{'saml'}{$lonhost}{'title'};
 1444:                     $samlnotsso{$lonhost} = $settings->{'saml'}{$lonhost}{'notsso'};
 1445:                     $styleon{$lonhost} = '';
 1446:                     $styleoff{$lonhost} = 'display:none';
 1447:                 } else {
 1448:                     $styleon{$lonhost} = 'display:none';
 1449:                     $styleoff{$lonhost} = '';
 1450:                 }
 1451:             }
 1452:         }
 1453:         my $itemcount = 1;
 1454:         foreach my $lonhost (sort(keys(%domservers))) {
 1455:             my $samlon = ' ';
 1456:             my $samloff = ' checked="checked" ';
 1457:             if ($saml{$lonhost}) {
 1458:                 $samlon = $samloff;
 1459:                 $samloff = ' ';
 1460:             }
 1461:             my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1462:             $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.$domservers{$lonhost}.'</span></td>'.
 1463:                           '<td><span class="LC_nobreak"><label><input type="radio" name="saml_'.$lonhost.'"'.$samloff.
 1464:                           'onclick="toggleSamlOptions(this.form,'."'$lonhost'".');" value="0" />'.
 1465:                           &mt('No').'</label>'.('&nbsp;'x2).
 1466:                           '<label><input type="radio" name="saml_'.$lonhost.'"'.$samlon.
 1467:                           'onclick="toggleSamlOptions(this.form,'."'$lonhost'".');" value="1" />'.
 1468:                           &mt('Yes').'</label></span></td>'.
 1469:                           '<td id="samloptionson_'.$lonhost.'" style="'.$styleon{$lonhost}.'" width="100%">'.
 1470:                           '<table><tr><th colspan="5" align="center">'.&mt('SSO').'</th><th align="center">'.
 1471:                           '<span class="LC_nobreak">'.&mt('Non-SSO').'</span></th></tr>'.
 1472:                           '<tr><th>'.&mt('Text').'</th><th>'.&mt('Image').'</th>'.
 1473:                           '<th>'.&mt('Alt Text').'</th><th>'.&mt('URL').'</th>'.
 1474:                           '<th>'.&mt('Tool Tip').'</th><th>'.&mt('Text').'</th></tr>'.
 1475:                           '<tr'.$css_class.'><td><input type="text" name="saml_text_'.$lonhost.'" size="8" value="'.
 1476:                           $samltext{$lonhost}.'" /></td><td>';
 1477:             if ($samlimg{$lonhost}) {
 1478:                 $datatable .= '<img src="'.$samlimg{$lonhost}.'" /><br />'.
 1479:                               '<span class="LC_nobreak"><label>'.
 1480:                               '<input type="checkbox" name="saml_img_del" value="'.$lonhost.'" />'.
 1481:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1482:             } else {
 1483:                 $datatable .= $lt{'upl'};
 1484:             }
 1485:             $datatable .='<br />';
 1486:             if ($switchserver) {
 1487:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1488:             } else {
 1489:                 $datatable .= '<input type="file" name="saml_img_'.$lonhost.'" />';
 1490:             }
 1491:             $datatable .= '</td>'.
 1492:                           '<td><input type="text" name="saml_alt_'.$lonhost.'" size="20" '.
 1493:                           'value="'.$samlalt{$lonhost}.'" /></td>'.
 1494:                           '<td><input type="text" name="saml_url_'.$lonhost.'" size="8" '.
 1495:                           'value="'.$samlurl{$lonhost}.'" /></td>'.
 1496:                           '<td><textarea name="saml_title_'.$lonhost.'" rows="3" cols="15">'.
 1497:                           $samltitle{$lonhost}.'</textarea></td>'.
 1498:                           '<td><input type="text" name="saml_notsso_'.$lonhost.'" size="8" '.
 1499:                           'value="'.$samlnotsso{$lonhost}.'" /></td></tr>'.
 1500:                           '</table></td>'.
 1501:                           '<td id="samloptionsoff_'.$lonhost.'" style="'.$styleoff{$lonhost}.'" width="100%">&nbsp;</td></tr>';
 1502:            $itemcount ++;
 1503:         }
 1504:         $datatable .= '</table></td></tr>';
 1505:     }
 1506:     return $datatable;
 1507: }
 1508: 
 1509: sub login_choices {
 1510:     my %choices =
 1511:         &Apache::lonlocal::texthash (
 1512:             coursecatalog => 'Display Course/Community Catalog link?',
 1513:             adminmail     => "Display Administrator's E-mail Address?",
 1514:             helpdesk      => 'Display "Contact Helpdesk" link',
 1515:             disallowlogin => "Login page requests redirected",
 1516:             hostid        => "Server",
 1517:             server        => "Redirect to:",
 1518:             serverpath    => "Path",
 1519:             custompath    => "Custom", 
 1520:             exempt        => "Exempt IP(s)",
 1521:             directlogin   => "No redirect",
 1522:             newuser       => "Link to create a user account",
 1523:             img           => "Header",
 1524:             logo          => "Main Logo",
 1525:             domlogo       => "Domain Logo",
 1526:             login         => "Log-in Header", 
 1527:             textcol       => "Text color",
 1528:             bgcol         => "Box color",
 1529:             bgs           => "Background colors",
 1530:             links         => "Link colors",
 1531:             font          => "Font color",
 1532:             pgbg          => "Header",
 1533:             mainbg        => "Page",
 1534:             sidebg        => "Login box",
 1535:             link          => "Link",
 1536:             alink         => "Active link",
 1537:             vlink         => "Visited link",
 1538:             headtag       => "Custom markup",
 1539:             action        => "Action",
 1540:             current       => "Current",
 1541:             samllanding   => "Dual login?",
 1542:             samloptions   => "Options",
 1543:         );
 1544:     return %choices;
 1545: }
 1546: 
 1547: sub login_file_options {
 1548:       return &Apache::lonlocal::texthash(
 1549:                                            del     => 'Delete?',
 1550:                                            rep     => 'Replace:',
 1551:                                            upl     => 'Upload:',
 1552:                                            curr    => 'View contents',
 1553:                                            default => 'Default',
 1554:                                            custom  => 'Custom',
 1555:                                            none    => 'None',
 1556:       );
 1557: }
 1558: 
 1559: sub print_ipaccess {
 1560:     my ($dom,$settings,$rowtotal) = @_;
 1561:     my $css_class;
 1562:     my $itemcount = 0;
 1563:     my $datatable;
 1564:     my %ordered;
 1565:     if (ref($settings) eq 'HASH') {
 1566:         foreach my $item (keys(%{$settings})) {
 1567:             if (ref($settings->{$item}) eq 'HASH') {
 1568:                 my $num = $settings->{$item}{'order'};
 1569:                 if ($num eq '') {
 1570:                     $num = scalar(keys(%{$settings}));
 1571:                 }
 1572:                 $ordered{$num} = $item;
 1573:             }
 1574:         }
 1575:     }
 1576:     my $maxnum = scalar(keys(%ordered));
 1577:     if (keys(%ordered)) {
 1578:         my @items = sort { $a <=> $b } keys(%ordered);
 1579:         for (my $i=0; $i<@items; $i++) {
 1580:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1581:             my $item = $ordered{$items[$i]};
 1582:             my ($name,$ipranges,%commblocks,%courses);
 1583:             if (ref($settings->{$item}) eq 'HASH') {
 1584:                 $name = $settings->{$item}->{'name'};
 1585:                 $ipranges = $settings->{$item}->{'ip'};
 1586:                 if (ref($settings->{$item}->{'commblocks'}) eq 'HASH') {
 1587:                     %commblocks = %{$settings->{$item}->{'commblocks'}};
 1588:                 }
 1589:                 if (ref($settings->{$item}->{'courses'}) eq 'HASH') {
 1590:                     %courses = %{$settings->{$item}->{'courses'}};
 1591:                 }
 1592:             }
 1593:             my $chgstr = ' onchange="javascript:reorderIPaccess(this.form,'."'ipaccess_pos_".$item."'".');"';
 1594:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 1595:                          .'<select name="ipaccess_pos_'.$item.'"'.$chgstr.'>';
 1596:             for (my $k=0; $k<=$maxnum; $k++) {
 1597:                 my $vpos = $k+1;
 1598:                 my $selstr;
 1599:                 if ($k == $i) {
 1600:                     $selstr = ' selected="selected" ';
 1601:                 }
 1602:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 1603:             }
 1604:             $datatable .= '</select>'.('&nbsp;'x2).
 1605:                 '<label><input type="checkbox" name="ipaccess_del" value="'.$item.'" />'.
 1606:                 &mt('Delete?').'</label></span></td>'.
 1607:                 '<td colspan="2"><input type="hidden" name="ipaccess_id_'.$i.'" value="'.$item.'" />'.
 1608:                 &ipaccess_options($i,$itemcount,$dom,$name,$ipranges,\%commblocks,\%courses).
 1609:                 '</td></tr>';
 1610:             $itemcount ++;
 1611:         }
 1612:     }
 1613:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1614:     my $chgstr = ' onchange="javascript:reorderIPaccess(this.form,'."'ipaccess_pos_add'".');"';
 1615:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 1616:                   '<input type="hidden" name="ipaccess_maxnum" value="'.$maxnum.'" />'."\n".
 1617:                   '<select name="ipaccess_pos_add"'.$chgstr.'>';
 1618:     for (my $k=0; $k<$maxnum+1; $k++) {
 1619:         my $vpos = $k+1;
 1620:         my $selstr;
 1621:         if ($k == $maxnum) {
 1622:             $selstr = ' selected="selected" ';
 1623:         }
 1624:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 1625:     }
 1626:     $datatable .= '</select>&nbsp;'."\n".
 1627:                   '<input type="checkbox" name="ipaccess_add" value="1" />'.&mt('Add').'</span></td>'."\n".
 1628:                   '<td colspan="2">'.
 1629:                   &ipaccess_options('add',$itemcount,$dom).
 1630:                   '</td>'."\n".
 1631:                   '</tr>'."\n";
 1632:     $$rowtotal ++;
 1633:     return $datatable;
 1634: }
 1635: 
 1636: sub ipaccess_options {
 1637:     my ($num,$itemcount,$dom,$name,$ipranges,$blocksref,$coursesref) = @_;
 1638:     my (%currblocks,%currcourses,$output);
 1639:     if (ref($blocksref) eq 'HASH') {
 1640:         %currblocks = %{$blocksref};
 1641:     }
 1642:     if (ref($coursesref) eq 'HASH') {
 1643:         %currcourses = %{$coursesref};
 1644:     }
 1645:     $output = '<fieldset><legend>'.&mt('Location(s)').'</legend>'.
 1646:               '<span class="LC_nobreak">'.&mt('Name').':&nbsp;'.
 1647:               '<input type="text" name="ipaccess_name_'.$num.'" value="'.$name.'" />'.
 1648:               '</span></fieldset>'.
 1649:               '<fieldset><legend>'.&mt('IP Range(s)').'</legend>'.
 1650:               &mt('Format for each IP range').': '.&mt('A.B.C.D/N or A.B.C.D-E.F.G.H').'<br />'.
 1651:               &mt('Range(s) will be stored as IP netblock(s) in CIDR notation (comma separated)').'<br />'.
 1652:               '<textarea name="ipaccess_range_'.$num.'" rows="3" cols="80">'.
 1653:               $ipranges.'</textarea></fieldset>'.
 1654:               '<fieldset><legend>'.&mt('Functionality Blocked?').'</legend>'.
 1655:               &blocker_checkboxes($num,$blocksref).'</fieldset>'.
 1656:               '<fieldset><legend>'.&mt('Courses/Communities allowed').'</legend>'.
 1657:               '<table>';
 1658:     foreach my $cid (sort(keys(%currcourses))) {
 1659:         my %courseinfo = &Apache::lonnet::coursedescription($cid,{'one_time' => 1});
 1660:         $output .= '<tr><td><span class="LC_nobreak">'.
 1661:                    '<label><input type="checkbox" name="ipaccess_course_delete_'.$num.'" value="'.$cid.'" />'.
 1662:                    &mt('Delete?').'&nbsp;<span class="LC_cusr_emph">'.$courseinfo{'description'}.'</span></label></span>'.
 1663:                    ' <span class="LC_fontsize_medium">('.$cid.')</span></td></tr>';
 1664:     }
 1665:     $output .= '<tr><td><span class="LC_nobreak">'.&mt('Add').':&nbsp;'.
 1666:                '<input type="text" name="ipaccess_cdesc_'.$num.'" value="" onfocus="this.blur();opencrsbrowser('."'display','ipaccess_cnum_$num','ipaccess_cdom_$num','ipaccess_cdesc_$num'".');" />'.
 1667:                 &Apache::loncommon::selectcourse_link('display','ipaccess_cnum_'.$num,'ipaccess_cdom_'.$num,'ipaccess_cdesc_'.$num,$dom,undef,'Course/Community').
 1668:                '<input type="hidden" name="ipaccess_cnum_'.$num.'" value="" />'.
 1669:                '<input type="hidden" name="ipaccess_cdom_'.$num.'" value="" />'.
 1670:                '</span></td></tr></table>'."\n".
 1671:                '</fieldset>';
 1672:     return $output;
 1673: }
 1674: 
 1675: sub blocker_checkboxes {
 1676:     my ($num,$blocks) = @_;
 1677:     my ($typeorder,$types) = &commblocktype_text();
 1678:     my $numinrow = 6;
 1679:     my $output = '<table>';
 1680:     for (my $i=0; $i<@{$typeorder}; $i++) {
 1681:         my $block = $typeorder->[$i];
 1682:         my $blockstatus;
 1683:         if (ref($blocks) eq 'HASH') {
 1684:             if ($blocks->{$block} eq 'on') {
 1685:                 $blockstatus = 'checked="checked"';
 1686:             }
 1687:         }
 1688:         my $rem = $i%($numinrow);
 1689:         if ($rem == 0) {
 1690:             if ($i > 0) {
 1691:                 $output .= '</tr>';
 1692:             }
 1693:             $output .= '<tr>';
 1694:         }
 1695:         if ($i == scalar(@{$typeorder})-1) {
 1696:             my $colsleft = $numinrow-$rem;
 1697:             if ($colsleft > 1) {
 1698:                 $output .= '<td colspan="'.$colsleft.'">';
 1699:             } else {
 1700:                 $output .= '<td>';
 1701:             }
 1702:         } else {
 1703:             $output .= '<td>';
 1704:         }
 1705:         my $item = 'ipaccess_block_'.$num;
 1706:         if ($blockstatus) {
 1707:             $blockstatus = ' '.$blockstatus;
 1708:         }
 1709:         $output .= '<span class="LC_nobreak"><label>'."\n".
 1710:                    '<input type="checkbox" name="'.$item.'"'.
 1711:                    $blockstatus.' value="'.$block.'"'.' />'.
 1712:                    $types->{$block}.'</label></span>'."\n".
 1713:                    '<br /></td>';
 1714:     }
 1715:     $output .= '</tr></table>';
 1716:     return $output;
 1717: }
 1718: 
 1719: sub commblocktype_text {
 1720:     my %types = &Apache::lonlocal::texthash(
 1721:         'com' => 'Messaging',
 1722:         'chat' => 'Chat Room',
 1723:         'boards' => 'Discussion',
 1724:         'port' => 'Portfolio',
 1725:         'groups' => 'Groups',
 1726:         'blogs' => 'Blogs',
 1727:         'about' => 'User Information',
 1728:         'printout' => 'Printouts',
 1729:         'passwd' => 'Change Password',
 1730:         'grades' => 'Gradebook',
 1731:         'search' => 'Course search',
 1732:         'wishlist' => 'Stored links',
 1733:         'annotate' => 'Annotations',
 1734:     );
 1735:     my $typeorder = ['com','chat','boards','port','groups','blogs','about','wishlist','printout','grades','search','annotate','passwd'];
 1736:     return ($typeorder,\%types);
 1737: }
 1738: 
 1739: sub print_rolecolors {
 1740:     my ($phase,$role,$dom,$confname,$settings,$rowtotal) = @_;
 1741:     my %choices = &color_font_choices();
 1742:     my @bgs = ('pgbg','tabbg','sidebg');
 1743:     my @links = ('link','alink','vlink');
 1744:     my @images = ('img');
 1745:     my %alt_text = &Apache::lonlocal::texthash(img => "Banner for $role role");
 1746:     my %designhash = &Apache::loncommon::get_domainconf($dom);
 1747:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 1748:     my (%is_custom,%designs);
 1749:     my %defaults = &role_defaults($role,\@bgs,\@links,\@images);
 1750:     if (ref($settings) eq 'HASH') {
 1751:         if (ref($settings->{$role}) eq 'HASH') {
 1752:             if ($settings->{$role}->{'img'} ne '') {
 1753:                 $designs{'img'} = $settings->{$role}->{'img'};
 1754:                 $is_custom{'img'} = 1;
 1755:             }
 1756:             if ($settings->{$role}->{'font'} ne '') {
 1757:                 $designs{'font'} = $settings->{$role}->{'font'};
 1758:                 $is_custom{'font'} = 1;
 1759:             }
 1760:             if ($settings->{$role}->{'fontmenu'} ne '') {
 1761:                 $designs{'fontmenu'} = $settings->{$role}->{'fontmenu'};
 1762:                 $is_custom{'fontmenu'} = 1;
 1763:             }
 1764:             foreach my $item (@bgs) {
 1765:                 if ($settings->{$role}->{$item} ne '') {
 1766:                     $designs{'bgs'}{$item} = $settings->{$role}->{$item};
 1767:                     $is_custom{$item} = 1;
 1768:                 }
 1769:             }
 1770:             foreach my $item (@links) {
 1771:                 if ($settings->{$role}->{$item} ne '') {
 1772:                     $designs{'links'}{$item} = $settings->{$role}->{$item};
 1773:                     $is_custom{$item} = 1;
 1774:                 }
 1775:             }
 1776:         }
 1777:     } else {
 1778:         if ($designhash{$dom.'.'.$role.'.img'} ne '') {
 1779:             $designs{img} = $designhash{$dom.'.'.$role.'.img'};
 1780:             $is_custom{'img'} = 1;
 1781:         }
 1782:         if ($designhash{$dom.'.'.$role.'.fontmenu'} ne '') {
 1783:             $designs{fontmenu} = $designhash{$dom.'.'.$role.'.fontmenu'};
 1784:             $is_custom{'fontmenu'} = 1; 
 1785:         }
 1786:         if ($designhash{$dom.'.'.$role.'.font'} ne '') {
 1787:             $designs{font} = $designhash{$dom.'.'.$role.'.font'};
 1788:             $is_custom{'font'} = 1;
 1789:         }
 1790:         foreach my $item (@bgs) {
 1791:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 1792:                 $designs{'bgs'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 1793:                 $is_custom{$item} = 1;
 1794:             
 1795:             }
 1796:         }
 1797:         foreach my $item (@links) {
 1798:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 1799:                 $designs{'links'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 1800:                 $is_custom{$item} = 1;
 1801:             }
 1802:         }
 1803:     }
 1804:     my $itemcount = 1;
 1805:     my $datatable = &display_color_options($dom,$confname,$phase,$role,$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal);
 1806:     $datatable .= '</tr></table></td></tr>';
 1807:     return $datatable;
 1808: }
 1809: 
 1810: sub role_defaults {
 1811:     my ($role,$bgs,$links,$images,$logintext) = @_;
 1812:     my %defaults;
 1813:     unless ((ref($bgs) eq 'ARRAY') && (ref($links) eq 'ARRAY') && (ref($images) eq 'ARRAY')) {
 1814:         return %defaults;
 1815:     }
 1816:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 1817:     if ($role eq 'login') {
 1818:         %defaults = (
 1819:                        font => $defaultdesign{$role.'.font'},
 1820:                     );
 1821:         if (ref($logintext) eq 'ARRAY') {
 1822:             foreach my $item (@{$logintext}) {
 1823:                 $defaults{'logintext'}{$item} = $defaultdesign{$role.'.'.$item};
 1824:             }
 1825:         }
 1826:         foreach my $item (@{$images}) {
 1827:             $defaults{'showlogo'}{$item} = 1;
 1828:         }
 1829:     } else {
 1830:         %defaults = (
 1831:                        img => $defaultdesign{$role.'.img'},
 1832:                        font => $defaultdesign{$role.'.font'},
 1833:                        fontmenu => $defaultdesign{$role.'.fontmenu'},
 1834:                     );
 1835:     }
 1836:     foreach my $item (@{$bgs}) {
 1837:         $defaults{'bgs'}{$item} = $defaultdesign{$role.'.'.$item};
 1838:     }
 1839:     foreach my $item (@{$links}) {
 1840:         $defaults{'links'}{$item} = $defaultdesign{$role.'.'.$item};
 1841:     }
 1842:     foreach my $item (@{$images}) {
 1843:         $defaults{$item} = $defaultdesign{$role.'.'.$item};
 1844:     }
 1845:     return %defaults;
 1846: }
 1847: 
 1848: sub display_color_options {
 1849:     my ($dom,$confname,$phase,$role,$itemcount,$choices,$is_custom,$defaults,$designs,
 1850:         $images,$bgs,$links,$alt_text,$rowtotal,$logintext) = @_;
 1851:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 1852:     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1853:     my $datatable = '<tr'.$css_class.'>'.
 1854:         '<td>'.$choices->{'font'}.'</td>';
 1855:     if (!$is_custom->{'font'}) {
 1856:         $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span class="css_default_'.$role.'_font" style="color: '.$defaults->{'font'}.';">'.$defaults->{'font'}.'</span></td>';
 1857:     } else {
 1858:         $datatable .= '<td>&nbsp;</td>';
 1859:     }
 1860:     my $current_color = $designs->{'font'} ? $designs->{'font'} : $defaults->{'font'};
 1861: 
 1862:     $datatable .= '<td><span class="LC_nobreak">'.
 1863:                   '<input type="text" class="colorchooser" size="10" name="'.$role.'_font"'.
 1864:                   ' value="'.$current_color.'" />&nbsp;'.
 1865:                   '&nbsp;</span></td></tr>';
 1866:     unless ($role eq 'login') { 
 1867:         $datatable .= '<tr'.$css_class.'>'.
 1868:                       '<td>'.$choices->{'fontmenu'}.'</td>';
 1869:         if (!$is_custom->{'fontmenu'}) {
 1870:             $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span class="css_default_'.$role.'_font" style="color: '.$defaults->{'fontmenu'}.';">'.$defaults->{'fontmenu'}.'</span></td>';
 1871:         } else {
 1872:             $datatable .= '<td>&nbsp;</td>';
 1873:         }
 1874: 	$current_color = $designs->{'fontmenu'} ?
 1875: 	    $designs->{'fontmenu'} : $defaults->{'fontmenu'};
 1876:         $datatable .= '<td><span class="LC_nobreak">'.
 1877:                       '<input class="colorchooser" type="text" size="10" name="'
 1878: 		      .$role.'_fontmenu"'.
 1879:                       ' value="'.$current_color.'" />&nbsp;'.
 1880:                       '&nbsp;</span></td></tr>';
 1881:     }
 1882:     my $switchserver = &check_switchserver($dom,$confname);
 1883:     foreach my $img (@{$images}) {
 1884: 	$itemcount ++;
 1885:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1886:         $datatable .= '<tr'.$css_class.'>'.
 1887:                       '<td>'.$choices->{$img};
 1888:         my ($imgfile,$img_import,$login_hdr_pick,$logincolors);
 1889:         if ($role eq 'login') {
 1890:             if ($img eq 'login') {
 1891:                 $login_hdr_pick =
 1892:                     &login_header_options($img,$role,$defaults,$is_custom,$choices);
 1893:                 $logincolors =
 1894:                     &login_text_colors($img,$role,$logintext,$phase,$choices,
 1895:                                        $designs,$defaults);
 1896:             } elsif ($img ne 'domlogo') {
 1897:                 $datatable.= &logo_display_options($img,$defaults,$designs);
 1898:             }
 1899:         }
 1900:         $datatable .= '</td>';
 1901:         if ($designs->{$img} ne '') {
 1902:             $imgfile = $designs->{$img};
 1903: 	    $img_import = ($imgfile =~ m{^/adm/});
 1904:         } else {
 1905:             $imgfile = $defaults->{$img};
 1906:         }
 1907:         if ($imgfile) {
 1908:             my ($showfile,$fullsize);
 1909:             if ($imgfile =~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
 1910:                 my $urldir = $1;
 1911:                 my $filename = $2;
 1912:                 my @info = &Apache::lonnet::stat_file($designs->{$img});
 1913:                 if (@info) {
 1914:                     my $thumbfile = 'tn-'.$filename;
 1915:                     my @thumb=&Apache::lonnet::stat_file($urldir.'/'.$thumbfile);
 1916:                     if (@thumb) {
 1917:                         $showfile = $urldir.'/'.$thumbfile;
 1918:                     } else {
 1919:                         $showfile = $imgfile;
 1920:                     }
 1921:                 } else {
 1922:                     $showfile = '';
 1923:                 }
 1924:             } elsif ($imgfile =~ m-^/(adm/[^/]+)/([^/]+)$-) {
 1925:                 $showfile = $imgfile;
 1926:                 my $imgdir = $1;
 1927:                 my $filename = $2;
 1928:                 if (-e "$londocroot/$imgdir/tn-".$filename) {
 1929:                     $showfile = "/$imgdir/tn-".$filename;
 1930:                 } else {
 1931:                     my $input = $londocroot.$imgfile;
 1932:                     my $output = "$londocroot/$imgdir/tn-".$filename;
 1933:                     if (!-e $output) {
 1934:                         my ($width,$height) = &thumb_dimensions();
 1935:                         my ($fullwidth,$fullheight) = &check_dimensions($input);
 1936:                         if ($fullwidth ne '' && $fullheight ne '') {
 1937:                             if ($fullwidth > $width && $fullheight > $height) { 
 1938:                                 my $size = $width.'x'.$height;
 1939:                                 my @args = ('convert','-sample',$size,$input,$output);
 1940:                                 system({$args[0]} @args);
 1941:                                 $showfile = "/$imgdir/tn-".$filename;
 1942:                             }
 1943:                         }
 1944:                     }
 1945:                 }
 1946:             }
 1947:             if ($showfile) {
 1948:                 if ($showfile =~ m{^/(adm|res)/}) {
 1949:                     if ($showfile =~ m{^/res/}) {
 1950:                         my $local_showfile =
 1951:                             &Apache::lonnet::filelocation('',$showfile);
 1952:                         &Apache::lonnet::repcopy($local_showfile);
 1953:                     }
 1954:                     $showfile = &Apache::loncommon::lonhttpdurl($showfile);
 1955:                 }
 1956:                 if ($imgfile) {
 1957:                     if ($imgfile  =~ m{^/(adm|res)/}) {
 1958:                         if ($imgfile =~ m{^/res/}) {
 1959:                             my $local_imgfile =
 1960:                                 &Apache::lonnet::filelocation('',$imgfile);
 1961:                             &Apache::lonnet::repcopy($local_imgfile);
 1962:                         }
 1963:                         $fullsize = &Apache::loncommon::lonhttpdurl($imgfile);
 1964:                     } else {
 1965:                         $fullsize = $imgfile;
 1966:                     }
 1967:                 }
 1968:                 $datatable .= '<td>';
 1969:                 if ($img eq 'login') {
 1970:                     $datatable .= $login_hdr_pick;
 1971:                 } 
 1972:                 $datatable .= &image_changes($is_custom->{$img},$alt_text->{$img},$img_import,
 1973:                                              $showfile,$fullsize,$role,$img,$imgfile,$logincolors);
 1974:             } else {
 1975:                 $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 1976:                               &mt('Upload:').'<br />';
 1977:             }
 1978:         } else {
 1979:             $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 1980:                           &mt('Upload:').'<br />';
 1981:         }
 1982:         if ($switchserver) {
 1983:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1984:         } else {
 1985:             if ($img ne 'login') { # suppress file selection for Log-in header
 1986:                 $datatable .='&nbsp;<input type="file" name="'.$role.'_'.$img.'" />';
 1987:             }
 1988:         }
 1989:         $datatable .= '</td></tr>';
 1990:     }
 1991:     $itemcount ++;
 1992:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1993:     $datatable .= '<tr'.$css_class.'>'.
 1994:                   '<td>'.$choices->{'bgs'}.'</td>';
 1995:     my $bgs_def;
 1996:     foreach my $item (@{$bgs}) {
 1997:         if (!$is_custom->{$item}) {
 1998:             $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>';
 1999:         }
 2000:     }
 2001:     if ($bgs_def) {
 2002:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$bgs_def.'</tr></table></td>';
 2003:     } else {
 2004:         $datatable .= '<td>&nbsp;</td>';
 2005:     }
 2006:     $datatable .= '<td class="LC_right_item">'.
 2007:                   '<table border="0"><tr>';
 2008: 
 2009:     foreach my $item (@{$bgs}) {
 2010:         $datatable .= '<td align="center">'.$choices->{$item};
 2011: 	my $color = $designs->{'bgs'}{$item} ? $designs->{'bgs'}{$item} : $defaults->{'bgs'}{$item};
 2012:         if ($designs->{'bgs'}{$item}) {
 2013:             $datatable .= '&nbsp;';
 2014:         }
 2015:         $datatable .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 2016:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 2017:     }
 2018:     $datatable .= '</tr></table></td></tr>';
 2019:     $itemcount ++;
 2020:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2021:     $datatable .= '<tr'.$css_class.'>'.
 2022:                   '<td>'.$choices->{'links'}.'</td>';
 2023:     my $links_def;
 2024:     foreach my $item (@{$links}) {
 2025:         if (!$is_custom->{$item}) {
 2026:             $links_def .= '<td>'.$choices->{$item}.'<br /><span class="css_default_'.$role.'_'.$item.'" style="color: '.$defaults->{'links'}{$item}.';">'.$defaults->{'links'}{$item}.'</span></td>';
 2027:         }
 2028:     }
 2029:     if ($links_def) {
 2030:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$links_def.'</tr></table></td>';
 2031:     } else {
 2032:         $datatable .= '<td>&nbsp;</td>';
 2033:     }
 2034:     $datatable .= '<td class="LC_right_item">'.
 2035:                   '<table border="0"><tr>';
 2036:     foreach my $item (@{$links}) {
 2037: 	my $color = $designs->{'links'}{$item} ? $designs->{'links'}{$item} : $defaults->{'links'}{$item};
 2038:         $datatable .= '<td align="center">'.$choices->{$item}."\n";
 2039:         if ($designs->{'links'}{$item}) {
 2040:             $datatable.='&nbsp;';
 2041:         }
 2042:         $datatable .= '<br /><input type="text" size="8" class="colorchooser" name="'.$role.'_'.$item.'" value="'.$color.
 2043:                       '" /></td>';
 2044:     }
 2045:     $$rowtotal += $itemcount;
 2046:     return $datatable;
 2047: }
 2048: 
 2049: sub logo_display_options {
 2050:     my ($img,$defaults,$designs) = @_;
 2051:     my $checkedon;
 2052:     if (ref($defaults) eq 'HASH') {
 2053:         if (ref($defaults->{'showlogo'}) eq 'HASH') {
 2054:             if ($defaults->{'showlogo'}{$img}) {
 2055:                 $checkedon = 'checked="checked" ';     
 2056:             }
 2057:         } 
 2058:     }
 2059:     if (ref($designs) eq 'HASH') {
 2060:         if (ref($designs->{'showlogo'}) eq 'HASH') {
 2061:             if (defined($designs->{'showlogo'}{$img})) {
 2062:                 if ($designs->{'showlogo'}{$img} == 0) {
 2063:                     $checkedon = '';
 2064:                 } elsif ($designs->{'showlogo'}{$img} == 1) {
 2065:                     $checkedon = 'checked="checked" ';
 2066:                 }
 2067:             }
 2068:         }
 2069:     }
 2070:     return '<br /><label>&nbsp;&nbsp;<input type="checkbox" name="'.
 2071:            'login_showlogo_'.$img.'" value="1" '.$checkedon.'/>'.
 2072:            &mt('show').'</label>'."\n";
 2073: }
 2074: 
 2075: sub login_header_options  {
 2076:     my ($img,$role,$defaults,$is_custom,$choices) = @_;
 2077:     my $output = '';
 2078:     if ((!$is_custom->{'textcol'}) || (!$is_custom->{'bgcol'})) {
 2079:         $output .= &mt('Text default(s):').'<br />';
 2080:         if (!$is_custom->{'textcol'}) {
 2081:             $output .= $choices->{'textcol'}.':&nbsp;'.$defaults->{'logintext'}{'textcol'}.
 2082:                        '&nbsp;&nbsp;&nbsp;';
 2083:         }
 2084:         if (!$is_custom->{'bgcol'}) {
 2085:             $output .= $choices->{'bgcol'}.':&nbsp;'.
 2086:                        '<span id="css_'.$role.'_font" style="background-color: '.
 2087:                        $defaults->{'logintext'}{'bgcol'}.';">&nbsp;&nbsp;&nbsp;</span>';
 2088:         }
 2089:         $output .= '<br />';
 2090:     }
 2091:     $output .='<br />';
 2092:     return $output;
 2093: }
 2094: 
 2095: sub login_text_colors {
 2096:     my ($img,$role,$logintext,$phase,$choices,$designs,$defaults) = @_;
 2097:     my $color_menu = '<table border="0"><tr>';
 2098:     foreach my $item (@{$logintext}) {
 2099:         $color_menu .= '<td align="center">'.$choices->{$item};
 2100:         my $color = $designs->{'logintext'}{$item} ? $designs->{'logintext'}{$item} : $defaults->{'logintext'}{$item};
 2101:         $color_menu .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 2102:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 2103:     }
 2104:     $color_menu .= '</tr></table><br />';
 2105:     return $color_menu;
 2106: }
 2107: 
 2108: sub image_changes {
 2109:     my ($is_custom,$alt_text,$img_import,$showfile,$fullsize,$role,$img,$imgfile,$logincolors) = @_;
 2110:     my $output;
 2111:     if ($img eq 'login') {
 2112:         $output = '</td><td>'.$logincolors; # suppress image for Log-in header
 2113:     } elsif (!$is_custom) {
 2114:         if ($img ne 'domlogo') {
 2115:             $output = &mt('Default image:').'<br />';
 2116:         } else {
 2117:             $output = &mt('Default in use:').'<br />';
 2118:         }
 2119:     }
 2120:     if ($img ne 'login') {
 2121:         if ($img_import) {
 2122:             $output .= '<input type="hidden" name="'.$role.'_import_'.$img.'" value="'.$imgfile.'" />';
 2123:         }
 2124:         $output .= '<a href="'.$fullsize.'" target="_blank"><img src="'.
 2125:                    $showfile.'" alt="'.$alt_text.'" border="0" /></a></td>';
 2126:         if ($is_custom) {
 2127:             $output .= '<td>'.$logincolors.'<span class="LC_nobreak"><label>'.
 2128:                        '<input type="checkbox" name="'.
 2129:                        $role.'_del_'.$img.'" value="1" />'.&mt('Delete?').
 2130:                        '</label>&nbsp;'.&mt('Replace:').'</span><br />';
 2131:         } else {
 2132:             $output .= '<td valign="middle">'.$logincolors.&mt('Upload:').'<br />';
 2133:         }
 2134:     }
 2135:     return $output;
 2136: }
 2137: 
 2138: sub print_quotas {
 2139:     my ($dom,$settings,$rowtotal,$action) = @_;
 2140:     my $context;
 2141:     if ($action eq 'quotas') {
 2142:         $context = 'tools';
 2143:     } else {
 2144:         $context = $action;
 2145:     }
 2146:     my ($datatable,$defaultquota,$authorquota,@usertools,@options,%validations);
 2147:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 2148:     my $typecount = 0;
 2149:     my ($css_class,%titles);
 2150:     if ($context eq 'requestcourses') {
 2151:         @usertools = ('official','unofficial','community','textbook');
 2152:         @options =('norequest','approval','validate','autolimit');
 2153:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
 2154:         %titles = &courserequest_titles();
 2155:     } elsif ($context eq 'requestauthor') {
 2156:         @usertools = ('author');
 2157:         @options = ('norequest','approval','automatic');
 2158:         %titles = &authorrequest_titles();
 2159:     } else {
 2160:         @usertools = ('aboutme','blog','webdav','portfolio');
 2161:         %titles = &tool_titles();
 2162:     }
 2163:     if (ref($types) eq 'ARRAY') {
 2164:         foreach my $type (@{$types}) {
 2165:             my ($currdefquota,$currauthorquota);
 2166:             unless (($context eq 'requestcourses') ||
 2167:                     ($context eq 'requestauthor')) {
 2168:                 if (ref($settings) eq 'HASH') {
 2169:                     if (ref($settings->{defaultquota}) eq 'HASH') {
 2170:                         $currdefquota = $settings->{defaultquota}->{$type};
 2171:                     } else {
 2172:                         $currdefquota = $settings->{$type};
 2173:                     }
 2174:                     if (ref($settings->{authorquota}) eq 'HASH') {
 2175:                         $currauthorquota = $settings->{authorquota}->{$type};
 2176:                     }
 2177:                 }
 2178:             }
 2179:             if (defined($usertypes->{$type})) {
 2180:                 $typecount ++;
 2181:                 $css_class = $typecount%2?' class="LC_odd_row"':'';
 2182:                 $datatable .= '<tr'.$css_class.'>'.
 2183:                               '<td>'.$usertypes->{$type}.'</td>'.
 2184:                               '<td class="LC_left_item">';
 2185:                 if ($context eq 'requestcourses') {
 2186:                     $datatable .= '<table><tr>';
 2187:                 }
 2188:                 my %cell;  
 2189:                 foreach my $item (@usertools) {
 2190:                     if ($context eq 'requestcourses') {
 2191:                         my ($curroption,$currlimit);
 2192:                         if (ref($settings) eq 'HASH') {
 2193:                             if (ref($settings->{$item}) eq 'HASH') {
 2194:                                 $curroption = $settings->{$item}->{$type};
 2195:                                 if ($curroption =~ /^autolimit=(\d*)$/) {
 2196:                                     $currlimit = $1; 
 2197:                                 }
 2198:                             }
 2199:                         }
 2200:                         if (!$curroption) {
 2201:                             $curroption = 'norequest';
 2202:                         }
 2203:                         $datatable .= '<th>'.$titles{$item}.'</th>';
 2204:                         foreach my $option (@options) {
 2205:                             my $val = $option;
 2206:                             if ($option eq 'norequest') {
 2207:                                 $val = 0;  
 2208:                             }
 2209:                             if ($option eq 'validate') {
 2210:                                 my $canvalidate = 0;
 2211:                                 if (ref($validations{$item}) eq 'HASH') { 
 2212:                                     if ($validations{$item}{$type}) {
 2213:                                         $canvalidate = 1;
 2214:                                     }
 2215:                                 }
 2216:                                 next if (!$canvalidate);
 2217:                             }
 2218:                             my $checked = '';
 2219:                             if ($option eq $curroption) {
 2220:                                 $checked = ' checked="checked"';
 2221:                             } elsif ($option eq 'autolimit') {
 2222:                                 if ($curroption =~ /^autolimit/) {
 2223:                                     $checked = ' checked="checked"';
 2224:                                 }                       
 2225:                             } 
 2226:                             $cell{$item} .= '<span class="LC_nobreak"><label>'.
 2227:                                   '<input type="radio" name="crsreq_'.$item.
 2228:                                   '_'.$type.'" value="'.$val.'"'.$checked.' />'.
 2229:                                   $titles{$option}.'</label>';
 2230:                             if ($option eq 'autolimit') {
 2231:                                 $cell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2232:                                                 $item.'_limit_'.$type.'" size="1" '.
 2233:                                                 'value="'.$currlimit.'" />';
 2234:                             }
 2235:                             $cell{$item} .= '</span> ';
 2236:                             if ($option eq 'autolimit') {
 2237:                                 $cell{$item} .= $titles{'unlimited'};
 2238:                             }
 2239:                         }
 2240:                     } elsif ($context eq 'requestauthor') {
 2241:                         my $curroption;
 2242:                         if (ref($settings) eq 'HASH') {
 2243:                             $curroption = $settings->{$type};
 2244:                         }
 2245:                         if (!$curroption) {
 2246:                             $curroption = 'norequest';
 2247:                         }
 2248:                         foreach my $option (@options) {
 2249:                             my $val = $option;
 2250:                             if ($option eq 'norequest') {
 2251:                                 $val = 0;
 2252:                             }
 2253:                             my $checked = '';
 2254:                             if ($option eq $curroption) {
 2255:                                 $checked = ' checked="checked"';
 2256:                             }
 2257:                             $datatable .= '<span class="LC_nobreak"><label>'.
 2258:                                   '<input type="radio" name="authorreq_'.$type.
 2259:                                   '" value="'.$val.'"'.$checked.' />'.
 2260:                                   $titles{$option}.'</label></span>&nbsp; ';
 2261:                         }
 2262:                     } else {
 2263:                         my $checked = 'checked="checked" ';
 2264:                         if (ref($settings) eq 'HASH') {
 2265:                             if (ref($settings->{$item}) eq 'HASH') {
 2266:                                 if ($settings->{$item}->{$type} == 0) {
 2267:                                     $checked = '';
 2268:                                 } elsif ($settings->{$item}->{$type} == 1) {
 2269:                                     $checked =  'checked="checked" ';
 2270:                                 }
 2271:                             }
 2272:                         }
 2273:                         $datatable .= '<span class="LC_nobreak"><label>'.
 2274:                                       '<input type="checkbox" name="'.$context.'_'.$item.
 2275:                                       '" value="'.$type.'" '.$checked.'/>'.$titles{$item}.
 2276:                                       '</label></span>&nbsp; ';
 2277:                     }
 2278:                 }
 2279:                 if ($context eq 'requestcourses') {
 2280:                     $datatable .= '</tr><tr>';
 2281:                     foreach my $item (@usertools) {
 2282:                         $datatable .= '<td style="vertical-align: top">'.$cell{$item}.'</td>';  
 2283:                     }
 2284:                     $datatable .= '</tr></table>';
 2285:                 }
 2286:                 $datatable .= '</td>';
 2287:                 unless (($context eq 'requestcourses') ||
 2288:                         ($context eq 'requestauthor')) {
 2289:                     $datatable .= 
 2290:                               '<td class="LC_right_item">'.
 2291:                               '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 2292:                               '<input type="text" name="quota_'.$type.
 2293:                               '" value="'.$currdefquota.
 2294:                               '" size="5" /></span>'.('&nbsp;' x 2).
 2295:                               '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 2296:                               '<input type="text" name="authorquota_'.$type.
 2297:                               '" value="'.$currauthorquota.
 2298:                               '" size="5" /></span></td>';
 2299:                 }
 2300:                 $datatable .= '</tr>';
 2301:             }
 2302:         }
 2303:     }
 2304:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 2305:         $defaultquota = '20';
 2306:         $authorquota = '500';
 2307:         if (ref($settings) eq 'HASH') {
 2308:             if (ref($settings->{'defaultquota'}) eq 'HASH') {
 2309:                 $defaultquota = $settings->{'defaultquota'}->{'default'};
 2310:             } elsif (defined($settings->{'default'})) {
 2311:                 $defaultquota = $settings->{'default'};
 2312:             }
 2313:             if (ref($settings->{'authorquota'}) eq 'HASH') {
 2314:                 $authorquota = $settings->{'authorquota'}->{'default'};
 2315:             }
 2316:         }
 2317:     }
 2318:     $typecount ++;
 2319:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 2320:     $datatable .= '<tr'.$css_class.'>'.
 2321:                   '<td>'.$othertitle.'</td>'.
 2322:                   '<td class="LC_left_item">';
 2323:     if ($context eq 'requestcourses') {
 2324:         $datatable .= '<table><tr>';
 2325:     }
 2326:     my %defcell;
 2327:     foreach my $item (@usertools) {
 2328:         if ($context eq 'requestcourses') {
 2329:             my ($curroption,$currlimit);
 2330:             if (ref($settings) eq 'HASH') {
 2331:                 if (ref($settings->{$item}) eq 'HASH') {
 2332:                     $curroption = $settings->{$item}->{'default'};
 2333:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 2334:                         $currlimit = $1;
 2335:                     }
 2336:                 }
 2337:             }
 2338:             if (!$curroption) {
 2339:                 $curroption = 'norequest';
 2340:             }
 2341:             $datatable .= '<th>'.$titles{$item}.'</th>';
 2342:             foreach my $option (@options) {
 2343:                 my $val = $option;
 2344:                 if ($option eq 'norequest') {
 2345:                     $val = 0;
 2346:                 }
 2347:                 if ($option eq 'validate') {
 2348:                     my $canvalidate = 0;
 2349:                     if (ref($validations{$item}) eq 'HASH') {
 2350:                         if ($validations{$item}{'default'}) {
 2351:                             $canvalidate = 1;
 2352:                         }
 2353:                     }
 2354:                     next if (!$canvalidate);
 2355:                 }
 2356:                 my $checked = '';
 2357:                 if ($option eq $curroption) {
 2358:                     $checked = ' checked="checked"';
 2359:                 } elsif ($option eq 'autolimit') {
 2360:                     if ($curroption =~ /^autolimit/) {
 2361:                         $checked = ' checked="checked"';
 2362:                     }
 2363:                 }
 2364:                 $defcell{$item} .= '<span class="LC_nobreak"><label>'.
 2365:                                   '<input type="radio" name="crsreq_'.$item.
 2366:                                   '_default" value="'.$val.'"'.$checked.' />'.
 2367:                                   $titles{$option}.'</label>';
 2368:                 if ($option eq 'autolimit') {
 2369:                     $defcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2370:                                        $item.'_limit_default" size="1" '.
 2371:                                        'value="'.$currlimit.'" />';
 2372:                 }
 2373:                 $defcell{$item} .= '</span> ';
 2374:                 if ($option eq 'autolimit') {
 2375:                     $defcell{$item} .= $titles{'unlimited'};
 2376:                 }
 2377:             }
 2378:         } elsif ($context eq 'requestauthor') {
 2379:             my $curroption;
 2380:             if (ref($settings) eq 'HASH') {
 2381:                 $curroption = $settings->{'default'};
 2382:             }
 2383:             if (!$curroption) {
 2384:                 $curroption = 'norequest';
 2385:             }
 2386:             foreach my $option (@options) {
 2387:                 my $val = $option;
 2388:                 if ($option eq 'norequest') {
 2389:                     $val = 0;
 2390:                 }
 2391:                 my $checked = '';
 2392:                 if ($option eq $curroption) {
 2393:                     $checked = ' checked="checked"';
 2394:                 }
 2395:                 $datatable .= '<span class="LC_nobreak"><label>'.
 2396:                               '<input type="radio" name="authorreq_default"'.
 2397:                               ' value="'.$val.'"'.$checked.' />'.
 2398:                               $titles{$option}.'</label></span>&nbsp; ';
 2399:             }
 2400:         } else {
 2401:             my $checked = 'checked="checked" ';
 2402:             if (ref($settings) eq 'HASH') {
 2403:                 if (ref($settings->{$item}) eq 'HASH') {
 2404:                     if ($settings->{$item}->{'default'} == 0) {
 2405:                         $checked = '';
 2406:                     } elsif ($settings->{$item}->{'default'} == 1) {
 2407:                         $checked = 'checked="checked" ';
 2408:                     }
 2409:                 }
 2410:             }
 2411:             $datatable .= '<span class="LC_nobreak"><label>'.
 2412:                           '<input type="checkbox" name="'.$context.'_'.$item.
 2413:                           '" value="default" '.$checked.'/>'.$titles{$item}.
 2414:                           '</label></span>&nbsp; ';
 2415:         }
 2416:     }
 2417:     if ($context eq 'requestcourses') {
 2418:         $datatable .= '</tr><tr>';
 2419:         foreach my $item (@usertools) {
 2420:             $datatable .= '<td style="vertical-align: top">'.$defcell{$item}.'</td>';
 2421:         }
 2422:         $datatable .= '</tr></table>';
 2423:     }
 2424:     $datatable .= '</td>';
 2425:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 2426:         $datatable .= '<td class="LC_right_item">'.
 2427:                       '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 2428:                       '<input type="text" name="defaultquota" value="'.
 2429:                       $defaultquota.'" size="5" /></span>'.('&nbsp;' x2).
 2430:                       '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 2431:                       '<input type="text" name="authorquota" value="'.
 2432:                       $authorquota.'" size="5" /></span></td>';
 2433:     }
 2434:     $datatable .= '</tr>';
 2435:     $typecount ++;
 2436:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 2437:     $datatable .= '<tr'.$css_class.'>'.
 2438:                   '<td>'.&mt('LON-CAPA Advanced Users').'<br />';
 2439:     if ($context eq 'requestcourses') {
 2440:         $datatable .= &mt('(overrides affiliation, if set)').
 2441:                       '</td>'.
 2442:                       '<td class="LC_left_item">'.
 2443:                       '<table><tr>';
 2444:     } else {
 2445:         $datatable .= &mt('(overrides affiliation, if checked)').
 2446:                       '</td>'.
 2447:                       '<td class="LC_left_item" colspan="2">'.
 2448:                       '<br />';
 2449:     }
 2450:     my %advcell;
 2451:     foreach my $item (@usertools) {
 2452:         if ($context eq 'requestcourses') {
 2453:             my ($curroption,$currlimit);
 2454:             if (ref($settings) eq 'HASH') {
 2455:                 if (ref($settings->{$item}) eq 'HASH') {
 2456:                     $curroption = $settings->{$item}->{'_LC_adv'};
 2457:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 2458:                         $currlimit = $1;
 2459:                     }
 2460:                 }
 2461:             }
 2462:             $datatable .= '<th>'.$titles{$item}.'</th>';
 2463:             my $checked = '';
 2464:             if ($curroption eq '') {
 2465:                 $checked = ' checked="checked"';
 2466:             }
 2467:             $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2468:                                '<input type="radio" name="crsreq_'.$item.
 2469:                                '__LC_adv" value=""'.$checked.' />'.
 2470:                                &mt('No override set').'</label></span>&nbsp; ';
 2471:             foreach my $option (@options) {
 2472:                 my $val = $option;
 2473:                 if ($option eq 'norequest') {
 2474:                     $val = 0;
 2475:                 }
 2476:                 if ($option eq 'validate') {
 2477:                     my $canvalidate = 0;
 2478:                     if (ref($validations{$item}) eq 'HASH') {
 2479:                         if ($validations{$item}{'_LC_adv'}) {
 2480:                             $canvalidate = 1;
 2481:                         }
 2482:                     }
 2483:                     next if (!$canvalidate);
 2484:                 }
 2485:                 my $checked = '';
 2486:                 if ($val eq $curroption) {
 2487:                     $checked = ' checked="checked"';
 2488:                 } elsif ($option eq 'autolimit') {
 2489:                     if ($curroption =~ /^autolimit/) {
 2490:                         $checked = ' checked="checked"';
 2491:                     }
 2492:                 }
 2493:                 $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2494:                                   '<input type="radio" name="crsreq_'.$item.
 2495:                                   '__LC_adv" value="'.$val.'"'.$checked.' />'.
 2496:                                   $titles{$option}.'</label>';
 2497:                 if ($option eq 'autolimit') {
 2498:                     $advcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2499:                                        $item.'_limit__LC_adv" size="1" '.
 2500:                                        'value="'.$currlimit.'" />';
 2501:                 }
 2502:                 $advcell{$item} .= '</span> ';
 2503:                 if ($option eq 'autolimit') {
 2504:                     $advcell{$item} .= $titles{'unlimited'};
 2505:                 }
 2506:             }
 2507:         } elsif ($context eq 'requestauthor') {
 2508:             my $curroption;
 2509:             if (ref($settings) eq 'HASH') {
 2510:                 $curroption = $settings->{'_LC_adv'};
 2511:             }
 2512:             my $checked = '';
 2513:             if ($curroption eq '') {
 2514:                 $checked = ' checked="checked"';
 2515:             }
 2516:             $datatable .= '<span class="LC_nobreak"><label>'.
 2517:                           '<input type="radio" name="authorreq__LC_adv"'.
 2518:                           ' value=""'.$checked.' />'.
 2519:                           &mt('No override set').'</label></span>&nbsp; ';
 2520:             foreach my $option (@options) {
 2521:                 my $val = $option;
 2522:                 if ($option eq 'norequest') {
 2523:                     $val = 0;
 2524:                 }
 2525:                 my $checked = '';
 2526:                 if ($val eq $curroption) {
 2527:                     $checked = ' checked="checked"';
 2528:                 }
 2529:                 $datatable .= '<span class="LC_nobreak"><label>'.
 2530:                               '<input type="radio" name="authorreq__LC_adv"'.
 2531:                               ' value="'.$val.'"'.$checked.' />'.
 2532:                               $titles{$option}.'</label></span>&nbsp; ';
 2533:             }
 2534:         } else {
 2535:             my $checked = 'checked="checked" ';
 2536:             if (ref($settings) eq 'HASH') {
 2537:                 if (ref($settings->{$item}) eq 'HASH') {
 2538:                     if ($settings->{$item}->{'_LC_adv'} == 0) {
 2539:                         $checked = '';
 2540:                     } elsif ($settings->{$item}->{'_LC_adv'} == 1) {
 2541:                         $checked = 'checked="checked" ';
 2542:                     }
 2543:                 }
 2544:             }
 2545:             $datatable .= '<span class="LC_nobreak"><label>'.
 2546:                           '<input type="checkbox" name="'.$context.'_'.$item.
 2547:                           '" value="_LC_adv" '.$checked.'/>'.$titles{$item}.
 2548:                           '</label></span>&nbsp; ';
 2549:         }
 2550:     }
 2551:     if ($context eq 'requestcourses') {
 2552:         $datatable .= '</tr><tr>';
 2553:         foreach my $item (@usertools) {
 2554:             $datatable .= '<td style="vertical-align: top">'.$advcell{$item}.'</td>';
 2555:         }
 2556:         $datatable .= '</tr></table>';
 2557:     }
 2558:     $datatable .= '</td></tr>';
 2559:     $$rowtotal += $typecount;
 2560:     return $datatable;
 2561: }
 2562: 
 2563: sub print_requestmail {
 2564:     my ($dom,$action,$settings,$rowtotal,$customcss,$rowstyle) = @_;
 2565:     my ($now,$datatable,%currapp);
 2566:     $now = time;
 2567:     if (ref($settings) eq 'HASH') {
 2568:         if (ref($settings->{'notify'}) eq 'HASH') {
 2569:             if ($settings->{'notify'}{'approval'} ne '') {
 2570:                 map {$currapp{$_}=1;} split(/,/,$settings->{'notify'}{'approval'});
 2571:             }
 2572:         }
 2573:     }
 2574:     my $numinrow = 2;
 2575:     my $css_class;
 2576:     if ($$rowtotal%2) {
 2577:         $css_class = 'LC_odd_row';
 2578:     }
 2579:     if ($customcss) {
 2580:         $css_class .= " $customcss";
 2581:     }
 2582:     $css_class =~ s/^\s+//;
 2583:     if ($css_class) {
 2584:         $css_class = ' class="'.$css_class.'"';
 2585:     }
 2586:     if ($rowstyle) {
 2587:         $css_class .= ' style="'.$rowstyle.'"';
 2588:     }
 2589:     my $text;
 2590:     if ($action eq 'requestcourses') {
 2591:         $text = &mt('Receive notification of course requests requiring approval');
 2592:     } elsif ($action eq 'requestauthor') {
 2593:         $text = &mt('Receive notification of Authoring Space requests requiring approval');
 2594:     } else {
 2595:        $text = &mt('Receive notification of queued requests for self-created user accounts requiring approval');
 2596:     }
 2597:     $datatable = '<tr'.$css_class.'>'.
 2598:                  ' <td>'.$text.'</td>'.
 2599:                  ' <td class="LC_left_item">';
 2600:     my ($numdc,$table,$rows) = &active_dc_picker($dom,$numinrow,'checkbox',
 2601:                                                  $action.'notifyapproval',%currapp);
 2602:     if ($numdc > 0) {
 2603:         $datatable .= $table;
 2604:     } else {
 2605:         $datatable .= &mt('There are no active Domain Coordinators');
 2606:     }
 2607:     $datatable .='</td></tr>';
 2608:     return $datatable;
 2609: }
 2610: 
 2611: sub print_studentcode {
 2612:     my ($settings,$rowtotal) = @_;
 2613:     my $rownum = 0; 
 2614:     my ($output,%current);
 2615:     my @crstypes = ('official','unofficial','community','textbook');
 2616:     if (ref($settings) eq 'HASH') {
 2617:         if (ref($settings->{'uniquecode'}) eq 'HASH') {
 2618:             foreach my $type (@crstypes) {
 2619:                 $current{$type} = $settings->{'uniquecode'}{$type};
 2620:             }
 2621:         }
 2622:     }
 2623:     $output .= '<tr>'.
 2624:                '<td class="LC_left_item">'.&mt('Generate unique six character code as course identifier?').'</td>'.
 2625:                '<td class="LC_left_item">';
 2626:     foreach my $type (@crstypes) {
 2627:         my $check = ' ';
 2628:         if ($current{$type}) {
 2629:             $check = ' checked="checked" ';
 2630:         }
 2631:         $output .= '<span class="LC_nobreak"><label>'.
 2632:                    '<input type="checkbox" name="uniquecode" value="'.$type.'"'.$check.'/>'.
 2633:                    &mt($type).'</label></span>'.('&nbsp;'x2).' ';
 2634:     }
 2635:     $output .= '</td></tr>';
 2636:     $$rowtotal ++;
 2637:     return $output;
 2638: }
 2639: 
 2640: sub print_textbookcourses {
 2641:     my ($dom,$type,$settings,$rowtotal) = @_;
 2642:     my $rownum = 0;
 2643:     my $css_class;
 2644:     my $itemcount = 1;
 2645:     my $maxnum = 0;
 2646:     my $bookshash;
 2647:     if (ref($settings) eq 'HASH') {
 2648:         $bookshash = $settings->{$type};
 2649:     }
 2650:     my %ordered;
 2651:     if (ref($bookshash) eq 'HASH') {
 2652:         foreach my $item (keys(%{$bookshash})) {
 2653:             if (ref($bookshash->{$item}) eq 'HASH') {
 2654:                 my $num = $bookshash->{$item}{'order'};
 2655:                 $ordered{$num} = $item;
 2656:             }
 2657:         }
 2658:     }
 2659:     my $confname = $dom.'-domainconfig';
 2660:     my $switchserver = &check_switchserver($dom,$confname);
 2661:     my $maxnum = scalar(keys(%ordered));
 2662:     my $datatable;
 2663:     if (keys(%ordered)) {
 2664:         my @items = sort { $a <=> $b } keys(%ordered);
 2665:         for (my $i=0; $i<@items; $i++) {
 2666:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2667:             my $key = $ordered{$items[$i]};
 2668:             my %coursehash=&Apache::lonnet::coursedescription($key);
 2669:             my $coursetitle = $coursehash{'description'};
 2670:             my ($subject,$title,$author,$publisher,$image,$imgsrc,$cdom,$cnum);
 2671:             if (ref($bookshash->{$key}) eq 'HASH') {
 2672:                 $subject = $bookshash->{$key}->{'subject'};
 2673:                 $title = $bookshash->{$key}->{'title'};
 2674:                 if ($type eq 'textbooks') {
 2675:                     $publisher = $bookshash->{$key}->{'publisher'};
 2676:                     $author = $bookshash->{$key}->{'author'};
 2677:                     $image = $bookshash->{$key}->{'image'};
 2678:                     if ($image ne '') {
 2679:                         my ($path,$imagefile) = ($image =~ m{^(.+)/([^/]+)$});
 2680:                         my $imagethumb = "$path/tn-".$imagefile;
 2681:                         $imgsrc = '<img src="'.$imagethumb.'" alt="'.&mt('Textbook image').'" />';
 2682:                     }
 2683:                 }
 2684:             }
 2685:             my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type".'_'."$key','$type'".');"';
 2686:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 2687:                          .'<select name="'.$type.'_'.$key.'"'.$chgstr.'>';
 2688:             for (my $k=0; $k<=$maxnum; $k++) {
 2689:                 my $vpos = $k+1;
 2690:                 my $selstr;
 2691:                 if ($k == $i) {
 2692:                     $selstr = ' selected="selected" ';
 2693:                 }
 2694:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2695:             }
 2696:             $datatable .= '</select>'.('&nbsp;'x2).
 2697:                 '<label><input type="checkbox" name="'.$type.'_del" value="'.$key.'" />'.
 2698:                 &mt('Delete?').'</label></span></td>'.
 2699:                 '<td colspan="2">'.
 2700:                 '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_subject_'.$i.'" value="'.$subject.'" /></span> '.
 2701:                 ('&nbsp;'x2).
 2702:                 '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_title_'.$i.'" value="'.$title.'" /></span> ';
 2703:             if ($type eq 'textbooks') {
 2704:                 $datatable .= ('&nbsp;'x2).
 2705:                               '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_publisher_'.$i.'" value="'.$publisher.'" /></span> '.
 2706:                               ('&nbsp;'x2).
 2707:                               '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_author_'.$i.'" value="'.$author.'" /></span> '.
 2708:                               ('&nbsp;'x2).
 2709:                               '<span class="LC_nobreak">'.&mt('Thumbnail:');
 2710:                 if ($image) {
 2711:                     $datatable .= $imgsrc.
 2712:                                   '<label><input type="checkbox" name="'.$type.'_image_del"'.
 2713:                                   ' value="'.$key.'" />'.&mt('Delete?').'</label></span> '.
 2714:                                   '<span class="LC_nobreak">&nbsp;'.&mt('Replace:').'&nbsp;';
 2715:                 }
 2716:                 if ($switchserver) {
 2717:                     $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2718:                 } else {
 2719:                     $datatable .= '<input type="file" name="'.$type.'_image_'.$i.'" value="" />';
 2720:                 }
 2721:             }
 2722:             $datatable .= '<input type="hidden" name="'.$type.'_id_'.$i.'" value="'.$type.'_'.$key.'" /></span> '.
 2723:                           '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 2724:                           $coursetitle.'</span></td></tr>'."\n";
 2725:             $itemcount ++;
 2726:         }
 2727:     }
 2728:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2729:     my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type"."_addbook_pos','$type'".');"';
 2730:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 2731:                   '<input type="hidden" name="'.$type.'_maxnum" value="'.$maxnum.'" />'."\n".
 2732:                   '<select name="'.$type.'_addbook_pos"'.$chgstr.'>';
 2733:     for (my $k=0; $k<$maxnum+1; $k++) {
 2734:         my $vpos = $k+1;
 2735:         my $selstr;
 2736:         if ($k == $maxnum) {
 2737:             $selstr = ' selected="selected" ';
 2738:         }
 2739:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2740:     }
 2741:     $datatable .= '</select>&nbsp;'."\n".
 2742:                   '<input type="checkbox" name="'.$type.'_addbook" value="1" />'.&mt('Add').'</span></td>'."\n".
 2743:                   '<td colspan="2">'.
 2744:                   '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_addbook_subject" value="" /></span> '."\n".
 2745:                   ('&nbsp;'x2).
 2746:                   '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_addbook_title" value="" /></span> '."\n".
 2747:                   ('&nbsp;'x2);
 2748:     if ($type eq 'textbooks') {
 2749:         $datatable .= '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_addbook_publisher" value="" /></span> '."\n".
 2750:                       ('&nbsp;'x2).
 2751:                       '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_addbook_author" value="" /></span> '."\n".
 2752:                       ('&nbsp;'x2).
 2753:                       '<span class="LC_nobreak">'.&mt('Image:').'&nbsp;';
 2754:         if ($switchserver) {
 2755:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2756:         } else {
 2757:             $datatable .= '<input type="file" name="'.$type.'_addbook_image" value="" />';
 2758:         }
 2759:         $datatable .= '</span>'."\n";
 2760:     }
 2761:     $datatable .= '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 2762:                   &Apache::loncommon::select_dom_form($env{'request.role.domain'},$type.'_addbook_cdom').
 2763:                   '<input type="text" size="25" name="'.$type.'_addbook_cnum" value="" />'.
 2764:                   &Apache::loncommon::selectcourse_link
 2765:                       ('display',$type.'_addbook_cnum',$type.'_addbook_cdom',undef,undef,undef,'Course').
 2766:                   '</span></td>'."\n".
 2767:                   '</tr>'."\n";
 2768:     $itemcount ++;
 2769:     return $datatable;
 2770: }
 2771: 
 2772: sub textbookcourses_javascript {
 2773:     my ($settings) = @_;
 2774:     return unless(ref($settings) eq 'HASH');
 2775:     my (%ordered,%total,%jstext);
 2776:     foreach my $type ('textbooks','templates') {
 2777:         $total{$type} = 0;
 2778:         if (ref($settings->{$type}) eq 'HASH') {
 2779:             foreach my $item (keys(%{$settings->{$type}})) {
 2780:                 if (ref($settings->{$type}->{$item}) eq 'HASH') {
 2781:                     my $num = $settings->{$type}->{$item}{'order'};
 2782:                     $ordered{$type}{$num} = $item;
 2783:                 }
 2784:             }
 2785:             $total{$type} = scalar(keys(%{$settings->{$type}}));
 2786:         }
 2787:         my @jsarray = ();
 2788:         foreach my $item (sort {$a <=> $b } (keys(%{$ordered{$type}}))) {
 2789:             push(@jsarray,$ordered{$type}{$item});
 2790:         }
 2791:         $jstext{$type} = '    var '.$type.' = Array('."'".join("','",@jsarray)."'".');'."\n";
 2792:     }
 2793:     return <<"ENDSCRIPT";
 2794: <script type="text/javascript">
 2795: // <![CDATA[
 2796: function reorderBooks(form,item,caller) {
 2797:     var changedVal;
 2798: $jstext{'textbooks'};
 2799: $jstext{'templates'};
 2800:     var newpos;
 2801:     var maxh;
 2802:     if (caller == 'textbooks') {  
 2803:         newpos = 'textbooks_addbook_pos';
 2804:         maxh = 1 + $total{'textbooks'};
 2805:     } else {
 2806:         newpos = 'templates_addbook_pos';
 2807:         maxh = 1 + $total{'templates'};
 2808:     }
 2809:     var current = new Array;
 2810:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 2811:     if (item == newpos) {
 2812:         changedVal = newitemVal;
 2813:     } else {
 2814:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 2815:         current[newitemVal] = newpos;
 2816:     }
 2817:     if (caller == 'textbooks') {
 2818:         for (var i=0; i<textbooks.length; i++) {
 2819:             var elementName = 'textbooks_'+textbooks[i];
 2820:             if (elementName != item) {
 2821:                 if (form.elements[elementName]) {
 2822:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 2823:                     current[currVal] = elementName;
 2824:                 }
 2825:             }
 2826:         }
 2827:     }
 2828:     if (caller == 'templates') {
 2829:         for (var i=0; i<templates.length; i++) {
 2830:             var elementName = 'templates_'+templates[i];
 2831:             if (elementName != item) {
 2832:                 if (form.elements[elementName]) {
 2833:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 2834:                     current[currVal] = elementName;
 2835:                 }
 2836:             }
 2837:         }
 2838:     }
 2839:     var oldVal;
 2840:     for (var j=0; j<maxh; j++) {
 2841:         if (current[j] == undefined) {
 2842:             oldVal = j;
 2843:         }
 2844:     }
 2845:     if (oldVal < changedVal) {
 2846:         for (var k=oldVal+1; k<=changedVal ; k++) {
 2847:            var elementName = current[k];
 2848:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 2849:         }
 2850:     } else {
 2851:         for (var k=changedVal; k<oldVal; k++) {
 2852:             var elementName = current[k];
 2853:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 2854:         }
 2855:     }
 2856:     return;
 2857: }
 2858: 
 2859: // ]]>
 2860: </script>
 2861: 
 2862: ENDSCRIPT
 2863: }
 2864: 
 2865: sub ltitools_javascript {
 2866:     my ($settings) = @_;
 2867:     my $togglejs = &ltitools_toggle_js();
 2868:     unless (ref($settings) eq 'HASH') {
 2869:         return $togglejs;
 2870:     }
 2871:     my (%ordered,$total,%jstext);
 2872:     $total = 0;
 2873:     foreach my $item (keys(%{$settings})) {
 2874:         if (ref($settings->{$item}) eq 'HASH') {
 2875:             my $num = $settings->{$item}{'order'};
 2876:             $ordered{$num} = $item;
 2877:         }
 2878:     }
 2879:     $total = scalar(keys(%{$settings}));
 2880:     my @jsarray = ();
 2881:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 2882:         push(@jsarray,$ordered{$item});
 2883:     }
 2884:     my $jstext = '    var ltitools = Array('."'".join("','",@jsarray)."'".');'."\n";
 2885:     return <<"ENDSCRIPT";
 2886: <script type="text/javascript">
 2887: // <![CDATA[
 2888: function reorderLTITools(form,item) {
 2889:     var changedVal;
 2890: $jstext
 2891:     var newpos = 'ltitools_add_pos';
 2892:     var maxh = 1 + $total;
 2893:     var current = new Array;
 2894:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 2895:     if (item == newpos) {
 2896:         changedVal = newitemVal;
 2897:     } else {
 2898:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 2899:         current[newitemVal] = newpos;
 2900:     }
 2901:     for (var i=0; i<ltitools.length; i++) {
 2902:         var elementName = 'ltitools_'+ltitools[i];
 2903:         if (elementName != item) {
 2904:             if (form.elements[elementName]) {
 2905:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 2906:                 current[currVal] = elementName;
 2907:             }
 2908:         }
 2909:     }
 2910:     var oldVal;
 2911:     for (var j=0; j<maxh; j++) {
 2912:         if (current[j] == undefined) {
 2913:             oldVal = j;
 2914:         }
 2915:     }
 2916:     if (oldVal < changedVal) {
 2917:         for (var k=oldVal+1; k<=changedVal ; k++) {
 2918:            var elementName = current[k];
 2919:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 2920:         }
 2921:     } else {
 2922:         for (var k=changedVal; k<oldVal; k++) {
 2923:             var elementName = current[k];
 2924:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 2925:         }
 2926:     }
 2927:     return;
 2928: }
 2929: 
 2930: // ]]>
 2931: </script>
 2932: 
 2933: $togglejs
 2934: 
 2935: ENDSCRIPT
 2936: }
 2937: 
 2938: sub ltitools_toggle_js {
 2939:     return <<"ENDSCRIPT";
 2940: <script type="text/javascript">
 2941: // <![CDATA[
 2942: 
 2943: function toggleLTITools(form,setting,item) {
 2944:     var radioname = '';
 2945:     var divid = '';
 2946:     if (setting == 'user') {
 2947:         divid = 'ltitools_'+setting+'_div_'+item;
 2948:         var checkid = 'ltitools_'+setting+'_field_'+item;
 2949:         if (document.getElementById(divid)) {
 2950:             if (document.getElementById(checkid)) {
 2951:                 if (document.getElementById(checkid).checked) {
 2952:                     document.getElementById(divid).style.display = 'inline-block';
 2953:                 } else {
 2954:                     document.getElementById(divid).style.display = 'none';
 2955:                 }
 2956:             }
 2957:         }
 2958:     }
 2959:     return;
 2960: }
 2961: // ]]>
 2962: </script>
 2963: 
 2964: ENDSCRIPT
 2965: }
 2966: 
 2967: sub wafproxy_javascript {
 2968:     my ($dom) = @_;
 2969:     return <<"ENDSCRIPT";
 2970: <script type="text/javascript">
 2971: // <![CDATA[
 2972: function updateWAF() {
 2973:     if (document.getElementById('wafproxy_remoteip')) {
 2974:         var wafremote = 0;
 2975:         if (document.display.wafproxy_remoteip.options[document.display.wafproxy_remoteip.selectedIndex].value == 'h') {
 2976:             wafremote = 1;
 2977:         }
 2978:         var fields = new Array('header','trust');
 2979:         for (var i=0; i<fields.length; i++) {
 2980:             if (document.getElementById('wafproxy_'+fields[i])) {
 2981:                 if (wafremote == 1) {
 2982:                     document.getElementById('wafproxy_'+fields[i]).style.display = 'table-row';
 2983:                 }
 2984:                 else {
 2985:                     document.getElementById('wafproxy_'+fields[i]).style.display = 'none';
 2986:                 }
 2987:             }
 2988:         }
 2989:         if (document.getElementById('wafproxyranges_$dom')) {
 2990:             if (wafremote == 1) {
 2991:                 document.getElementById('wafproxyranges_$dom').style.display = 'inline-block';
 2992:             } else {
 2993:                 for (var i=0; i<document.display.wafproxy_vpnaccess.length; i++) {
 2994:                     if (document.display.wafproxy_vpnaccess[i].checked) {
 2995:                         if (document.display.wafproxy_vpnaccess[i].value == 0) {
 2996:                             document.getElementById('wafproxyranges_$dom').style.display = 'none';
 2997:                         }
 2998:                     }
 2999:                 }
 3000:             }
 3001:         }
 3002:     }
 3003:     return;
 3004: }
 3005: 
 3006: function checkWAF() {
 3007:     if (document.getElementById('wafproxy_remoteip')) {
 3008:         var wafvpn = 0;
 3009:         for (var i=0; i<document.display.wafproxy_vpnaccess.length; i++) {
 3010:             if (document.display.wafproxy_vpnaccess[i].checked) {
 3011:                 if (document.display.wafproxy_vpnaccess[i].value == 1) {
 3012:                     wafvpn = 1;
 3013:                 }
 3014:                 break;
 3015:             }
 3016:         }
 3017:         var vpn = new Array('vpnint','vpnext');
 3018:         for (var i=0; i<vpn.length; i++) {
 3019:             if (document.getElementById('wafproxy_show_'+vpn[i])) {
 3020:                 if (wafvpn == 1) {
 3021:                     document.getElementById('wafproxy_show_'+vpn[i]).style.display = 'table-row';
 3022:                 }
 3023:                 else {
 3024:                     document.getElementById('wafproxy_show_'+vpn[i]).style.display = 'none';
 3025:                 }
 3026:             }
 3027:         }
 3028:         if (document.getElementById('wafproxyranges_$dom')) {
 3029:             if (wafvpn == 1) {
 3030:                 document.getElementById('wafproxyranges_$dom').style.display = 'inline-block';
 3031:             }
 3032:             else if (document.display.wafproxy_remoteip.options[document.display.wafproxy_remoteip.selectedIndex].value != 'h') {
 3033:                 document.getElementById('wafproxyranges_$dom').style.display = 'none';
 3034:             }
 3035:         }
 3036:     }
 3037:     return;
 3038: }
 3039: 
 3040: function toggleWAF() {
 3041:     if (document.getElementById('wafproxy_table')) {
 3042:         var wafproxy = 0;
 3043:         for (var i=0; i<document.display.wafproxy_${dom}.length; i++) {
 3044:              if (document.display.wafproxy_${dom}[i].checked) {
 3045:                  if (document.display.wafproxy_${dom}[i].value == 1) {
 3046:                      wafproxy = 1;
 3047:                      break;
 3048:                 }
 3049:             }
 3050:         }
 3051:         if (wafproxy == 1) {
 3052:             document.getElementById('wafproxy_table').style.display='inline';
 3053:         }
 3054:         else {
 3055:            document.getElementById('wafproxy_table').style.display='none';
 3056:         }
 3057:         if (document.getElementById('wafproxyrow_${dom}')) {
 3058:             if (wafproxy == 1) {
 3059:                 document.getElementById('wafproxyrow_${dom}').style.display = 'table-row';
 3060:             }
 3061:             else {
 3062:                 document.getElementById('wafproxyrow_${dom}').style.display = 'none';
 3063:             }
 3064:         }
 3065:         if (document.getElementById('nowafproxyrow_$dom')) {
 3066:             if (wafproxy == 1) {
 3067:                 document.getElementById('nowafproxyrow_${dom}').style.display = 'none';
 3068:             }
 3069:             else {
 3070:                 document.getElementById('nowafproxyrow_${dom}').style.display = 'table-row';
 3071:             }
 3072:         }
 3073:     }
 3074:     return;
 3075: }
 3076: // ]]>
 3077: </script>
 3078: 
 3079: ENDSCRIPT
 3080: }
 3081: 
 3082: sub autoupdate_javascript {
 3083:     return <<"ENDSCRIPT";
 3084: <script type="text/javascript">
 3085: // <![CDATA[
 3086: function toggleLastActiveDays(form) {
 3087:     var radioname = 'lastactive';
 3088:     var divid = 'lastactive_div';
 3089:     var num = form.elements[radioname].length;
 3090:     if (num) {
 3091:         var setvis = '';
 3092:         for (var i=0; i<num; i++) {
 3093:             if (form.elements[radioname][i].checked) {
 3094:                 if (form.elements[radioname][i].value == '1') {
 3095:                     if (document.getElementById(divid)) {
 3096:                         document.getElementById(divid).style.display = 'inline-block';
 3097:                     }
 3098:                     setvis = 1;
 3099:                 }
 3100:                 break;
 3101:             }
 3102:         }
 3103:         if (!setvis) {
 3104:             if (document.getElementById(divid)) {
 3105:                 document.getElementById(divid).style.display = 'none';
 3106:             }
 3107:         }
 3108:     }
 3109:     return;
 3110: }
 3111: // ]]>
 3112: </script>
 3113: 
 3114: ENDSCRIPT
 3115: }
 3116: 
 3117: sub autoenroll_javascript {
 3118:     return <<"ENDSCRIPT";
 3119: <script type="text/javascript">
 3120: // <![CDATA[
 3121: function toggleFailsafe(form) {
 3122:     var radioname = 'autoenroll_failsafe';
 3123:     var divid = 'autoenroll_failsafe_div';
 3124:     var num = form.elements[radioname].length;
 3125:     if (num) {
 3126:         var setvis = '';
 3127:         for (var i=0; i<num; i++) {
 3128:             if (form.elements[radioname][i].checked) {
 3129:                 if ((form.elements[radioname][i].value == 'zero') || (form.elements[radioname][i].value == 'any')) {
 3130:                     if (document.getElementById(divid)) {
 3131:                         document.getElementById(divid).style.display = 'inline-block';
 3132:                     }
 3133:                     setvis = 1;
 3134:                 }
 3135:                 break;
 3136:             }
 3137:         }
 3138:         if (!setvis) {
 3139:             if (document.getElementById(divid)) {
 3140:                 document.getElementById(divid).style.display = 'none';
 3141:             }
 3142:         }
 3143:     }
 3144:     return;
 3145: }
 3146: // ]]>
 3147: </script>
 3148: 
 3149: ENDSCRIPT
 3150: }
 3151: 
 3152: sub saml_javascript {
 3153:     return <<"ENDSCRIPT";
 3154: <script type="text/javascript">
 3155: // <![CDATA[
 3156: function toggleSamlOptions(form,hostid) {
 3157:     var radioname = 'saml_'+hostid;
 3158:     var tablecellon = 'samloptionson_'+hostid;
 3159:     var tablecelloff = 'samloptionsoff_'+hostid;
 3160:     var num = form.elements[radioname].length;
 3161:     if (num) {
 3162:         var setvis = '';
 3163:         for (var i=0; i<num; i++) {
 3164:             if (form.elements[radioname][i].checked) {
 3165:                 if (form.elements[radioname][i].value == '1') {
 3166:                     if (document.getElementById(tablecellon)) {
 3167:                         document.getElementById(tablecellon).style.display='';
 3168:                     }
 3169:                     if (document.getElementById(tablecelloff)) {
 3170:                         document.getElementById(tablecelloff).style.display='none';
 3171:                     }
 3172:                     setvis = 1;
 3173:                 }
 3174:                 break;
 3175:             }
 3176:         }
 3177:         if (!setvis) {
 3178:             if (document.getElementById(tablecellon)) {
 3179:                 document.getElementById(tablecellon).style.display='none';
 3180:             }
 3181:             if (document.getElementById(tablecelloff)) {
 3182:                 document.getElementById(tablecelloff).style.display='';
 3183:             }
 3184:         }
 3185:     }
 3186:     return;
 3187: }
 3188: // ]]>
 3189: </script>
 3190: 
 3191: ENDSCRIPT
 3192: }
 3193: 
 3194: sub ipaccess_javascript {
 3195:     my ($settings) = @_;
 3196:     my (%ordered,$total,%jstext);
 3197:     $total = 0;
 3198:     if (ref($settings) eq 'HASH') {
 3199:         foreach my $item (keys(%{$settings})) {
 3200:             if (ref($settings->{$item}) eq 'HASH') {
 3201:                 my $num = $settings->{$item}{'order'};
 3202:                 $ordered{$num} = $item;
 3203:             }
 3204:         }
 3205:         $total = scalar(keys(%{$settings}));
 3206:     }
 3207:     my @jsarray = ();
 3208:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3209:         push(@jsarray,$ordered{$item});
 3210:     }
 3211:     my $jstext = '    var ipaccess = Array('."'".join("','",@jsarray)."'".');'."\n";
 3212:     return <<"ENDSCRIPT";
 3213: <script type="text/javascript">
 3214: // <![CDATA[
 3215: function reorderIPaccess(form,item) {
 3216:     var changedVal;
 3217: $jstext
 3218:     var newpos = 'ipaccess_pos_add';
 3219:     var maxh = 1 + $total;
 3220:     var current = new Array;
 3221:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 3222:     if (item == newpos) {
 3223:         changedVal = newitemVal;
 3224:     } else {
 3225:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3226:         current[newitemVal] = newpos;
 3227:     }
 3228:     for (var i=0; i<ipaccess.length; i++) {
 3229:         var elementName = 'ipaccess_pos_'+ipaccess[i];
 3230:         if (elementName != item) {
 3231:             if (form.elements[elementName]) {
 3232:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3233:                 current[currVal] = elementName;
 3234:             }
 3235:         }
 3236:     }
 3237:     var oldVal;
 3238:     for (var j=0; j<maxh; j++) {
 3239:         if (current[j] == undefined) {
 3240:             oldVal = j;
 3241:         }
 3242:     }
 3243:     if (oldVal < changedVal) {
 3244:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3245:            var elementName = current[k];
 3246:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3247:         }
 3248:     } else {
 3249:         for (var k=changedVal; k<oldVal; k++) {
 3250:             var elementName = current[k];
 3251:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3252:         }
 3253:     }
 3254:     return;
 3255: }
 3256: // ]]>
 3257: </script>
 3258: 
 3259: ENDSCRIPT
 3260: }
 3261: 
 3262: sub print_autoenroll {
 3263:     my ($dom,$settings,$rowtotal) = @_;
 3264:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
 3265:     my ($defdom,$runon,$runoff,$coownerson,$coownersoff,
 3266:         $failsafe,$autofailsafe,$failsafesty,%failsafechecked);
 3267:     $failsafesty = 'none';
 3268:     %failsafechecked = (
 3269:         off => ' checked="checked"',
 3270:     );
 3271:     if (ref($settings) eq 'HASH') {
 3272:         if (exists($settings->{'run'})) {
 3273:             if ($settings->{'run'} eq '0') {
 3274:                 $runoff = ' checked="checked" ';
 3275:                 $runon = ' ';
 3276:             } else {
 3277:                 $runon = ' checked="checked" ';
 3278:                 $runoff = ' ';
 3279:             }
 3280:         } else {
 3281:             if ($autorun) {
 3282:                 $runon = ' checked="checked" ';
 3283:                 $runoff = ' ';
 3284:             } else {
 3285:                 $runoff = ' checked="checked" ';
 3286:                 $runon = ' ';
 3287:             }
 3288:         }
 3289:         if (exists($settings->{'co-owners'})) {
 3290:             if ($settings->{'co-owners'} eq '0') {
 3291:                 $coownersoff = ' checked="checked" ';
 3292:                 $coownerson = ' ';
 3293:             } else {
 3294:                 $coownerson = ' checked="checked" ';
 3295:                 $coownersoff = ' ';
 3296:             }
 3297:         } else {
 3298:             $coownersoff = ' checked="checked" ';
 3299:             $coownerson = ' ';
 3300:         }
 3301:         if (exists($settings->{'sender_domain'})) {
 3302:             $defdom = $settings->{'sender_domain'};
 3303:         }
 3304:         if (exists($settings->{'failsafe'})) {
 3305:             $failsafe = $settings->{'failsafe'};
 3306:             if ($failsafe eq 'zero') {
 3307:                 $failsafechecked{'zero'} = ' checked="checked"';
 3308:                 $failsafechecked{'off'} = '';
 3309:                 $failsafesty = 'inline-block';
 3310:             } elsif ($failsafe eq 'any') {
 3311:                 $failsafechecked{'any'} = ' checked="checked"';
 3312:                 $failsafechecked{'off'} = '';
 3313:             }
 3314:             $autofailsafe = $settings->{'autofailsafe'};
 3315:         } elsif (exists($settings->{'autofailsafe'})) {
 3316:             $autofailsafe = $settings->{'autofailsafe'};
 3317:             if ($autofailsafe ne '') {
 3318:                 $failsafechecked{'zero'} = ' checked="checked"';
 3319:                 $failsafe = 'zero';
 3320:                 $failsafechecked{'off'} = '';
 3321:             }
 3322:         }
 3323:     } else {
 3324:         if ($autorun) {
 3325:             $runon = ' checked="checked" ';
 3326:             $runoff = ' ';
 3327:         } else {
 3328:             $runoff = ' checked="checked" ';
 3329:             $runon = ' ';
 3330:         }
 3331:     }
 3332:     my $domform = &Apache::loncommon::select_dom_form($defdom,'sender_domain',1);
 3333:     my $notif_sender;
 3334:     if (ref($settings) eq 'HASH') {
 3335:         $notif_sender = $settings->{'sender_uname'};
 3336:     }
 3337:     my $datatable='<tr class="LC_odd_row">'.
 3338:                   '<td>'.&mt('Auto-enrollment active?').'</td>'.
 3339:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3340:                   '<input type="radio" name="autoenroll_run"'.
 3341:                   $runon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3342:                   '<label><input type="radio" name="autoenroll_run"'.
 3343:                   $runoff.' value="0" />'.&mt('No').'</label></span></td>'.
 3344:                   '</tr><tr>'.
 3345:                   '<td>'.&mt('Notification messages - sender').
 3346:                   '</td><td class="LC_right_item"><span class="LC_nobreak">'.
 3347:                   &mt('username').':&nbsp;'.
 3348:                   '<input type="text" name="sender_uname" value="'.
 3349:                   $notif_sender.'" size="10" />&nbsp;&nbsp;'.&mt('domain').
 3350:                   ':&nbsp;'.$domform.'</span></td></tr>'.
 3351:                   '<tr class="LC_odd_row">'.
 3352:                   '<td>'.&mt('Automatically assign co-ownership').'</td>'.
 3353:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3354:                   '<input type="radio" name="autoassign_coowners"'.
 3355:                   $coownerson.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3356:                   '<label><input type="radio" name="autoassign_coowners"'.
 3357:                   $coownersoff.' value="0" />'.&mt('No').'</label></span></td>'.
 3358:                   '</tr><tr>'.
 3359:                   '<td>'.&mt('Failsafe for no drops when institutional data missing').'</td>'.
 3360:                   '<td class="LC_left_item"><span class="LC_nobreak">'.
 3361:                   '<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; '.
 3362:                   '<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 />'.
 3363:                   '<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>'.
 3364:                   '<div class="LC_floatleft" style="display:'.$failsafesty.';" id="autoenroll_failsafe_div">'.
 3365:                   '<span class="LC_nobreak">'.
 3366:                   &mt('Threshold for number of students in section to drop: [_1]',
 3367:                       '<input type="text" name="autoenroll_autofailsafe" value="'.$autofailsafe.'" size="4" />').
 3368:                   '</span></div></td></tr>';
 3369:     $$rowtotal += 4;
 3370:     return $datatable;
 3371: }
 3372: 
 3373: sub print_autoupdate {
 3374:     my ($position,$dom,$settings,$rowtotal) = @_;
 3375:     my ($enable,$datatable);
 3376:     if ($position eq 'top') {
 3377:         my %choices = &Apache::lonlocal::texthash (
 3378:                           run        => 'Auto-update active?',
 3379:                           classlists => 'Update information in classlists?',
 3380:                           unexpired  => 'Skip updates for users without active or future roles?',
 3381:                           lastactive => 'Skip updates for inactive users?',
 3382:         );
 3383:         my $itemcount = 0;
 3384:         my $updateon = ' ';
 3385:         my $updateoff = ' checked="checked" ';
 3386:         if (ref($settings) eq 'HASH') {
 3387:             if ($settings->{'run'} eq '1') {
 3388:                 $updateon = $updateoff;
 3389:                 $updateoff = ' ';
 3390:             }
 3391:         }
 3392:         $enable = '<tr class="LC_odd_row">'. 
 3393:                   '<td>'.&mt($choices{'run'}).'</td>'.
 3394:                   '<td class="LC_left_item"><span class="LC_nobreak"><label>'.
 3395:                   '<input type="radio" name="autoupdate_run"'.
 3396:                   $updateoff.'value="0" />'.&mt('No').'</label>&nbsp;'.
 3397:                   '<label><input type="radio" name="autoupdate_run"'.
 3398:                   $updateon.'value="1" />'.&mt('Yes').'</label></span></td>'.
 3399:                   '</tr>';
 3400:         my @toggles = ('classlists','unexpired');
 3401:         my %defaultchecked = ('classlists' => 'off',
 3402:                               'unexpired'  => 'off'
 3403:                               );
 3404:         $$rowtotal ++;
 3405:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 3406:                                                      \%choices,$itemcount,'','','left','no');
 3407:         $datatable = $enable.$datatable;
 3408:         $$rowtotal += $itemcount;
 3409:         my $lastactiveon = ' ';
 3410:         my $lastactiveoff = ' checked="checked" ';
 3411:         my $lastactivestyle = 'none';
 3412:         my $lastactivedays;
 3413:         my $onclick = ' onclick="javascript:toggleLastActiveDays(this.form);"';
 3414:         if (ref($settings) eq 'HASH') {
 3415:             if ($settings->{'lastactive'} =~ /^\d+$/) {
 3416:                 $lastactiveon = $lastactiveoff;
 3417:                 $lastactiveoff = ' ';
 3418:                 $lastactivestyle = 'inline-block';
 3419:                 $lastactivedays = $settings->{'lastactive'};
 3420:             }
 3421:         }
 3422:         my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 3423:         $datatable .= '<tr'.$css_class.'>'.
 3424:                       '<td>'.$choices{'lastactive'}.'</td>'.
 3425:                       '<td class="LC_left_item"><span class="LC_nobreak"><label>'.
 3426:                       '<input type="radio" name="lastactive"'.
 3427:                       $lastactiveoff.'value="0"'.$onclick.' />'.&mt('No').'</label>'.
 3428:                       '&nbsp;<label>'.
 3429:                       '<input type="radio" name="lastactive"'.
 3430:                       $lastactiveon.' value="1"'.$onclick.' />'.&mt('Yes').'</label>'.
 3431:                       '<div id="lastactive_div" style="display:'.$lastactivestyle.';">'.
 3432:                       ':&nbsp;'.&mt('inactive = no activity in last [_1] days',
 3433:                           '<input type="text" size="5" name="lastactivedays" value="'.
 3434:                           $lastactivedays.'" />').
 3435:                       '</span></td>'.
 3436:                       '</tr>';
 3437:         $$rowtotal ++;
 3438:     } elsif ($position eq 'middle') {
 3439:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3440:         my $numinrow = 3;
 3441:         my $locknamesettings;
 3442:         $datatable .= &insttypes_row($settings,$types,$usertypes,
 3443:                                      $dom,$numinrow,$othertitle,
 3444:                                     'lockablenames',$rowtotal);
 3445:         $$rowtotal ++;
 3446:     } else {
 3447:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3448:         my @fields = ('lastname','firstname','middlename','generation',
 3449:                       'permanentemail','id');
 3450:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3451:         my $numrows = 0;
 3452:         if (ref($types) eq 'ARRAY') {
 3453:             if (@{$types} > 0) {
 3454:                 $datatable = 
 3455:                     &usertype_update_row($settings,$usertypes,\%fieldtitles,
 3456:                                          \@fields,$types,\$numrows);
 3457:                     $$rowtotal += @{$types}; 
 3458:             }
 3459:         }
 3460:         $datatable .= 
 3461:             &usertype_update_row($settings,{'default' => $othertitle},
 3462:                                  \%fieldtitles,\@fields,['default'],
 3463:                                  \$numrows);
 3464:         $$rowtotal ++;     
 3465:     }
 3466:     return $datatable;
 3467: }
 3468: 
 3469: sub print_autocreate {
 3470:     my ($dom,$settings,$rowtotal) = @_;
 3471:     my (%createon,%createoff,%currhash);
 3472:     my @types = ('xml','req');
 3473:     if (ref($settings) eq 'HASH') {
 3474:         foreach my $item (@types) {
 3475:             $createoff{$item} = ' checked="checked" ';
 3476:             $createon{$item} = ' ';
 3477:             if (exists($settings->{$item})) {
 3478:                 if ($settings->{$item}) {
 3479:                     $createon{$item} = ' checked="checked" ';
 3480:                     $createoff{$item} = ' ';
 3481:                 }
 3482:             }
 3483:         }
 3484:         if ($settings->{'xmldc'} ne '') {
 3485:             $currhash{$settings->{'xmldc'}} = 1;
 3486:         }
 3487:     } else {
 3488:         foreach my $item (@types) {
 3489:             $createoff{$item} = ' checked="checked" ';
 3490:             $createon{$item} = ' ';
 3491:         }
 3492:     }
 3493:     $$rowtotal += 2;
 3494:     my $numinrow = 2;
 3495:     my $datatable='<tr class="LC_odd_row">'.
 3496:                   '<td>'.&mt('Create pending official courses from XML files').'</td>'.
 3497:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3498:                   '<input type="radio" name="autocreate_xml"'.
 3499:                   $createon{'xml'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3500:                   '<label><input type="radio" name="autocreate_xml"'.
 3501:                   $createoff{'xml'}.' value="0" />'.&mt('No').'</label></span>'.
 3502:                   '</td></tr><tr>'.
 3503:                   '<td>'.&mt('Create pending requests for official courses (if validated)').'</td>'.
 3504:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3505:                   '<input type="radio" name="autocreate_req"'.
 3506:                   $createon{'req'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3507:                   '<label><input type="radio" name="autocreate_req"'.
 3508:                   $createoff{'req'}.' value="0" />'.&mt('No').'</label></span>';
 3509:     my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 3510:                                                    'autocreate_xmldc',%currhash);
 3511:     $datatable .= '</td></tr><tr class="LC_odd_row"><td>';
 3512:     if ($numdc > 1) {
 3513:         $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)').
 3514:                       '</td><td class="LC_left_item">';
 3515:     } else {
 3516:         $datatable .= &mt('Course creation processed as:').
 3517:                       '</td><td class="LC_right_item">';
 3518:     }
 3519:     $datatable .= $dctable.'</td></tr>';
 3520:     $$rowtotal += $rows;
 3521:     return $datatable;
 3522: }
 3523: 
 3524: sub print_directorysrch {
 3525:     my ($position,$dom,$settings,$rowtotal) = @_;
 3526:     my $datatable;
 3527:     if ($position eq 'top') {
 3528:         my $instsrchon = ' ';
 3529:         my $instsrchoff = ' checked="checked" ';
 3530:         my ($exacton,$containson,$beginson);
 3531:         my $instlocalon = ' ';
 3532:         my $instlocaloff = ' checked="checked" ';
 3533:         if (ref($settings) eq 'HASH') {
 3534:             if ($settings->{'available'} eq '1') {
 3535:                 $instsrchon = $instsrchoff;
 3536:                 $instsrchoff = ' ';
 3537:             }
 3538:             if ($settings->{'localonly'} eq '1') {
 3539:                 $instlocalon = $instlocaloff;
 3540:                 $instlocaloff = ' ';
 3541:             }
 3542:             if (ref($settings->{'searchtypes'}) eq 'ARRAY') {
 3543:                 foreach my $type (@{$settings->{'searchtypes'}}) {
 3544:                     if ($type eq 'exact') {
 3545:                         $exacton = ' checked="checked" ';
 3546:                     } elsif ($type eq 'contains') {
 3547:                         $containson = ' checked="checked" ';
 3548:                     } elsif ($type eq 'begins') {
 3549:                         $beginson = ' checked="checked" ';
 3550:                     }
 3551:                 }
 3552:             } else {
 3553:                 if ($settings->{'searchtypes'} eq 'exact') {
 3554:                     $exacton = ' checked="checked" ';
 3555:                 } elsif ($settings->{'searchtypes'} eq 'contains') {
 3556:                     $containson = ' checked="checked" ';
 3557:                 } elsif ($settings->{'searchtypes'} eq 'specify') {
 3558:                     $exacton = ' checked="checked" ';
 3559:                     $containson = ' checked="checked" ';
 3560:                 }
 3561:             }
 3562:         }
 3563:         my ($searchtitles,$titleorder) = &sorted_searchtitles();
 3564:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3565: 
 3566:         my $numinrow = 4;
 3567:         my $cansrchrow = 0;
 3568:         $datatable='<tr class="LC_odd_row">'.
 3569:                    '<td colspan="2"><span class ="LC_nobreak">'.&mt('Institutional directory search available?').'</span></td>'.
 3570:                    '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3571:                    '<input type="radio" name="dirsrch_available"'.
 3572:                    $instsrchon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3573:                    '<label><input type="radio" name="dirsrch_available"'.
 3574:                    $instsrchoff.' value="0" />'.&mt('No').'</label></span></td>'.
 3575:                    '</tr><tr>'.
 3576:                    '<td colspan="2"><span class ="LC_nobreak">'.&mt('Other domains can search institution?').'</span></td>'.
 3577:                    '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3578:                    '<input type="radio" name="dirsrch_instlocalonly"'.
 3579:                    $instlocaloff.' value="0" />'.&mt('Yes').'</label>&nbsp;'.
 3580:                    '<label><input type="radio" name="dirsrch_instlocalonly"'.
 3581:                    $instlocalon.' value="1" />'.&mt('No').'</label></span></td>'.
 3582:                    '</tr>';
 3583:         $$rowtotal += 2;
 3584:         if (ref($usertypes) eq 'HASH') {
 3585:             if (keys(%{$usertypes}) > 0) {
 3586:                 $datatable .= &insttypes_row($settings,$types,$usertypes,$dom,
 3587:                                              $numinrow,$othertitle,'cansearch',
 3588:                                              $rowtotal);
 3589:                 $cansrchrow = 1;
 3590:             }
 3591:         }
 3592:         if ($cansrchrow) {
 3593:             $$rowtotal ++;
 3594:             $datatable .= '<tr>';
 3595:         } else {
 3596:             $datatable .= '<tr class="LC_odd_row">';
 3597:         }
 3598:         $datatable .= '<td><span class ="LC_nobreak">'.&mt('Supported search methods').
 3599:                       '</span></td><td class="LC_left_item" colspan="2"><table><tr>';
 3600:         foreach my $title (@{$titleorder}) {
 3601:             if (defined($searchtitles->{$title})) {
 3602:                 my $check = ' ';
 3603:                 if (ref($settings) eq 'HASH') {
 3604:                     if (ref($settings->{'searchby'}) eq 'ARRAY') {
 3605:                         if (grep(/^\Q$title\E$/,@{$settings->{'searchby'}})) {
 3606:                             $check = ' checked="checked" ';
 3607:                         }
 3608:                     }
 3609:                 }
 3610:                 $datatable .= '<td class="LC_left_item">'.
 3611:                               '<span class="LC_nobreak"><label>'.
 3612:                               '<input type="checkbox" name="searchby" '.
 3613:                               'value="'.$title.'"'.$check.'/>'.
 3614:                               $searchtitles->{$title}.'</label></span></td>';
 3615:             }
 3616:         }
 3617:         $datatable .= '</tr></table></td></tr>';
 3618:         $$rowtotal ++;
 3619:         if ($cansrchrow) {
 3620:             $datatable .= '<tr class="LC_odd_row">';
 3621:         } else {
 3622:             $datatable .= '<tr>';
 3623:         }
 3624:         $datatable .= '<td><span class ="LC_nobreak">'.&mt('Search latitude').'</span></td>'.   
 3625:                       '<td class="LC_left_item" colspan="2">'.
 3626:                       '<span class="LC_nobreak"><label>'.
 3627:                       '<input type="checkbox" name="searchtypes" '.
 3628:                       $exacton.' value="exact" />'.&mt('Exact match').
 3629:                       '</label>&nbsp;'.
 3630:                       '<label><input type="checkbox" name="searchtypes" '.
 3631:                       $beginson.' value="begins" />'.&mt('Begins with').
 3632:                       '</label>&nbsp;'.
 3633:                       '<label><input type="checkbox" name="searchtypes" '.
 3634:                       $containson.' value="contains" />'.&mt('Contains').
 3635:                       '</label></span></td></tr>';
 3636:         $$rowtotal ++;
 3637:     } else {
 3638:         my $domsrchon = ' checked="checked" ';
 3639:         my $domsrchoff = ' ';
 3640:         my $domlocalon = ' ';
 3641:         my $domlocaloff = ' checked="checked" ';
 3642:         if (ref($settings) eq 'HASH') {
 3643:             if ($settings->{'lclocalonly'} eq '1') {
 3644:                 $domlocalon = $domlocaloff;
 3645:                 $domlocaloff = ' ';
 3646:             }
 3647:             if ($settings->{'lcavailable'} eq '0') {
 3648:                 $domsrchoff = $domsrchon;
 3649:                 $domsrchon = ' ';
 3650:             }
 3651:         }
 3652:         $datatable='<tr class="LC_odd_row">'.
 3653:                       '<td colspan="2"><span class ="LC_nobreak">'.&mt('LON-CAPA directory search available?').'</span></td>'.
 3654:                       '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3655:                       '<input type="radio" name="dirsrch_domavailable"'.
 3656:                       $domsrchon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3657:                       '<label><input type="radio" name="dirsrch_domavailable"'.
 3658:                       $domsrchoff.' value="0" />'.&mt('No').'</label></span></td>'.
 3659:                       '</tr><tr>'.
 3660:                       '<td colspan="2"><span class ="LC_nobreak">'.&mt('Other domains can search LON-CAPA domain?').'</span></td>'.
 3661:                       '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3662:                       '<input type="radio" name="dirsrch_domlocalonly"'.
 3663:                       $domlocaloff.' value="0" />'.&mt('Yes').'</label>&nbsp;'.
 3664:                       '<label><input type="radio" name="dirsrch_domlocalonly"'.
 3665:                       $domlocalon.' value="1" />'.&mt('No').'</label></span></td>'.
 3666:                       '</tr>';
 3667:         $$rowtotal += 2;
 3668:     }
 3669:     return $datatable;
 3670: }
 3671: 
 3672: sub print_contacts {
 3673:     my ($position,$dom,$settings,$rowtotal) = @_;
 3674:     my $datatable;
 3675:     my @contacts = ('adminemail','supportemail');
 3676:     my (%checked,%to,%otheremails,%bccemails,%includestr,%includeloc,%currfield,
 3677:         $maxsize,$fields,$fieldtitles,$fieldoptions,$possoptions,@mailings,%lonstatus);
 3678:     if ($position eq 'top') {
 3679:         if (ref($settings) eq 'HASH') {
 3680:             foreach my $item (@contacts) {
 3681:                 if (exists($settings->{$item})) {
 3682:                     $to{$item} = $settings->{$item};
 3683:                 }
 3684:             }
 3685:         }
 3686:     } elsif ($position eq 'middle') {
 3687:         @mailings = ('errormail','packagesmail','lonstatusmail','requestsmail',
 3688:                      'updatesmail','idconflictsmail','hostipmail');
 3689:         foreach my $type (@mailings) {
 3690:             $otheremails{$type} = '';
 3691:         }
 3692:     } elsif ($position eq 'lower') {
 3693:         if (ref($settings) eq 'HASH') {
 3694:             if (ref($settings->{'lonstatus'}) eq 'HASH') {
 3695:                 %lonstatus = %{$settings->{'lonstatus'}};
 3696:             }
 3697:         }
 3698:     } else {
 3699:         @mailings = ('helpdeskmail','otherdomsmail');
 3700:         foreach my $type (@mailings) {
 3701:             $otheremails{$type} = '';
 3702:         }
 3703:         $bccemails{'helpdeskmail'} = '';
 3704:         $bccemails{'otherdomsmail'} = '';
 3705:         $includestr{'helpdeskmail'} = '';
 3706:         $includestr{'otherdomsmail'} = '';
 3707:         ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
 3708:     }
 3709:     if (ref($settings) eq 'HASH') {
 3710:         unless (($position eq 'top') || ($position eq 'lower')) {
 3711:             foreach my $type (@mailings) {
 3712:                 if (exists($settings->{$type})) {
 3713:                     if (ref($settings->{$type}) eq 'HASH') {
 3714:                         foreach my $item (@contacts) {
 3715:                             if ($settings->{$type}{$item}) {
 3716:                                 $checked{$type}{$item} = ' checked="checked" ';
 3717:                             }
 3718:                         }
 3719:                         $otheremails{$type} = $settings->{$type}{'others'};
 3720:                         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 3721:                             $bccemails{$type} = $settings->{$type}{'bcc'};
 3722:                             if ($settings->{$type}{'include'} ne '') {
 3723:                                 ($includeloc{$type},$includestr{$type}) = split(/:/,$settings->{$type}{'include'},2);
 3724:                                 $includestr{$type} = &unescape($includestr{$type});
 3725:                             }
 3726:                         }
 3727:                     }
 3728:                 } elsif ($type eq 'lonstatusmail') {
 3729:                     $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" ';
 3730:                 }
 3731:             }
 3732:         }
 3733:         if ($position eq 'bottom') {
 3734:             foreach my $type (@mailings) {
 3735:                 $bccemails{$type} = $settings->{$type}{'bcc'};
 3736:                 if ($settings->{$type}{'include'} ne '') {
 3737:                     ($includeloc{$type},$includestr{$type}) = split(/:/,$settings->{$type}{'include'},2);
 3738:                     $includestr{$type} = &unescape($includestr{$type});
 3739:                 }
 3740:             }
 3741:             if (ref($settings->{'helpform'}) eq 'HASH') {
 3742:                 if (ref($fields) eq 'ARRAY') {
 3743:                     foreach my $field (@{$fields}) {
 3744:                         $currfield{$field} = $settings->{'helpform'}{$field};
 3745:                     }
 3746:                 }
 3747:                 if (exists($settings->{'helpform'}{'maxsize'})) {
 3748:                     $maxsize = $settings->{'helpform'}{'maxsize'};
 3749:                 } else {
 3750:                     $maxsize = '1.0';
 3751:                 }
 3752:             } else {
 3753:                 if (ref($fields) eq 'ARRAY') {
 3754:                     foreach my $field (@{$fields}) {
 3755:                         $currfield{$field} = 'yes';
 3756:                     }
 3757:                 }
 3758:                 $maxsize = '1.0';
 3759:             }
 3760:         }
 3761:     } else {
 3762:         if ($position eq 'top') {
 3763:             $to{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
 3764:             $to{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
 3765:             $checked{'errormail'}{'adminemail'} = ' checked="checked" ';
 3766:             $checked{'packagesmail'}{'adminemail'} = ' checked="checked" ';
 3767:             $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" ';
 3768:             $checked{'requestsmail'}{'adminemail'} = ' checked="checked" ';
 3769:             $checked{'updatesmail'}{'adminemail'} = ' checked="checked" ';
 3770:             $checked{'idconflictsmail'}{'adminemail'} = ' checked="checked" ';
 3771:             $checked{'hostipmail'}{'adminemail'} = ' checked="checked" ';
 3772:         } elsif ($position eq 'bottom') {
 3773:             $checked{'helpdeskmail'}{'supportemail'} = ' checked="checked" ';
 3774:             $checked{'otherdomsmail'}{'supportemail'} = ' checked="checked" ';
 3775:             if (ref($fields) eq 'ARRAY') {
 3776:                 foreach my $field (@{$fields}) {
 3777:                     $currfield{$field} = 'yes';
 3778:                 }
 3779:             }
 3780:             $maxsize = '1.0';
 3781:         }
 3782:     }
 3783:     my ($titles,$short_titles) = &contact_titles();
 3784:     my $rownum = 0;
 3785:     my $css_class;
 3786:     if ($position eq 'top') {
 3787:         foreach my $item (@contacts) {
 3788:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 3789:             $datatable .= '<tr'.$css_class.'>'. 
 3790:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
 3791:                           '</span></td><td class="LC_right_item">'.
 3792:                           '<input type="text" name="'.$item.'" value="'.
 3793:                           $to{$item}.'" /></td></tr>';
 3794:             $rownum ++;
 3795:         }
 3796:     } elsif ($position eq 'bottom') {
 3797:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 3798:         $datatable .= '<tr'.$css_class.'>'.
 3799:                       '<td>'.&mt('Extra helpdesk form fields:').'<br />'.
 3800:                       &mt('(e-mail, subject, and description always shown)').
 3801:                       '</td><td class="LC_left_item">';
 3802:         if ((ref($fields) eq 'ARRAY') && (ref($fieldtitles) eq 'HASH') &&
 3803:             (ref($fieldoptions) eq 'HASH') && (ref($possoptions) eq 'HASH')) {
 3804:             $datatable .= '<table><tr><th>'.&mt('Field').'</th><th>'.&mt('Status').'</th></tr>';
 3805:             foreach my $field (@{$fields}) {
 3806:                 $datatable .= '<tr><td>'.$fieldtitles->{$field};
 3807:                 if (($field eq 'screenshot') || ($field eq 'cc')) {
 3808:                     $datatable .= ' '.&mt('(logged-in users)');
 3809:                 }
 3810:                 $datatable .='</td><td>';
 3811:                 my $clickaction;
 3812:                 if ($field eq 'screenshot') {
 3813:                     $clickaction = ' onclick="screenshotSize(this);"';
 3814:                 }
 3815:                 if (ref($possoptions->{$field}) eq 'ARRAY') {
 3816:                     foreach my $option (@{$possoptions->{$field}}) {
 3817:                         my $checked;
 3818:                         if ($currfield{$field} eq $option) {
 3819:                             $checked = ' checked="checked"';
 3820:                         }
 3821:                         $datatable .= '<span class="LC_nobreak"><label>'.
 3822:                                       '<input type="radio" name="helpform_'.$field.'" '.
 3823:                                       'value="'.$option.'"'.$checked.$clickaction.' />'.$fieldoptions->{$option}.
 3824:                                       '</label></span>'.('&nbsp;'x2);
 3825:                     }
 3826:                 }
 3827:                 if ($field eq 'screenshot') {
 3828:                     my $display;
 3829:                     if ($currfield{$field} eq 'no') {
 3830:                         $display = ' style="display:none"';
 3831:                     }
 3832:                     $datatable .= '</td></tr><tr id="help_screenshotsize"'.$display.'>'.
 3833:                                   '<td>'.&mt('Maximum size for upload (MB)').'</td><td>'.
 3834:                                   '<input type="text" size="5" name="helpform_maxsize" value="'.$maxsize.'" />';
 3835:                 }
 3836:                 $datatable .= '</td></tr>';
 3837:             }
 3838:             $datatable .= '</table>';
 3839:         }
 3840:         $datatable .= '</td></tr>'."\n";
 3841:         $rownum ++;
 3842:     }
 3843:     unless (($position eq 'top') || ($position eq 'lower')) {
 3844:         foreach my $type (@mailings) {
 3845:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 3846:             $datatable .= '<tr'.$css_class.'>'.
 3847:                           '<td><span class="LC_nobreak">'.
 3848:                           $titles->{$type}.': </span></td>'.
 3849:                           '<td class="LC_left_item">';
 3850:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 3851:                 $datatable .= '<fieldset><legend>'.&mt('E-mail recipient(s)').'</legend>';
 3852:             }
 3853:             $datatable .= '<span class="LC_nobreak">';
 3854:             foreach my $item (@contacts) {
 3855:                 $datatable .= '<label>'.
 3856:                               '<input type="checkbox" name="'.$type.'"'.
 3857:                               $checked{$type}{$item}.
 3858:                               ' value="'.$item.'" />'.$short_titles->{$item}.
 3859:                               '</label>&nbsp;';
 3860:             }
 3861:             $datatable .= '</span><br />'.&mt('Others').':&nbsp;&nbsp;'.
 3862:                           '<input type="text" name="'.$type.'_others" '.
 3863:                           'value="'.$otheremails{$type}.'"  />';
 3864:             my %locchecked;
 3865:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 3866:                 foreach my $loc ('s','b') {
 3867:                     if ($includeloc{$type} eq $loc) {
 3868:                         $locchecked{$loc} = ' checked="checked"';
 3869:                         last;
 3870:                     }
 3871:                 }
 3872:                 $datatable .= '<br />'.&mt('Bcc:').('&nbsp;'x6).
 3873:                               '<input type="text" name="'.$type.'_bcc" '.
 3874:                               'value="'.$bccemails{$type}.'"  /></fieldset>'.
 3875:                               '<fieldset><legend>'.&mt('Optional added text').'</legend>'.
 3876:                               &mt('Text automatically added to e-mail:').' '.
 3877:                               '<input type="text" name="'.$type.'_includestr" value="'.$includestr{$type}.'" /><br />'.
 3878:                               '<span class="LC_nobreak">'.&mt('Location:').'&nbsp;'.
 3879:                               '<label><input type="radio" name="'.$type.'_includeloc" value="s"'.$locchecked{'s'}.' />'.&mt('in subject').'</label>'.
 3880:                               ('&nbsp;'x2).
 3881:                               '<label><input type="radio" name="'.$type.'_includeloc" value="b"'.$locchecked{'b'}.' />'.&mt('in body').'</label>'.
 3882:                               '</span></fieldset>';
 3883:             }
 3884:             $datatable .= '</td></tr>'."\n";
 3885:             $rownum ++;
 3886:         }
 3887:     }
 3888:     if ($position eq 'middle') {
 3889:         my %choices;
 3890:         my $corelink = &core_link_msu();
 3891:         $choices{'reporterrors'} = &mt('E-mail error reports to [_1]',$corelink);
 3892:         $choices{'reportupdates'} = &mt('E-mail record of completed LON-CAPA updates to [_1]',
 3893:                                         $corelink);
 3894:         $choices{'reportstatus'} = &mt('E-mail status if errors above threshold to [_1]',$corelink);
 3895:         my @toggles = ('reporterrors','reportupdates','reportstatus');
 3896:         my %defaultchecked = ('reporterrors'  => 'on',
 3897:                               'reportupdates' => 'on',
 3898:                               'reportstatus'  => 'on');
 3899:         (my $reports,$rownum) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 3900:                                                    \%choices,$rownum);
 3901:         $datatable .= $reports;
 3902:     } elsif ($position eq 'lower') {
 3903:         my (%current,%excluded,%weights);
 3904:         my ($defaults,$names) = &Apache::loncommon::lon_status_items();
 3905:         if ($lonstatus{'threshold'} =~ /^\d+$/) {
 3906:             $current{'errorthreshold'} = $lonstatus{'threshold'};
 3907:         } else {
 3908:             $current{'errorthreshold'} = $defaults->{'threshold'};
 3909:         }
 3910:         if ($lonstatus{'sysmail'} =~ /^\d+$/) {
 3911:             $current{'errorsysmail'} = $lonstatus{'sysmail'};
 3912:         } else {
 3913:             $current{'errorsysmail'} = $defaults->{'sysmail'};
 3914:         }
 3915:         if (ref($lonstatus{'weights'}) eq 'HASH') {
 3916:             foreach my $type ('E','W','N','U') {
 3917:                 if ($lonstatus{'weights'}{$type} =~ /^\d+$/) {
 3918:                     $weights{$type} = $lonstatus{'weights'}{$type};
 3919:                 } else {
 3920:                     $weights{$type} = $defaults->{$type};
 3921:                 }
 3922:             }
 3923:         } else {
 3924:             foreach my $type ('E','W','N','U') {
 3925:                 $weights{$type} = $defaults->{$type};
 3926:             }
 3927:         }
 3928:         if (ref($lonstatus{'excluded'}) eq 'ARRAY') {
 3929:             if (@{$lonstatus{'excluded'}} > 0) {
 3930:                 map {$excluded{$_} = 1; } @{$lonstatus{'excluded'}};
 3931:             }
 3932:         }
 3933:         foreach my $item ('errorthreshold','errorsysmail') {
 3934:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 3935:             $datatable .= '<tr'.$css_class.'>'.
 3936:                           '<td class="LC_left_item"><span class="LC_nobreak">'.
 3937:                           $titles->{$item}.
 3938:                           '</span></td><td class="LC_left_item">'.
 3939:                           '<input type="text" name="'.$item.'" value="'.
 3940:                           $current{$item}.'" size="5" /></td></tr>';
 3941:             $rownum ++;
 3942:         }
 3943:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 3944:         $datatable .= '<tr'.$css_class.'>'.
 3945:                       '<td class="LC_left_item">'.
 3946:                       '<span class="LC_nobreak">'.$titles->{'errorweights'}.
 3947:                       '</span></td><td class="LC_left_item"><table><tr>';
 3948:         foreach my $type ('E','W','N','U') {
 3949:             $datatable .= '<td>'.$names->{$type}.'<br />'.
 3950:                           '<input type="text" name="errorweights_'.$type.'" value="'.
 3951:                           $weights{$type}.'" size="5" /></td>';
 3952:         }
 3953:         $datatable .= '</tr></table></tr>';
 3954:         $rownum ++;
 3955:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 3956:         $datatable .= '<tr'.$css_class.'><td class="LC_left_item">'.
 3957:                       $titles->{'errorexcluded'}.'</td>'.
 3958:                       '<td class="LC_left_item"><table>';
 3959:         my $numinrow = 4;
 3960:         my @ids = sort(values(%Apache::lonnet::serverhomeIDs));
 3961:         for (my $i=0; $i<@ids; $i++) {
 3962:             my $rem = $i%($numinrow);
 3963:             if ($rem == 0) {
 3964:                 if ($i > 0) {
 3965:                     $datatable .= '</tr>';
 3966:                 }
 3967:                 $datatable .= '<tr>';
 3968:             }
 3969:             my $check;
 3970:             if ($excluded{$ids[$i]}) {
 3971:                 $check = ' checked="checked" ';
 3972:             }
 3973:             $datatable .= '<td class="LC_left_item">'.
 3974:                           '<span class="LC_nobreak"><label>'.
 3975:                           '<input type="checkbox" name="errorexcluded" '.
 3976:                           'value="'.$ids[$i].'"'.$check.' />'.
 3977:                           $ids[$i].'</label></span></td>';
 3978:         }
 3979:         my $colsleft = $numinrow - @ids%($numinrow);
 3980:         if ($colsleft > 1 ) {
 3981:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 3982:                           '&nbsp;</td>';
 3983:         } elsif ($colsleft == 1) {
 3984:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 3985:         }
 3986:         $datatable .= '</tr></table></td></tr>';
 3987:         $rownum ++;
 3988:     } elsif ($position eq 'bottom') {
 3989:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3990:         my (@posstypes,%usertypeshash);
 3991:         if (ref($types) eq 'ARRAY') {
 3992:             @posstypes = @{$types};
 3993:         }
 3994:         if (@posstypes) {
 3995:             if (ref($usertypes) eq 'HASH') {
 3996:                 %usertypeshash = %{$usertypes};
 3997:             }
 3998:             my @overridden;
 3999:             my $numinrow = 4;
 4000:             if (ref($settings) eq 'HASH') {
 4001:                 if (ref($settings->{'overrides'}) eq 'HASH') {
 4002:                     foreach my $key (sort(keys(%{$settings->{'overrides'}}))) {
 4003:                         if (ref($settings->{'overrides'}{$key}) eq 'HASH') {
 4004:                             push(@overridden,$key);
 4005:                             foreach my $item (@contacts) {
 4006:                                 if ($settings->{'overrides'}{$key}{$item}) {
 4007:                                     $checked{'override_'.$key}{$item} = ' checked="checked" ';
 4008:                                 }
 4009:                             }
 4010:                             $otheremails{'override_'.$key} = $settings->{'overrides'}{$key}{'others'};
 4011:                             $bccemails{'override_'.$key} = $settings->{'overrides'}{$key}{'bcc'};
 4012:                             $includeloc{'override_'.$key} = '';
 4013:                             $includestr{'override_'.$key} = '';
 4014:                             if ($settings->{'overrides'}{$key}{'include'} ne '') {
 4015:                                 ($includeloc{'override_'.$key},$includestr{'override_'.$key}) =
 4016:                                     split(/:/,$settings->{'overrides'}{$key}{'include'},2);
 4017:                                 $includestr{'override_'.$key} = &unescape($includestr{'override_'.$key});
 4018:                             }
 4019:                         }
 4020:                     }
 4021:                 }
 4022:             }
 4023:             my $customclass = 'LC_helpdesk_override';
 4024:             my $optionsprefix = 'LC_options_helpdesk_';
 4025: 
 4026:             my $onclicktypes = "toggleHelpdeskRow(this.form,'overrides','$customclass','$optionsprefix');";
 4027: 
 4028:             $datatable .= &insttypes_row($settings,$types,$usertypes,$dom,
 4029:                                          $numinrow,$othertitle,'overrides',
 4030:                                          \$rownum,$onclicktypes,$customclass);
 4031:             $rownum ++;
 4032:             $usertypeshash{'default'} = $othertitle;
 4033:             foreach my $status (@posstypes) {
 4034:                 my $css_class;
 4035:                 if ($rownum%2) {
 4036:                     $css_class = 'LC_odd_row ';
 4037:                 }
 4038:                 $css_class .= $customclass;
 4039:                 my $rowid = $optionsprefix.$status;
 4040:                 my $hidden = 1;
 4041:                 my $currstyle = 'display:none';
 4042:                 if (grep(/^\Q$status\E$/,@overridden)) {
 4043:                     $currstyle = 'display:table-row';
 4044:                     $hidden = 0;
 4045:                 }
 4046:                 my $key = 'override_'.$status;
 4047:                 $datatable .= &overridden_helpdesk($checked{$key},$otheremails{$key},$bccemails{$key},
 4048:                                                   $includeloc{$key},$includestr{$key},$status,$rowid,
 4049:                                                   $usertypeshash{$status},$css_class,$currstyle,
 4050:                                                   \@contacts,$short_titles);
 4051:                 unless ($hidden) {
 4052:                     $rownum ++;
 4053:                 }
 4054:             }
 4055:         }
 4056:     }
 4057:     $$rowtotal += $rownum;
 4058:     return $datatable;
 4059: }
 4060: 
 4061: sub core_link_msu {
 4062:     return &Apache::loncommon::modal_link('http://loncapa.org/core.html',
 4063:                                           &mt('LON-CAPA core group - MSU'),600,500);
 4064: }
 4065: 
 4066: sub overridden_helpdesk {
 4067:     my ($checked,$otheremails,$bccemails,$includeloc,$includestr,$type,$rowid,
 4068:         $typetitle,$css_class,$rowstyle,$contacts,$short_titles) = @_;
 4069:     my $class = 'LC_left_item';
 4070:     if ($css_class) {
 4071:         $css_class = ' class="'.$css_class.'"';
 4072:     }
 4073:     if ($rowid) {
 4074:         $rowid = ' id="'.$rowid.'"';
 4075:     }
 4076:     if ($rowstyle) {
 4077:         $rowstyle = ' style="'.$rowstyle.'"';
 4078:     }
 4079:     my ($output,$description);
 4080:     $description = &mt('Helpdesk requests from: [_1] in this domain (overrides default)',"<b>$typetitle</b>");
 4081:     $output = '<tr'.$css_class.$rowid.$rowstyle.'>'.
 4082:               "<td>$description</td>\n".
 4083:               '<td class="'.$class.'" colspan="2">'.
 4084:               '<fieldset><legend>'.&mt('E-mail recipient(s)').'</legend>'.
 4085:               '<span class="LC_nobreak">';
 4086:     if (ref($contacts) eq 'ARRAY') {
 4087:         foreach my $item (@{$contacts}) {
 4088:             my $check;
 4089:             if (ref($checked) eq 'HASH') {
 4090:                $check = $checked->{$item};
 4091:             }
 4092:             my $title;
 4093:             if (ref($short_titles) eq 'HASH') {
 4094:                 $title = $short_titles->{$item};
 4095:             }
 4096:             $output .= '<label>'.
 4097:                        '<input type="checkbox" name="override_'.$type.'"'.$check.
 4098:                        ' value="'.$item.'" />'.$title.'</label>&nbsp;';
 4099:         }
 4100:     }
 4101:     $output .= '</span><br />'.&mt('Others').':&nbsp;&nbsp;'.
 4102:                '<input type="text" name="override_'.$type.'_others" '.
 4103:                'value="'.$otheremails.'"  />';
 4104:     my %locchecked;
 4105:     foreach my $loc ('s','b') {
 4106:         if ($includeloc eq $loc) {
 4107:             $locchecked{$loc} = ' checked="checked"';
 4108:             last;
 4109:         }
 4110:     }
 4111:     $output .= '<br />'.&mt('Bcc:').('&nbsp;'x6).
 4112:                '<input type="text" name="override_'.$type.'_bcc" '.
 4113:                'value="'.$bccemails.'"  /></fieldset>'.
 4114:                '<fieldset><legend>'.&mt('Optional added text').'</legend>'.
 4115:                &mt('Text automatically added to e-mail:').' '.
 4116:                '<input type="text" name="override_'.$type.'_includestr" value="'.$includestr.'" /><br />'.
 4117:                '<span class="LC_nobreak">'.&mt('Location:').'&nbsp;'.
 4118:                '<label><input type="radio" name="override_'.$type.'_includeloc" value="s"'.$locchecked{'s'}.' />'.&mt('in subject').'</label>'.
 4119:                ('&nbsp;'x2).
 4120:                '<label><input type="radio" name="override_'.$type.'_includeloc" value="b"'.$locchecked{'b'}.' />'.&mt('in body').'</label>'.
 4121:                '</span></fieldset>'.
 4122:                '</td></tr>'."\n";
 4123:     return $output;
 4124: }
 4125: 
 4126: sub contacts_javascript {
 4127:     return <<"ENDSCRIPT";
 4128: 
 4129: <script type="text/javascript">
 4130: // <![CDATA[
 4131: 
 4132: function screenshotSize(field) {
 4133:     if (document.getElementById('help_screenshotsize')) {
 4134:         if (field.value == 'no') {
 4135:             document.getElementById('help_screenshotsize').style.display="none";
 4136:         } else {
 4137:             document.getElementById('help_screenshotsize').style.display="";
 4138:         }
 4139:     }
 4140:     return;
 4141: }
 4142: 
 4143: function toggleHelpdeskRow(form,checkbox,target,prefix,docount) {
 4144:     if (form.elements[checkbox].length != undefined) {
 4145:         var count = 0;
 4146:         if (docount) {
 4147:             for (var i=0; i<form.elements[checkbox].length; i++) {
 4148:                 if (form.elements[checkbox][i].checked) {
 4149:                     count ++;
 4150:                 }
 4151:             }
 4152:         }
 4153:         for (var i=0; i<form.elements[checkbox].length; i++) {
 4154:             var type = form.elements[checkbox][i].value;
 4155:             if (document.getElementById(prefix+type)) {
 4156:                 if (form.elements[checkbox][i].checked) {
 4157:                     document.getElementById(prefix+type).style.display = 'table-row';
 4158:                     if (count % 2 == 1) {
 4159:                         document.getElementById(prefix+type).className = target+' LC_odd_row';
 4160:                     } else {
 4161:                         document.getElementById(prefix+type).className = target;
 4162:                     }
 4163:                     count ++;
 4164:                 } else {
 4165:                     document.getElementById(prefix+type).style.display = 'none';
 4166:                 }
 4167:             }
 4168:         }
 4169:     }
 4170:     return;
 4171: }
 4172: 
 4173: // ]]>
 4174: </script>
 4175: 
 4176: ENDSCRIPT
 4177: }
 4178: 
 4179: sub print_helpsettings {
 4180:     my ($position,$dom,$settings,$rowtotal) = @_;
 4181:     my $confname = $dom.'-domainconfig';
 4182:     my $formname = 'display';
 4183:     my ($datatable,$itemcount);
 4184:     if ($position eq 'top') {
 4185:         $itemcount = 1;
 4186:         my (%choices,%defaultchecked,@toggles);
 4187:         $choices{'submitbugs'} = &mt('Display link to: [_1]?',
 4188:                                      &Apache::loncommon::modal_link('http://bugs.loncapa.org',
 4189:                                      &mt('LON-CAPA bug tracker'),600,500));
 4190:         %defaultchecked = ('submitbugs' => 'on');
 4191:         @toggles = ('submitbugs');
 4192:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 4193:                                                      \%choices,$itemcount);
 4194:         $$rowtotal ++;
 4195:     } else {
 4196:         my $css_class;
 4197:         my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
 4198:         my (%customroles,%ordered,%current);
 4199:         if (ref($settings) eq 'HASH') {
 4200:             if (ref($settings->{'adhoc'}) eq 'HASH') {
 4201:                 %current = %{$settings->{'adhoc'}};
 4202:             }
 4203:         }
 4204:         my $count = 0;
 4205:         foreach my $key (sort(keys(%existing))) {
 4206:             if ($key=~/^rolesdef\_(\w+)$/) {
 4207:                 my $rolename = $1;
 4208:                 my (%privs,$order);
 4209:                 ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 4210:                 $customroles{$rolename} = \%privs;
 4211:                 if (ref($current{$rolename}) eq 'HASH') {
 4212:                     $order = $current{$rolename}{'order'};
 4213:                 }
 4214:                 if ($order eq '') {
 4215:                     $order = $count;
 4216:                 }
 4217:                 $ordered{$order} = $rolename;
 4218:                 $count++;
 4219:             }
 4220:         }
 4221:         my $maxnum = scalar(keys(%ordered));
 4222:         my @roles_by_num = ();
 4223:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 4224:             push(@roles_by_num,$item);
 4225:         }
 4226:         my $context = 'domprefs';
 4227:         my $crstype = 'Course';
 4228:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4229:         my @accesstypes = ('all','dh','da','none');
 4230:         my ($numstatustypes,@jsarray);
 4231:         if (ref($types) eq 'ARRAY') {
 4232:             if (@{$types} > 0) {
 4233:                 $numstatustypes = scalar(@{$types});
 4234:                 push(@accesstypes,'status');
 4235:                 @jsarray = ('bystatus');
 4236:             }
 4237:         }
 4238:         my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh','da']);
 4239:         if (keys(%domhelpdesk)) {
 4240:             push(@accesstypes,('inc','exc'));
 4241:             push(@jsarray,('notinc','notexc'));
 4242:         }
 4243:         my $hiddenstr = join("','",@jsarray);
 4244:         $datatable .= &helpsettings_javascript(\@roles_by_num,$maxnum,$hiddenstr,$formname);
 4245:         my $context = 'domprefs';
 4246:         my $crstype = 'Course';
 4247:         my $prefix = 'helproles_';
 4248:         my $add_class = 'LC_hidden';
 4249:         foreach my $num (@roles_by_num) {
 4250:             my $role = $ordered{$num};
 4251:             my ($desc,$access,@statuses);
 4252:             if (ref($current{$role}) eq 'HASH') {
 4253:                 $desc = $current{$role}{'desc'};
 4254:                 $access = $current{$role}{'access'};
 4255:                 if (ref($current{$role}{'insttypes'}) eq 'ARRAY') {
 4256:                     @statuses = @{$current{$role}{'insttypes'}};
 4257:                 }
 4258:             }
 4259:             if ($desc eq '') {
 4260:                 $desc = $role;
 4261:             }
 4262:             my $identifier = 'custhelp'.$num;
 4263:             my %full=();
 4264:             my %levels= (
 4265:                          course => {},
 4266:                          domain => {},
 4267:                          system => {},
 4268:                         );
 4269:             my %levelscurrent=(
 4270:                                course => {},
 4271:                                domain => {},
 4272:                                system => {},
 4273:                               );
 4274:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 4275:             my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4276:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4277:             my $chgstr = ' onchange="javascript:reorderHelpRoles(this.form,'."'helproles_".$num."_pos'".');"';
 4278:             $datatable .= '<tr '.$css_class.'><td valign="top"><b>'.$role.'</b><br />'.
 4279:                           '<select name="helproles_'.$num.'_pos"'.$chgstr.'>';
 4280:             for (my $k=0; $k<=$maxnum; $k++) {
 4281:                 my $vpos = $k+1;
 4282:                 my $selstr;
 4283:                 if ($k == $num) {
 4284:                     $selstr = ' selected="selected" ';
 4285:                 }
 4286:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 4287:             }
 4288:             $datatable .= '</select>'.('&nbsp;'x2).
 4289:                           '<input type="hidden" name="helproles_'.$num.'" value="'.$role.'" />'.
 4290:                           '</td>'.
 4291:                           '<td><fieldset><legend>'.&mt('Role name').'</legend>'.
 4292:                           &mt('Name shown to users:').
 4293:                           '<input type="text" name="helproles_'.$num.'_desc" value="'.$desc.'" />'.
 4294:                           '</fieldset>'.
 4295:                           &helpdeskroles_access($dom,$prefix,$num,$add_class,$current{$role},\@accesstypes,
 4296:                                                 $othertitle,$usertypes,$types,\%domhelpdesk).
 4297:                           '<fieldset>'.
 4298:                           '<legend>'.&mt('Role privileges').&adhocbutton($prefix,$num,'privs','show').'</legend>'.
 4299:                           &Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 4300:                                                                    \%levelscurrent,$identifier,
 4301:                                                                    'LC_hidden',$prefix.$num.'_privs').
 4302:                           '</fieldset></td>';
 4303:             $itemcount ++;
 4304:         }
 4305:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4306:         my $newcust = 'custhelp'.$count;
 4307:         my (%privs,%levelscurrent);
 4308:         my %full=();
 4309:         my %levels= (
 4310:                      course => {},
 4311:                      domain => {},
 4312:                      system => {},
 4313:                     );
 4314:         &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 4315:         my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4316:         my $chgstr = ' onchange="javascript:reorderHelpRoles(this.form,'."'helproles_".$count."_pos'".');"';
 4317:         $datatable .= '<tr '.$css_class.'><td valign="top"><span class="LC_nobreak"><label>'.
 4318:                       '<input type="hidden" name="helproles_maxnum" value="'.$maxnum.'" />'."\n".
 4319:                       '<select name="helproles_'.$count.'_pos"'.$chgstr.'>';
 4320:         for (my $k=0; $k<$maxnum+1; $k++) {
 4321:             my $vpos = $k+1;
 4322:             my $selstr;
 4323:             if ($k == $maxnum) {
 4324:                 $selstr = ' selected="selected" ';
 4325:             }
 4326:             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 4327:         }
 4328:         $datatable .= '</select>&nbsp;'."\n".
 4329:                       '<input type="checkbox" name="newcusthelp" value="'.$count.'" />'. &mt('Add').
 4330:                       '</label></span></td>'.
 4331:                       '<td><fieldset><legend>'.&mt('Role name').'</legend>'.
 4332:                       '<span class="LC_nobreak">'.
 4333:                       &mt('Internal name:').
 4334:                       '<input type="text" size="10" name="custhelpname'.$count.'" value="" />'.
 4335:                       '</span>'.('&nbsp;'x4).
 4336:                       '<span class="LC_nobreak">'.
 4337:                       &mt('Name shown to users:').
 4338:                       '<input type="text" size="20" name="helproles_'.$count.'_desc" value="" />'.
 4339:                       '</span></fieldset>'.
 4340:                        &helpdeskroles_access($dom,$prefix,$count,'',undef,\@accesstypes,$othertitle,
 4341:                                              $usertypes,$types,\%domhelpdesk).
 4342:                       '<fieldset><legend>'.&mt('Role privileges').'</legend>'.
 4343:                       &Apache::lonuserutils::custom_role_header($context,$crstype,
 4344:                                                                 \@templateroles,$newcust).
 4345:                       &Apache::lonuserutils::custom_role_table('Course',\%full,\%levels,
 4346:                                                                \%levelscurrent,$newcust).
 4347:                       '</fieldset>'.
 4348:                       &helpsettings_javascript(\@roles_by_num,$maxnum,$hiddenstr,$formname).
 4349:                       '</td></tr>';
 4350:         $count ++;
 4351:         $$rowtotal += $count;
 4352:     }
 4353:     return $datatable;
 4354: }
 4355: 
 4356: sub adhocbutton {
 4357:     my ($prefix,$num,$field,$visibility) = @_;
 4358:     my %lt = &Apache::lonlocal::texthash(
 4359:                                           show => 'Show details',
 4360:                                           hide => 'Hide details',
 4361:                                         );
 4362:     return '<span style="text-decoration:line-through; font-weight: normal;">'.('&nbsp;'x10).
 4363:            '</span>'.('&nbsp;'x2).'<input type="button" id="'.$prefix.$num.'_'.$field.'_vis"'.
 4364:            ' value="'.$lt{$visibility}.'" style="height:20px;" '.
 4365:            'onclick="toggleHelpdeskItem('."'$num','$field'".');" />'.('&nbsp;'x2);
 4366: }
 4367: 
 4368: sub helpsettings_javascript {
 4369:     my ($roles_by_num,$total,$hiddenstr,$formname) = @_;
 4370:     return unless(ref($roles_by_num) eq 'ARRAY');
 4371:     my %html_js_lt = &Apache::lonlocal::texthash(
 4372:                                           show => 'Show details',
 4373:                                           hide => 'Hide details',
 4374:                                         );
 4375:     &html_escape(\%html_js_lt);
 4376:     my $jstext = '    var helproles = Array('."'".join("','",@{$roles_by_num})."'".');'."\n";
 4377:     return <<"ENDSCRIPT";
 4378: <script type="text/javascript">
 4379: // <![CDATA[
 4380: 
 4381: function reorderHelpRoles(form,item) {
 4382:     var changedVal;
 4383: $jstext
 4384:     var newpos = 'helproles_${total}_pos';
 4385:     var maxh = 1 + $total;
 4386:     var current = new Array();
 4387:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 4388:     if (item == newpos) {
 4389:         changedVal = newitemVal;
 4390:     } else {
 4391:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 4392:         current[newitemVal] = newpos;
 4393:     }
 4394:     for (var i=0; i<helproles.length; i++) {
 4395:         var elementName = 'helproles_'+helproles[i]+'_pos';
 4396:         if (elementName != item) {
 4397:             if (form.elements[elementName]) {
 4398:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 4399:                 current[currVal] = elementName;
 4400:             }
 4401:         }
 4402:     }
 4403:     var oldVal;
 4404:     for (var j=0; j<maxh; j++) {
 4405:         if (current[j] == undefined) {
 4406:             oldVal = j;
 4407:         }
 4408:     }
 4409:     if (oldVal < changedVal) {
 4410:         for (var k=oldVal+1; k<=changedVal ; k++) {
 4411:            var elementName = current[k];
 4412:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 4413:         }
 4414:     } else {
 4415:         for (var k=changedVal; k<oldVal; k++) {
 4416:             var elementName = current[k];
 4417:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 4418:         }
 4419:     }
 4420:     return;
 4421: }
 4422: 
 4423: function helpdeskAccess(num) {
 4424:     var curraccess = null;
 4425:     if (document.$formname.elements['helproles_'+num+'_access'].length) {
 4426:         for (var i=0; i<document.$formname.elements['helproles_'+num+'_access'].length; i++) {
 4427:             if (document.$formname.elements['helproles_'+num+'_access'][i].checked) {
 4428:                 curraccess = document.$formname.elements['helproles_'+num+'_access'][i].value;
 4429:             }
 4430:         }
 4431:     }
 4432:     var shown = Array();
 4433:     var hidden = Array();
 4434:     if (curraccess == 'none') {
 4435:         hidden = Array('$hiddenstr');
 4436:     } else {
 4437:         if (curraccess == 'status') {
 4438:             shown = Array('bystatus');
 4439:             hidden = Array('notinc','notexc');
 4440:         } else {
 4441:             if (curraccess == 'exc') {
 4442:                 shown = Array('notexc');
 4443:                 hidden = Array('notinc','bystatus');
 4444:             }
 4445:             if (curraccess == 'inc') {
 4446:                 shown = Array('notinc');
 4447:                 hidden = Array('notexc','bystatus');
 4448:             }
 4449:             if ((curraccess == 'all') || (curraccess == 'dh') || (curraccess == 'da')) {
 4450:                 hidden = Array('notinc','notexc','bystatus');
 4451:             }
 4452:         }
 4453:     }
 4454:     if (hidden.length > 0) {
 4455:         for (var i=0; i<hidden.length; i++) {
 4456:             if (document.getElementById('helproles_'+num+'_'+hidden[i])) {
 4457:                 document.getElementById('helproles_'+num+'_'+hidden[i]).style.display = 'none';
 4458:             }
 4459:         }
 4460:     }
 4461:     if (shown.length > 0) {
 4462:         for (var i=0; i<shown.length; i++) {
 4463:             if (document.getElementById('helproles_'+num+'_'+shown[i])) {
 4464:                 if (shown[i] == 'privs') {
 4465:                     document.getElementById('helproles_'+num+'_'+shown[i]).style.display = 'block';
 4466:                 } else {
 4467:                     document.getElementById('helproles_'+num+'_'+shown[i]).style.display = 'inline-block';
 4468:                 }
 4469:             }
 4470:         }
 4471:     }
 4472:     return;
 4473: }
 4474: 
 4475: function toggleHelpdeskItem(num,field) {
 4476:     if (document.getElementById('helproles_'+num+'_'+field)) {
 4477:         if (document.getElementById('helproles_'+num+'_'+field).className.match(/(?:^|\\s)LC_hidden(?!\\S)/)) {
 4478:             document.getElementById('helproles_'+num+'_'+field).className =
 4479:                 document.getElementById('helproles_'+num+'_'+field).className.replace(/(?:^|\\s)LC_hidden(?!\\S)/g ,'');
 4480:             if (document.getElementById('helproles_'+num+'_'+field+'_vis')) {
 4481:                 document.getElementById('helproles_'+num+'_'+field+'_vis').value = '$html_js_lt{hide}';
 4482:             }
 4483:         } else {
 4484:             document.getElementById('helproles_'+num+'_'+field).className += ' LC_hidden';
 4485:             if (document.getElementById('helproles_'+num+'_'+field+'_vis')) {
 4486:                 document.getElementById('helproles_'+num+'_'+field+'_vis').value = '$html_js_lt{show}';
 4487:             }
 4488:         }
 4489:     }
 4490:     return;
 4491: }
 4492: 
 4493: // ]]>
 4494: </script>
 4495: 
 4496: ENDSCRIPT
 4497: }
 4498: 
 4499: sub helpdeskroles_access {
 4500:     my ($dom,$prefix,$num,$add_class,$current,$accesstypes,$othertitle,
 4501:         $usertypes,$types,$domhelpdesk) = @_;
 4502:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($domhelpdesk) eq 'HASH'));
 4503:     my %lt = &Apache::lonlocal::texthash(
 4504:                     'rou'    => 'Role usage',
 4505:                     'whi'    => 'Which helpdesk personnel may use this role?',
 4506:                     'all'    => 'All with domain helpdesk or helpdesk assistant role',
 4507:                     'dh'     => 'All with domain helpdesk role',
 4508:                     'da'     => 'All with domain helpdesk assistant role',
 4509:                     'none'   => 'None',
 4510:                     'status' => 'Determined based on institutional status',
 4511:                     'inc'    => 'Include all, but exclude specific personnel',
 4512:                     'exc'    => 'Exclude all, but include specific personnel',
 4513:                   );
 4514:     my %usecheck = (
 4515:                      all => ' checked="checked"',
 4516:                    );
 4517:     my %displaydiv = (
 4518:                       status => 'none',
 4519:                       inc    => 'none',
 4520:                       exc    => 'none',
 4521:                       priv   => 'block',
 4522:                      );
 4523:     my $output;
 4524:     if (ref($current) eq 'HASH') {
 4525:         if (($current->{'access'} ne '') && ($current->{'access'} ne 'all')) {
 4526:             if (grep(/^\Q$current->{access}\E$/,@{$accesstypes})) {
 4527:                 $usecheck{$current->{access}} = $usecheck{'all'};
 4528:                 delete($usecheck{'all'});
 4529:                 if ($current->{access} =~ /^(status|inc|exc)$/) {
 4530:                     my $access = $1;
 4531:                     $displaydiv{$access} = 'inline';
 4532:                 } elsif ($current->{access} eq 'none') {
 4533:                     $displaydiv{'priv'} = 'none';
 4534:                 }
 4535:             }
 4536:         }
 4537:     }
 4538:     $output = '<fieldset id="'.$prefix.$num.'_usage"><legend>'.$lt{'rou'}.'</legend>'.
 4539:               '<p>'.$lt{'whi'}.'</p>';
 4540:     foreach my $access (@{$accesstypes}) {
 4541:         $output .= '<p><label><input type="radio" name="'.$prefix.$num.'_access" value="'.$access.'" '.$usecheck{$access}.
 4542:                    ' onclick="helpdeskAccess('."'$num'".');" />'.
 4543:                    $lt{$access}.'</label>';
 4544:         if ($access eq 'status') {
 4545:             $output .= '<div id="'.$prefix.$num.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 4546:                        &Apache::lonuserutils::adhoc_status_types($dom,$prefix,$num,$current->{$access},
 4547:                                                                  $othertitle,$usertypes,$types).
 4548:                        '</div>';
 4549:         } elsif (($access eq 'inc') && (keys(%{$domhelpdesk}) > 0)) {
 4550:             $output .= '<div id="'.$prefix.$num.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 4551:                        &Apache::lonuserutils::adhoc_staff($access,$prefix,$num,$current->{$access},$domhelpdesk).
 4552:                        '</div>';
 4553:         } elsif (($access eq 'exc') && (keys(%{$domhelpdesk}) > 0)) {
 4554:             $output .= '<div id="'.$prefix.$num.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 4555:                        &Apache::lonuserutils::adhoc_staff($access,$prefix,$num,$current->{$access},$domhelpdesk).
 4556:                        '</div>';
 4557:         }
 4558:         $output .= '</p>';
 4559:     }
 4560:     $output .= '</fieldset>';
 4561:     return $output;
 4562: }
 4563: 
 4564: sub radiobutton_prefs {
 4565:     my ($settings,$toggles,$defaultchecked,$choices,$itemcount,$onclick,
 4566:         $additional,$align,$firstval) = @_;
 4567:     return unless ((ref($toggles) eq 'ARRAY') && (ref($defaultchecked) eq 'HASH') &&
 4568:                    (ref($choices) eq 'HASH'));
 4569: 
 4570:     my (%checkedon,%checkedoff,$datatable,$css_class);
 4571: 
 4572:     foreach my $item (@{$toggles}) {
 4573:         if ($defaultchecked->{$item} eq 'on') {
 4574:             $checkedon{$item} = ' checked="checked" ';
 4575:             $checkedoff{$item} = ' ';
 4576:         } elsif ($defaultchecked->{$item} eq 'off') {
 4577:             $checkedoff{$item} = ' checked="checked" ';
 4578:             $checkedon{$item} = ' ';
 4579:         }
 4580:     }
 4581:     if (ref($settings) eq 'HASH') {
 4582:         foreach my $item (@{$toggles}) {
 4583:             if ($settings->{$item} eq '1') {
 4584:                 $checkedon{$item} =  ' checked="checked" ';
 4585:                 $checkedoff{$item} = ' ';
 4586:             } elsif ($settings->{$item} eq '0') {
 4587:                 $checkedoff{$item} =  ' checked="checked" ';
 4588:                 $checkedon{$item} = ' ';
 4589:             }
 4590:         }
 4591:     }
 4592:     if ($onclick) {
 4593:         $onclick = ' onclick="'.$onclick.'"';
 4594:     }
 4595:     foreach my $item (@{$toggles}) {
 4596:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4597:         $datatable .=
 4598:             '<tr'.$css_class.'><td valign="top">'.
 4599:             '<span class="LC_nobreak">'.$choices->{$item}.
 4600:             '</span></td>';
 4601:         if ($align eq 'left') {
 4602:             $datatable .= '<td class="LC_left_item">';
 4603:         } else {
 4604:             $datatable .= '<td class="LC_right_item">';
 4605:         }
 4606:         $datatable .= '<span class="LC_nobreak">';
 4607:         if ($firstval eq 'no') {
 4608:             $datatable .=
 4609:                 '<label><input type="radio" name="'.
 4610:                 $item.'" '.$checkedoff{$item}.' value="0"'.$onclick.' />'.&mt('No').
 4611:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'" '.
 4612:                 $checkedon{$item}.' value="1"'.$onclick.' />'.&mt('Yes').'</label>';
 4613:         } else {
 4614:             $datatable .=
 4615:             '<label><input type="radio" name="'.
 4616:             $item.'" '.$checkedon{$item}.' value="1"'.$onclick.' />'.&mt('Yes').
 4617:             '</label>&nbsp;<label><input type="radio" name="'.$item.'" '.
 4618:             $checkedoff{$item}.' value="0"'.$onclick.' />'.&mt('No').'</label>';
 4619:         }
 4620:         $datatable .= '</span>'.$additional.'</td></tr>';
 4621:         $itemcount ++;
 4622:     }
 4623:     return ($datatable,$itemcount);
 4624: }
 4625: 
 4626: sub print_ltitools {
 4627:     my ($dom,$settings,$rowtotal) = @_;
 4628:     my $rownum = 0;
 4629:     my $css_class;
 4630:     my $itemcount = 1;
 4631:     my $maxnum = 0;
 4632:     my %ordered;
 4633:     if (ref($settings) eq 'HASH') {
 4634:         foreach my $item (keys(%{$settings})) {
 4635:             if (ref($settings->{$item}) eq 'HASH') {
 4636:                 my $num = $settings->{$item}{'order'};
 4637:                 $ordered{$num} = $item;
 4638:             }
 4639:         }
 4640:     }
 4641:     my $confname = $dom.'-domainconfig';
 4642:     my $switchserver = &check_switchserver($dom,$confname);
 4643:     my $maxnum = scalar(keys(%ordered));
 4644:     my $datatable;
 4645:     my %lt = &ltitools_names();
 4646:     my @courseroles = ('cc','in','ta','ep','st');
 4647:     my @ltiroles = qw(Instructor ContentDeveloper TeachingAssistant Learner);
 4648:     my @fields = ('fullname','firstname','lastname','email','roles','user');
 4649:     if (keys(%ordered)) {
 4650:         my @items = sort { $a <=> $b } keys(%ordered);
 4651:         for (my $i=0; $i<@items; $i++) {
 4652:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4653:             my $item = $ordered{$items[$i]};
 4654:             my ($title,$key,$secret,$url,$lifetime,$imgsrc,%sigsel);
 4655:             if (ref($settings->{$item}) eq 'HASH') {
 4656:                 $title = $settings->{$item}->{'title'};
 4657:                 $url = $settings->{$item}->{'url'};
 4658:                 $key = $settings->{$item}->{'key'};
 4659:                 $secret = $settings->{$item}->{'secret'};
 4660:                 $lifetime = $settings->{$item}->{'lifetime'};
 4661:                 my $image = $settings->{$item}->{'image'};
 4662:                 if ($image ne '') {
 4663:                     $imgsrc = '<img src="'.$image.'" alt="'.&mt('Tool Provider icon').'" />';
 4664:                 }
 4665:                 if ($settings->{$item}->{'sigmethod'} eq 'HMAC-256') {
 4666:                     $sigsel{'HMAC-256'} = ' selected="selected"';
 4667:                 } else {
 4668:                     $sigsel{'HMAC-SHA1'} = ' selected="selected"';
 4669:                 }
 4670:             }
 4671:             my $chgstr = ' onchange="javascript:reorderLTITools(this.form,'."'ltitools_".$item."'".');"';
 4672:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 4673:                          .'<select name="ltitools_'.$item.'"'.$chgstr.'>';
 4674:             for (my $k=0; $k<=$maxnum; $k++) {
 4675:                 my $vpos = $k+1;
 4676:                 my $selstr;
 4677:                 if ($k == $i) {
 4678:                     $selstr = ' selected="selected" ';
 4679:                 }
 4680:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 4681:             }
 4682:             $datatable .= '</select>'.('&nbsp;'x2).
 4683:                 '<label><input type="checkbox" name="ltitools_del" value="'.$item.'" />'.
 4684:                 &mt('Delete?').'</label></span></td>'.
 4685:                 '<td colspan="2">'.
 4686:                 '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 4687:                 '<span class="LC_nobreak">'.$lt{'title'}.':<input type="text" size="20" name="ltitools_title_'.$i.'" value="'.$title.'" /></span> '.
 4688:                 ('&nbsp;'x2).
 4689:                 '<span class="LC_nobreak">'.$lt{'version'}.':<select name="ltitools_version_'.$i.'">'.
 4690:                 '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '.
 4691:                 ('&nbsp;'x2).
 4692:                 '<span class="LC_nobreak">'.$lt{'msgtype'}.':<select name="ltitools_msgtype_'.$i.'">'.
 4693:                 '<option value="basic-lti-launch-request" selected="selected">Launch</option></select></span> '.
 4694:                 ('&nbsp;'x2).
 4695:                 '<span class="LC_nobreak">'.$lt{'sigmethod'}.':<select name="ltitools_sigmethod_'.$i.'">'.
 4696:                 '<option value="HMAC-SHA1"'.$sigsel{'HMAC-SHA1'}.'>HMAC-SHA1</option>'.
 4697:                 '<option value="HMAC-SHA256"'.$sigsel{'HMAC-SHA256'}.'>HMAC-SHA256</option></select></span>'.
 4698:                 '<br /><br />'.
 4699:                 '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="40" name="ltitools_url_'.$i.'"'.
 4700:                 ' value="'.$url.'" /></span>'.
 4701:                 ('&nbsp;'x2).
 4702:                 '<span class="LC_nobreak">'.$lt{'key'}.':'.
 4703:                 '<input type="text" size="25" name="ltitools_key_'.$i.'" value="'.$key.'" /></span> '.
 4704:                 ('&nbsp;'x2).
 4705:                 '<span class="LC_nobreak">'.$lt{'lifetime'}.':'.
 4706:                 '<input type="text" size="5" name="ltitools_lifetime_'.$i.'" value="'.$lifetime.'" /></span> '.
 4707:                 ('&nbsp;'x2).
 4708:                 '<span class="LC_nobreak">'.$lt{'secret'}.':'.
 4709:                 '<input type="password" size="20" name="ltitools_secret_'.$i.'" value="'.$secret.'" />'.
 4710:                 '<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>'.
 4711:                 '<input type="hidden" name="ltitools_id_'.$i.'" value="'.$item.'" /></span>'.
 4712:                 '</fieldset>'.
 4713:                 '<fieldset><legend>'.&mt('Optional settings').'</legend>'.
 4714:                 '<span class="LC_nobreak">'.&mt('Display target:');
 4715:             my %currdisp;
 4716:             if (ref($settings->{$item}->{'display'}) eq 'HASH') {
 4717:                 if ($settings->{$item}->{'display'}->{'target'} eq 'window') {
 4718:                     $currdisp{'window'} = ' checked="checked"';
 4719:                 } elsif ($settings->{$item}->{'display'}->{'target'} eq 'tab') {
 4720:                     $currdisp{'tab'} = ' checked="checked"';
 4721:                 } else {
 4722:                     $currdisp{'iframe'} = ' checked="checked"';
 4723:                 }
 4724:                 if ($settings->{$item}->{'display'}->{'width'} =~ /^(\d+)$/) {
 4725:                     $currdisp{'width'} = $1;
 4726:                 }
 4727:                 if ($settings->{$item}->{'display'}->{'height'} =~ /^(\d+)$/) {
 4728:                      $currdisp{'height'} = $1;
 4729:                 }
 4730:                 $currdisp{'linktext'} = $settings->{$item}->{'display'}->{'linktext'};
 4731:                 $currdisp{'explanation'} = $settings->{$item}->{'display'}->{'explanation'};
 4732:             } else {
 4733:                 $currdisp{'iframe'} = ' checked="checked"';
 4734:             }
 4735:             foreach my $disp ('iframe','tab','window') {
 4736:                 $datatable .= '<label><input type="radio" name="ltitools_target_'.$i.'" value="'.$disp.'"'.$currdisp{$disp}.' />'.
 4737:                               $lt{$disp}.'</label>'.('&nbsp;'x2);
 4738:             }
 4739:             $datatable .= ('&nbsp;'x4);
 4740:             foreach my $dimen ('width','height') {
 4741:                 $datatable .= '<label>'.$lt{$dimen}.'&nbsp;'.
 4742:                               '<input type="text" name="ltitools_'.$dimen.'_'.$i.'" size="5" value="'.$currdisp{$dimen}.'" /></label>'.
 4743:                               ('&nbsp;'x2);
 4744:             }
 4745:             $datatable .= '</span><br />'.
 4746:                           '<div class="LC_left_float">'.$lt{'linktext'}.'<br />'.
 4747:                           '<input type="text" name="ltitools_linktext_'.$i.'" size="25" value="'.$currdisp{'linktext'}.'" /></div>'.
 4748:                           '<div class="LC_left_float">'.$lt{'explanation'}.'<br />'.
 4749:                           '<textarea name="ltitools_explanation_'.$i.'" rows="5" cols="40">'.$currdisp{'explanation'}.
 4750:                           '</textarea></div><div style=""></div>'.
 4751:                           '<div style="padding:0;clear:both;margin:0;border:0"></div>';
 4752:             $datatable .= '<span class="LC_nobreak">'.$lt{'icon'}.':&nbsp;';
 4753:             if ($imgsrc) {
 4754:                 $datatable .= $imgsrc.
 4755:                               '<label><input type="checkbox" name="ltitools_image_del"'.
 4756:                               ' value="'.$item.'" />'.&mt('Delete?').'</label></span> '.
 4757:                               '<span class="LC_nobreak">&nbsp;'.&mt('Replace:').'&nbsp;';
 4758:             } else {
 4759:                 $datatable .= '('.&mt('if larger than 21x21 pixels, image will be scaled').')&nbsp;';
 4760:             }
 4761:             if ($switchserver) {
 4762:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 4763:             } else {
 4764:                 $datatable .= '<input type="file" name="ltitools_image_'.$i.'" value="" />';
 4765:             }
 4766:             $datatable .= '</span></fieldset>';
 4767:             my (%checkedfields,%rolemaps,$userincdom);
 4768:             if (ref($settings->{$item}) eq 'HASH') {
 4769:                 if (ref($settings->{$item}->{'fields'}) eq 'HASH') {
 4770:                     %checkedfields = %{$settings->{$item}->{'fields'}};
 4771:                 }
 4772:                 $userincdom = $settings->{$item}->{'incdom'};
 4773:                 if (ref($settings->{$item}->{'roles'}) eq 'HASH') {
 4774:                     %rolemaps = %{$settings->{$item}->{'roles'}};
 4775:                     $checkedfields{'roles'} = 1;
 4776:                 }
 4777:             }
 4778:             $datatable .= '<fieldset><legend>'.&mt('User data sent on launch').'</legend>'.
 4779:                           '<span class="LC_nobreak">';
 4780:             my $userfieldstyle = 'display:none;';
 4781:             my $seluserdom = '';
 4782:             my $unseluserdom = ' selected="selected"';
 4783:             foreach my $field (@fields) {
 4784:                 my ($checked,$onclick,$id,$spacer);
 4785:                 if ($checkedfields{$field}) {
 4786:                     $checked = ' checked="checked"';
 4787:                 }
 4788:                 if ($field eq 'user') {
 4789:                     $id = ' id="ltitools_user_field_'.$i.'"';
 4790:                     $onclick = ' onclick="toggleLTITools(this.form,'."'$field','$i'".')"';
 4791:                     if ($checked) {
 4792:                         $userfieldstyle = 'display:inline-block';
 4793:                         if ($userincdom) {
 4794:                             $seluserdom = $unseluserdom;
 4795:                             $unseluserdom = '';
 4796:                         }
 4797:                     }
 4798:                 } else {
 4799:                     $spacer = ('&nbsp;' x2);
 4800:                 }
 4801:                 $datatable .= '<label>'.
 4802:                               '<input type="checkbox" name="ltitools_fields_'.$i.'" value="'.$field.'"'.$id.$checked.$onclick.' />'.
 4803:                               $lt{$field}.'</label>'.$spacer;
 4804:             }
 4805:             $datatable .= '</span>';
 4806:             $datatable .= '<div style="'.$userfieldstyle.'" id="ltitools_user_div_'.$i.'">'.
 4807:                           '<span class="LC_nobreak"> : '.
 4808:                           '<select name="ltitools_userincdom_'.$i.'">'.
 4809:                           '<option value="">'.&mt('Select').'</option>'.
 4810:                           '<option value="0"'.$unseluserdom.'>'.&mt('username').'</option>'.
 4811:                           '<option value="1"'.$seluserdom.'>'.&mt('username:domain').'</option>'.
 4812:                           '</select></span></div>';
 4813:             $datatable .= '</fieldset>'.
 4814:                           '<fieldset><legend>'.&mt('Role mapping').'</legend><table><tr>';
 4815:             foreach my $role (@courseroles) {
 4816:                 my ($selected,$selectnone);
 4817:                 if (!$rolemaps{$role}) {
 4818:                     $selectnone = ' selected="selected"';
 4819:                 }
 4820:                 $datatable .= '<td align="center">'.
 4821:                               &Apache::lonnet::plaintext($role,'Course').'<br />'.
 4822:                               '<select name="ltitools_roles_'.$role.'_'.$i.'">'.
 4823:                               '<option value=""'.$selectnone.'>'.&mt('Select').'</option>';
 4824:                 foreach my $ltirole (@ltiroles) {
 4825:                     unless ($selectnone) {
 4826:                         if ($rolemaps{$role} eq $ltirole) {
 4827:                             $selected = ' selected="selected"';
 4828:                         } else {
 4829:                             $selected = '';
 4830:                         }
 4831:                     }
 4832:                     $datatable .= '<option value="'.$ltirole.'"'.$selected.'>'.$ltirole.'</option>';
 4833:                 }
 4834:                 $datatable .= '</select></td>';
 4835:             }
 4836:             $datatable .= '</tr></table></fieldset>';
 4837:             my %courseconfig;
 4838:             if (ref($settings->{$item}) eq 'HASH') {
 4839:                 if (ref($settings->{$item}->{'crsconf'}) eq 'HASH') {
 4840:                     %courseconfig = %{$settings->{$item}->{'crsconf'}};
 4841:                 }
 4842:             }
 4843:             $datatable .= '<fieldset><legend>'.&mt('Configurable in course').'</legend><span class="LC_nobreak">';
 4844:             foreach my $item ('label','title','target','linktext','explanation','append') {
 4845:                 my $checked;
 4846:                 if ($courseconfig{$item}) {
 4847:                     $checked = ' checked="checked"';
 4848:                 }
 4849:                 $datatable .= '<label>'.
 4850:                        '<input type="checkbox" name="ltitools_courseconfig_'.$i.'" value="'.$item.'"'.$checked.' />'.
 4851:                        $lt{'crs'.$item}.'</label>'.('&nbsp;' x2)."\n";
 4852:             }
 4853:             $datatable .= '</span></fieldset>'.
 4854:                           '<fieldset><legend>'.&mt('Custom items sent on launch').'</legend>'.
 4855:                           '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>';
 4856:             if (ref($settings->{$item}->{'custom'}) eq 'HASH') {
 4857:                 my %custom = %{$settings->{$item}->{'custom'}};
 4858:                 if (keys(%custom) > 0) {
 4859:                     foreach my $key (sort(keys(%custom))) {
 4860:                         $datatable .= '<tr><td><span class="LC_nobreak">'.
 4861:                                       '<label><input type="checkbox" name="ltitools_customdel_'.$i.'" value="'.
 4862:                                       $key.'" />'.&mt('Delete').'</label></span></td><td>'.$key.'</td>'.
 4863:                                       '<td><input type="text" name="ltitools_customval_'.$key.'_'.$i.'"'.
 4864:                                       ' value="'.$custom{$key}.'" /></td></tr>';
 4865:                     }
 4866:                 }
 4867:             }
 4868:             $datatable .= '<tr><td><span class="LC_nobreak">'.
 4869:                           '<label><input type="checkbox" name="ltitools_customadd" value="'.$i.'" />'.
 4870:                           &mt('Add').'</label></span></td><td><input type="text" name="ltitools_custom_name_'.$i.'" />'.
 4871:                           '</td><td><input type="text" name="ltitools_custom_value_'.$i.'" /></td></tr>';
 4872:             $datatable .= '</table></fieldset></td></tr>'."\n";
 4873:             $itemcount ++;
 4874:         }
 4875:     }
 4876:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4877:     my $chgstr = ' onchange="javascript:reorderLTITools(this.form,'."'ltitools_add_pos'".');"';
 4878:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 4879:                   '<input type="hidden" name="ltitools_maxnum" value="'.$maxnum.'" />'."\n".
 4880:                   '<select name="ltitools_add_pos"'.$chgstr.'>';
 4881:     for (my $k=0; $k<$maxnum+1; $k++) {
 4882:         my $vpos = $k+1;
 4883:         my $selstr;
 4884:         if ($k == $maxnum) {
 4885:             $selstr = ' selected="selected" ';
 4886:         }
 4887:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 4888:     }
 4889:     $datatable .= '</select>&nbsp;'."\n".
 4890:                   '<input type="checkbox" name="ltitools_add" value="1" />'.&mt('Add').'</span></td>'."\n".
 4891:                   '<td colspan="2">'.
 4892:                   '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 4893:                   '<span class="LC_nobreak">'.$lt{'title'}.':<input type="text" size="20" name="ltitools_add_title" value="" /></span> '."\n".
 4894:                   ('&nbsp;'x2).
 4895:                   '<span class="LC_nobreak">'.$lt{'version'}.':<select name="ltitools_add_version">'.
 4896:                   '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '."\n".
 4897:                   ('&nbsp;'x2).
 4898:                   '<span class="LC_nobreak">'.$lt{'msgtype'}.':<select name="ltitools_add_msgtype">'.
 4899:                   '<option value="basic-lti-launch-request" selected="selected">Launch</option></select></span> '.
 4900:                   '<span class="LC_nobreak">'.$lt{'sigmethod'}.':<select name="ltitools_add_sigmethod">'.
 4901:                   '<option value="HMAC-SHA1" selected="selected">HMAC-SHA1</option>'.
 4902:                   '<option value="HMAC-SHA256">HMAC-SHA256</option></select></span>'.
 4903:                   '<br />'.
 4904:                   '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="40" name="ltitools_add_url" value="" /></span> '."\n".
 4905:                   ('&nbsp;'x2).
 4906:                   '<span class="LC_nobreak">'.$lt{'key'}.':<input type="text" size="25" name="ltitools_add_key" value="" /></span> '."\n".
 4907:                   ('&nbsp;'x2).
 4908:                   '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" size="5" name="ltitools_add_lifetime" value="300" /></span> '."\n".
 4909:                   ('&nbsp;'x2).
 4910:                   '<span class="LC_nobreak">'.$lt{'secret'}.':<input type="password" size="20" name="ltitools_add_secret" value="" />'.
 4911:                   '<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".
 4912:                   '</fieldset>'.
 4913:                   '<fieldset><legend>'.&mt('Optional settings').'</legend>'.
 4914:                   '<span class="LC_nobreak">'.&mt('Display target:');
 4915:     my %defaultdisp;
 4916:     $defaultdisp{'iframe'} = ' checked="checked"';
 4917:     foreach my $disp ('iframe','tab','window') {
 4918:         $datatable .= '<label><input type="radio" name="ltitools_add_target" value="'.$disp.'"'.$defaultdisp{$disp}.' />'.
 4919:                       $lt{$disp}.'</label>'.('&nbsp;'x2);
 4920:     }
 4921:     $datatable .= ('&nbsp;'x4);
 4922:     foreach my $dimen ('width','height') {
 4923:         $datatable .= '<label>'.$lt{$dimen}.'&nbsp;'.
 4924:                       '<input type="text" name="ltitools_add_'.$dimen.'" size="5" /></label>'.
 4925:                       ('&nbsp;'x2);
 4926:     }
 4927:     $datatable .= '</span><br />'.
 4928:                   '<div class="LC_left_float">'.$lt{'linktext'}.'<br />'.
 4929:                   '<input type="text" name="ltitools_add_linktext" size="5" /></div>'.
 4930:                   '<div class="LC_left_float">'.$lt{'explanation'}.'<br />'.
 4931:                   '<textarea name="ltitools_add_explanation" rows="5" cols="40"></textarea>'.
 4932:                   '</div><div style=""></div>'.
 4933:                   '<div style="padding:0;clear:both;margin:0;border:0"></div>';
 4934:     $datatable .= '<span class="LC_nobreak">'.$lt{'icon'}.':&nbsp;'.
 4935:                   '('.&mt('if larger than 21x21 pixels, image will be scaled').')&nbsp;';
 4936:     if ($switchserver) {
 4937:         $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 4938:     } else {
 4939:         $datatable .= '<input type="file" name="ltitools_add_image" value="" />';
 4940:     }
 4941:     $datatable .= '</span></fieldset>'.
 4942:                   '<fieldset><legend>'.&mt('User data sent on launch').'</legend>'.
 4943:                   '<span class="LC_nobreak">';
 4944:     foreach my $field (@fields) {
 4945:         my ($id,$onclick,$spacer);
 4946:         if ($field eq 'user') {
 4947:             $id = ' id="ltitools_user_field_add"';
 4948:             $onclick = ' onclick="toggleLTITools(this.form,'."'$field','add'".')"';
 4949:         } else {
 4950:             $spacer = ('&nbsp;' x2);
 4951:         }
 4952:         $datatable .= '<label>'.
 4953:                       '<input type="checkbox" name="ltitools_add_fields" value="'.$field.'"'.$id.$onclick.' />'.
 4954:                       $lt{$field}.'</label>'.$spacer;
 4955:     }
 4956:     $datatable .= '</span>'.
 4957:                   '<div style="display:none;" id="ltitools_user_div_add">'.
 4958:                   '<span class="LC_nobreak"> : '.
 4959:                   '<select name="ltitools_userincdom_add">'.
 4960:                   '<option value="" selected="selected">'.&mt('Select').'</option>'.
 4961:                   '<option value="0">'.&mt('username').'</option>'.
 4962:                   '<option value="1">'.&mt('username:domain').'</option>'.
 4963:                   '</select></span></div></fieldset>';
 4964:     $datatable .= '<fieldset><legend>'.&mt('Role mapping').'</legend><table><tr>';
 4965:     foreach my $role (@courseroles) {
 4966:         my ($checked,$checkednone);
 4967:         $datatable .= '<td align="center">'.
 4968:                       &Apache::lonnet::plaintext($role,'Course').'<br />'.
 4969:                       '<select name="ltitools_add_roles_'.$role.'">'.
 4970:                       '<option value="" selected="selected">'.&mt('Select').'</option>';
 4971:         foreach my $ltirole (@ltiroles) {
 4972:             $datatable .= '<option value="'.$ltirole.'">'.$ltirole.'</option>';
 4973:         }
 4974:         $datatable .= '</select></td>';
 4975:     }
 4976:     $datatable .= '</tr></table></fieldset>'.
 4977:                   '<fieldset><legend>'.&mt('Configurable in course').'</legend><span class="LC_nobreak">';
 4978:     foreach my $item ('label','title','target','linktext','explanation','append') {
 4979:         $datatable .= '<label>'.
 4980:                       '<input type="checkbox" name="ltitools_courseconfig" value="'.$item.'" checked="checked" />'.
 4981:                       $lt{'crs'.$item}.'</label>'.('&nbsp;' x2)."\n";
 4982:     }
 4983:     $datatable .= '</span></fieldset>'.
 4984:                   '<fieldset><legend>'.&mt('Custom items sent on launch').'</legend>'.
 4985:                   '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>'.
 4986:                   '<tr><td><span class="LC_nobreak">'.
 4987:                   '<label><input type="checkbox" name="ltitools_add_custom" value="1" />'.
 4988:                   &mt('Add').'</label></span></td><td><input type="text" name="ltitools_add_custom_name" />'.
 4989:                   '</td><td><input type="text" name="ltitools_add_custom_value" /></td></tr>'.
 4990:                   '</table></fieldset>'."\n".
 4991:                   '</td>'."\n".
 4992:                   '</tr>'."\n";
 4993:     $itemcount ++;
 4994:     return $datatable;
 4995: }
 4996: 
 4997: sub ltitools_names {
 4998:     my %lt = &Apache::lonlocal::texthash(
 4999:                                           'title'          => 'Title',
 5000:                                           'version'        => 'Version',
 5001:                                           'msgtype'        => 'Message Type',
 5002:                                           'sigmethod'      => 'Signature Method',
 5003:                                           'url'            => 'URL',
 5004:                                           'key'            => 'Key',
 5005:                                           'lifetime'       => 'Nonce lifetime (s)',
 5006:                                           'secret'         => 'Secret',
 5007:                                           'icon'           => 'Icon',
 5008:                                           'user'           => 'User',
 5009:                                           'fullname'       => 'Full Name',
 5010:                                           'firstname'      => 'First Name',
 5011:                                           'lastname'       => 'Last Name',
 5012:                                           'email'          => 'E-mail',
 5013:                                           'roles'          => 'Role',
 5014:                                           'window'         => 'Window',
 5015:                                           'tab'            => 'Tab',
 5016:                                           'iframe'         => 'iFrame',
 5017:                                           'height'         => 'Height',
 5018:                                           'width'          => 'Width',
 5019:                                           'linktext'       => 'Default Link Text',
 5020:                                           'explanation'    => 'Default Explanation',
 5021:                                           'crstarget'      => 'Display target',
 5022:                                           'crslabel'       => 'Course label',
 5023:                                           'crstitle'       => 'Course title',
 5024:                                           'crslinktext'    => 'Link Text',
 5025:                                           'crsexplanation' => 'Explanation',
 5026:                                           'crsappend'      => 'Provider URL',
 5027:                                         );
 5028: 
 5029:     return %lt;
 5030: }
 5031: 
 5032: sub print_coursedefaults {
 5033:     my ($position,$dom,$settings,$rowtotal) = @_;
 5034:     my ($css_class,$datatable,%checkedon,%checkedoff,%defaultchecked,@toggles);
 5035:     my $itemcount = 1;
 5036:     my %choices =  &Apache::lonlocal::texthash (
 5037:         uploadquota          => 'Default quota for files uploaded directly to course/community using Course Editor (MB)',
 5038:         anonsurvey_threshold => 'Responder count needed before showing submissions for anonymous surveys',
 5039:         coursecredits        => 'Credits can be specified for courses',
 5040:         uselcmath            => 'Math preview uses LON-CAPA previewer (javascript) in place of DragMath (Java)',
 5041:         usejsme              => 'Molecule editor uses JSME (HTML5) in place of JME (Java)',
 5042:         inline_chem          => 'Use inline previewer for chemical reaction response in place of pop-up',
 5043:         texengine            => 'Default method to display mathematics',
 5044:         postsubmit           => 'Disable submit button/keypress following student submission',
 5045:         canclone             => "People who may clone a course (besides course's owner and coordinators)",
 5046:         mysqltables          => 'Lifetime (s) of "Temporary" MySQL tables (student performance data) on homeserver',
 5047:     );
 5048:     my %staticdefaults = (
 5049:                            anonsurvey_threshold => 10,
 5050:                            uploadquota          => 500,
 5051:                            postsubmit           => 60,
 5052:                            mysqltables          => 172800,
 5053:                          );
 5054:     if ($position eq 'top') {
 5055:         %defaultchecked = (
 5056:                             'uselcmath'       => 'on',
 5057:                             'usejsme'         => 'on',
 5058:                             'inline_chem'     => 'on',
 5059:                             'canclone'        => 'none',
 5060:                           );
 5061:         @toggles = ('uselcmath','usejsme','inline_chem');
 5062:         my $deftex = $Apache::lonnet::deftex;
 5063:         if (ref($settings) eq 'HASH') {
 5064:             if ($settings->{'texengine'}) {
 5065:                 if ($settings->{'texengine'} =~ /^(MathJax|mimetex|tth)$/) {
 5066:                     $deftex = $settings->{'texengine'};
 5067:                 }
 5068:             }
 5069:         }
 5070:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5071:         my $mathdisp = '<tr'.$css_class.'><td style="vertical-align: top">'.
 5072:                        '<span class="LC_nobreak">'.$choices{'texengine'}.
 5073:                        '</span></td><td class="LC_right_item">'.
 5074:                        '<select name="texengine">'."\n";
 5075:         my %texoptions = (
 5076:                             MathJax  => 'MathJax',
 5077:                             mimetex  => &mt('Convert to Images'),
 5078:                             tth      => &mt('TeX to HTML'),
 5079:                          );
 5080:         foreach my $renderer ('MathJax','mimetex','tth') {
 5081:             my $selected = '';
 5082:             if ($renderer eq $deftex) {
 5083:                 $selected = ' selected="selected"';
 5084:             }
 5085:             $mathdisp .= '<option value="'.$renderer.'"'.$selected.'>'.$texoptions{$renderer}.'</option>'."\n";
 5086:         }
 5087:         $mathdisp .= '</select></td></tr>'."\n";
 5088:         $itemcount ++;
 5089:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 5090:                                                      \%choices,$itemcount);
 5091:         $datatable = $mathdisp.$datatable;
 5092:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5093:         $datatable .=
 5094:             '<tr'.$css_class.'><td valign="top">'.
 5095:             '<span class="LC_nobreak">'.$choices{'canclone'}.
 5096:             '</span></td><td class="LC_left_item">';
 5097:         my $currcanclone = 'none';
 5098:         my $onclick;
 5099:         my @cloneoptions = ('none','domain');
 5100:         my %clonetitles = &Apache::lonlocal::texthash (
 5101:                              none     => 'No additional course requesters',
 5102:                              domain   => "Any course requester in course's domain",
 5103:                              instcode => 'Course requests for official courses ...',
 5104:                           );
 5105:         my (%codedefaults,@code_order,@posscodes);
 5106:         if (&Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
 5107:                                                     \@code_order) eq 'ok') {
 5108:             if (@code_order > 0) {
 5109:                 push(@cloneoptions,'instcode');
 5110:                 $onclick = ' onclick="toggleDisplay(this.form,'."'cloneinstcode'".');"';
 5111:             }
 5112:         }
 5113:         if (ref($settings) eq 'HASH') {
 5114:             if ($settings->{'canclone'}) {
 5115:                 if (ref($settings->{'canclone'}) eq 'HASH') {
 5116:                     if (ref($settings->{'canclone'}{'instcode'}) eq 'ARRAY') {
 5117:                         if (@code_order > 0) {
 5118:                             $currcanclone = 'instcode';
 5119:                             @posscodes = @{$settings->{'canclone'}{'instcode'}};
 5120:                         }
 5121:                     }
 5122:                 } elsif ($settings->{'canclone'} eq 'domain') {
 5123:                     $currcanclone = $settings->{'canclone'};
 5124:                 }
 5125:             }
 5126:         }
 5127:         foreach my $option (@cloneoptions) {
 5128:             my ($checked,$additional);
 5129:             if ($currcanclone eq $option) {
 5130:                 $checked = ' checked="checked"';
 5131:             }
 5132:             if ($option eq 'instcode') {
 5133:                 if (@code_order) {
 5134:                     my $show = 'none';
 5135:                     if ($checked) {
 5136:                         $show = 'block';
 5137:                     }
 5138:                     $additional = '<div id="cloneinstcode" style="display:'.$show.'" />'.
 5139:                                   &mt('Institutional codes for new and cloned course have identical:').
 5140:                                   '<br />';
 5141:                     foreach my $item (@code_order) {
 5142:                         my $codechk;
 5143:                         if ($checked) {
 5144:                             if (grep(/^\Q$item\E$/,@posscodes)) {
 5145:                                 $codechk = ' checked="checked"';
 5146:                             }
 5147:                         }
 5148:                         $additional .= '<label>'.
 5149:                                        '<input type="checkbox" name="clonecode" value="'.$item.'"'.$codechk.' />'.
 5150:                                        $item.'</label>';
 5151:                     }
 5152:                     $additional .= ('&nbsp;'x2).'('.&mt('check as many as needed').')</div>';
 5153:                 }
 5154:             }
 5155:             $datatable .=
 5156:                 '<span class="LC_nobreak"><label><input type="radio" name="canclone"'.$checked.
 5157:                 ' value="'.$option.'"'.$onclick.' />'.$clonetitles{$option}.
 5158:                 '</label>&nbsp;'.$additional.'</span><br />';
 5159:         }
 5160:         $datatable .= '</td>'.
 5161:                       '</tr>';
 5162:         $itemcount ++;
 5163:     } else {
 5164:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 5165:         my ($currdefresponder,%defcredits,%curruploadquota,%deftimeout,%currmysql);
 5166:         my $currusecredits = 0;
 5167:         my $postsubmitclient = 1;
 5168:         my @types = ('official','unofficial','community','textbook');
 5169:         if (ref($settings) eq 'HASH') {
 5170:             $currdefresponder = $settings->{'anonsurvey_threshold'};
 5171:             if (ref($settings->{'uploadquota'}) eq 'HASH') {
 5172:                 foreach my $type (keys(%{$settings->{'uploadquota'}})) {
 5173:                     $curruploadquota{$type} = $settings->{'uploadquota'}{$type};
 5174:                 }
 5175:             }
 5176:             if (ref($settings->{'coursecredits'}) eq 'HASH') {
 5177:                 foreach my $type (@types) {
 5178:                     next if ($type eq 'community');
 5179:                     $defcredits{$type} = $settings->{'coursecredits'}->{$type};
 5180:                     if ($defcredits{$type} ne '') {
 5181:                         $currusecredits = 1;
 5182:                     }
 5183:                 }
 5184:             }
 5185:             if (ref($settings->{'postsubmit'}) eq 'HASH') {
 5186:                 if ($settings->{'postsubmit'}->{'client'} eq 'off') {
 5187:                     $postsubmitclient = 0;
 5188:                     foreach my $type (@types) {
 5189:                         $deftimeout{$type} = $staticdefaults{'postsubmit'};
 5190:                     }
 5191:                 } else {
 5192:                     foreach my $type (@types) {
 5193:                         if (ref($settings->{'postsubmit'}->{'timeout'}) eq 'HASH') {
 5194:                             if ($settings->{'postsubmit'}->{'timeout'}->{$type} =~ /^\d+$/) {
 5195:                                 $deftimeout{$type} = $settings->{'postsubmit'}->{'timeout'}->{$type};
 5196:                             } else {
 5197:                                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 5198:                             }
 5199:                         } else {
 5200:                             $deftimeout{$type} = $staticdefaults{'postsubmit'};
 5201:                         }
 5202:                     }
 5203:                 }
 5204:             } else {
 5205:                 foreach my $type (@types) {
 5206:                     $deftimeout{$type} = $staticdefaults{'postsubmit'};
 5207:                 }
 5208:             }
 5209:             if (ref($settings->{'mysqltables'}) eq 'HASH') {
 5210:                 foreach my $type (keys(%{$settings->{'mysqltables'}})) {
 5211:                     $currmysql{$type} = $settings->{'mysqltables'}{$type};
 5212:                 }
 5213:             } else {
 5214:                 foreach my $type (@types) {
 5215:                     $currmysql{$type} = $staticdefaults{'mysqltables'};
 5216:                 }
 5217:             }
 5218:         } else {
 5219:             foreach my $type (@types) {
 5220:                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 5221:             }
 5222:         }
 5223:         if (!$currdefresponder) {
 5224:             $currdefresponder = $staticdefaults{'anonsurvey_threshold'};
 5225:         } elsif ($currdefresponder < 1) {
 5226:             $currdefresponder = 1;
 5227:         }
 5228:         foreach my $type (@types) {
 5229:             if ($curruploadquota{$type} eq '') {
 5230:                 $curruploadquota{$type} = $staticdefaults{'uploadquota'};
 5231:             }
 5232:         }
 5233:         $datatable .=
 5234:                 '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 5235:                 $choices{'anonsurvey_threshold'}.
 5236:                 '</span></td>'.
 5237:                 '<td class="LC_right_item"><span class="LC_nobreak">'.
 5238:                 '<input type="text" name="anonsurvey_threshold"'.
 5239:                 ' value="'.$currdefresponder.'" size="5" /></span>'.
 5240:                 '</td></tr>'."\n";
 5241:         $itemcount ++;
 5242:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 5243:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 5244:                       $choices{'uploadquota'}.
 5245:                       '</span></td>'.
 5246:                       '<td align="right" class="LC_right_item">'.
 5247:                       '<table><tr>';
 5248:         foreach my $type (@types) {
 5249:             $datatable .= '<td align="center">'.&mt($type).'<br />'.
 5250:                            '<input type="text" name="uploadquota_'.$type.'"'.
 5251:                            ' value="'.$curruploadquota{$type}.'" size="5" /></td>';
 5252:         }
 5253:         $datatable .= '</tr></table></td></tr>'."\n";
 5254:         $itemcount ++;
 5255:         my $onclick = "toggleDisplay(this.form,'credits');";
 5256:         my $display = 'none';
 5257:         if ($currusecredits) {
 5258:             $display = 'block';
 5259:         }
 5260:         my $additional = '<div id="credits" style="display: '.$display.'">'.
 5261:                          '<i>'.&mt('Default credits').'</i><br /><table><tr>';
 5262:         foreach my $type (@types) {
 5263:             next if ($type eq 'community');
 5264:             $additional .= '<td align="center">'.&mt($type).'<br />'.
 5265:                            '<input type="text" name="'.$type.'_credits"'.
 5266:                            ' value="'.$defcredits{$type}.'" size="3" /></td>';
 5267:         }
 5268:         $additional .= '</tr></table></div>'."\n";
 5269:         %defaultchecked = ('coursecredits' => 'off');
 5270:         @toggles = ('coursecredits');
 5271:         my $current = {
 5272:                         'coursecredits' => $currusecredits,
 5273:                       };
 5274:         (my $table,$itemcount) =
 5275:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 5276:                                \%choices,$itemcount,$onclick,$additional,'left');
 5277:         $datatable .= $table;
 5278:         $onclick = "toggleDisplay(this.form,'studentsubmission');";
 5279:         my $display = 'none';
 5280:         if ($postsubmitclient) {
 5281:             $display = 'block';
 5282:         }
 5283:         $additional = '<div id="studentsubmission" style="display: '.$display.'">'.
 5284:                       &mt('Number of seconds submit is disabled').'<br />'.
 5285:                       '<i>'.&mt('Enter 0 to remain disabled until page reload.').'</i><br />'.
 5286:                       '<table><tr>';
 5287:         foreach my $type (@types) {
 5288:             $additional .= '<td align="center">'.&mt($type).'<br />'.
 5289:                            '<input type="text" name="'.$type.'_timeout" value="'.
 5290:                            $deftimeout{$type}.'" size="5" /></td>';
 5291:         }
 5292:         $additional .= '</tr></table></div>'."\n";
 5293:         %defaultchecked = ('postsubmit' => 'on');
 5294:         @toggles = ('postsubmit');
 5295:         $current = {
 5296:                        'postsubmit' => $postsubmitclient,
 5297:                    };
 5298:         ($table,$itemcount) =
 5299:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 5300:                                \%choices,$itemcount,$onclick,$additional,'left');
 5301:         $datatable .= $table;
 5302:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 5303:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 5304:                       $choices{'mysqltables'}.
 5305:                       '</span></td>'.
 5306:                       '<td align="right" class="LC_right_item">'.
 5307:                       '<table><tr>';
 5308:         foreach my $type (@types) {
 5309:             $datatable .= '<td align="center">'.&mt($type).'<br />'.
 5310:                            '<input type="text" name="mysqltables_'.$type.'"'.
 5311:                            ' value="'.$currmysql{$type}.'" size="8" /></td>';
 5312:         }
 5313:         $datatable .= '</tr></table></td></tr>'."\n";
 5314:         $itemcount ++;
 5315: 
 5316:     }
 5317:     $$rowtotal += $itemcount;
 5318:     return $datatable;
 5319: }
 5320: 
 5321: sub print_selfenrollment {
 5322:     my ($position,$dom,$settings,$rowtotal) = @_;
 5323:     my ($css_class,$datatable);
 5324:     my $itemcount = 1;
 5325:     my @types = ('official','unofficial','community','textbook');
 5326:     if (($position eq 'top') || ($position eq 'middle')) {
 5327:         my ($rowsref,$titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
 5328:         my %descs = &Apache::lonuserutils::selfenroll_default_descs();
 5329:         my @rows;
 5330:         my $key;
 5331:         if ($position eq 'top') {
 5332:             $key = 'admin'; 
 5333:             if (ref($rowsref) eq 'ARRAY') {
 5334:                 @rows = @{$rowsref};
 5335:             }
 5336:         } elsif ($position eq 'middle') {
 5337:             $key = 'default';
 5338:             @rows = ('types','registered','approval','limit');
 5339:         }
 5340:         foreach my $row (@rows) {
 5341:             if (defined($titlesref->{$row})) {
 5342:                 $itemcount ++;
 5343:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5344:                 $datatable .= '<tr'.$css_class.'>'.
 5345:                               '<td>'.$titlesref->{$row}.'</td>'.
 5346:                               '<td class="LC_left_item">'.
 5347:                               '<table><tr>';
 5348:                 my (%current,%currentcap);
 5349:                 if (ref($settings) eq 'HASH') {
 5350:                     if (ref($settings->{$key}) eq 'HASH') {
 5351:                         foreach my $type (@types) {
 5352:                             if (ref($settings->{$key}->{$type}) eq 'HASH') {
 5353:                                 $current{$type} = $settings->{$key}->{$type}->{$row};
 5354:                             }
 5355:                             if (($row eq 'limit') && ($key eq 'default')) {
 5356:                                 if (ref($settings->{$key}->{$type}) eq 'HASH') {
 5357:                                     $currentcap{$type} = $settings->{$key}->{$type}->{'cap'};
 5358:                                 }
 5359:                             }
 5360:                         }
 5361:                     }
 5362:                 }
 5363:                 my %roles = (
 5364:                              '0' => &Apache::lonnet::plaintext('dc'),
 5365:                             ); 
 5366:             
 5367:                 foreach my $type (@types) {
 5368:                     unless (($row eq 'registered') && ($key eq 'default')) {
 5369:                         $datatable .= '<th>'.&mt($type).'</th>';
 5370:                     }
 5371:                 }
 5372:                 unless (($row eq 'registered') && ($key eq 'default')) {
 5373:                     $datatable .= '</tr><tr>';
 5374:                 }
 5375:                 foreach my $type (@types) {
 5376:                     if ($type eq 'community') {
 5377:                         $roles{'1'} = &mt('Community personnel');
 5378:                     } else {
 5379:                         $roles{'1'} = &mt('Course personnel');
 5380:                     }
 5381:                     $datatable .= '<td style="vertical-align: top">';
 5382:                     if ($position eq 'top') {
 5383:                         my %checked;
 5384:                         if ($current{$type} eq '0') {
 5385:                             $checked{'0'} = ' checked="checked"';
 5386:                         } else {
 5387:                             $checked{'1'} = ' checked="checked"';
 5388:                         }
 5389:                         foreach my $role ('1','0') {
 5390:                             $datatable .= '<span class="LC_nobreak"><label>'.
 5391:                                           '<input type="radio" name="selfenrolladmin_'.$row.'_'.$type.'" '.
 5392:                                           'value="'.$role.'"'.$checked{$role}.' />'.
 5393:                                           $roles{$role}.'</label></span> ';
 5394:                         }
 5395:                     } else {
 5396:                         if ($row eq 'types') {
 5397:                             my %checked;
 5398:                             if ($current{$type} =~ /^(all|dom)$/) {
 5399:                                 $checked{$1} = ' checked="checked"';
 5400:                             } else {
 5401:                                 $checked{''} = ' checked="checked"';
 5402:                             }
 5403:                             foreach my $val ('','dom','all') {
 5404:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 5405:                                               '<input type ="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 5406:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 5407:                             }
 5408:                         } elsif ($row eq 'registered') {
 5409:                             my %checked;
 5410:                             if ($current{$type} eq '1') {
 5411:                                 $checked{'1'} = ' checked="checked"';
 5412:                             } else {
 5413:                                 $checked{'0'} = ' checked="checked"';
 5414:                             }
 5415:                             foreach my $val ('0','1') {
 5416:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 5417:                                               '<input type ="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 5418:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 5419:                             }
 5420:                         } elsif ($row eq 'approval') {
 5421:                             my %checked;
 5422:                             if ($current{$type} =~ /^([12])$/) {
 5423:                                 $checked{$1} = ' checked="checked"';
 5424:                             } else {
 5425:                                 $checked{'0'} = ' checked="checked"';
 5426:                             }
 5427:                             for my $val (0..2) {
 5428:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 5429:                                               '<input type="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 5430:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 5431:                             }
 5432:                         } elsif ($row eq 'limit') {
 5433:                             my %checked;
 5434:                             if ($current{$type} =~ /^(allstudents|selfenrolled)$/) {
 5435:                                 $checked{$1} = ' checked="checked"';
 5436:                             } else {
 5437:                                 $checked{'none'} = ' checked="checked"';
 5438:                             }
 5439:                             my $cap;
 5440:                             if ($currentcap{$type} =~ /^\d+$/) {
 5441:                                 $cap = $currentcap{$type};
 5442:                             }
 5443:                             foreach my $val ('none','allstudents','selfenrolled') {
 5444:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 5445:                                               '<input type="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 5446:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 5447:                             }
 5448:                             $datatable .= '<br />'.
 5449:                                           '<span class="LC_nobreak">'.&mt('Maximum allowed: ').
 5450:                                           '<input type="text" name="selfenrolldefault_cap_'.$type.'" size = "5" value="'.$cap.'" />'.
 5451:                                           '</span>'; 
 5452:                         }
 5453:                     }
 5454:                     $datatable .= '</td>';
 5455:                 }
 5456:                 $datatable .= '</tr>';
 5457:             }
 5458:             $datatable .= '</table></td></tr>';
 5459:         }
 5460:     } elsif ($position eq 'bottom') {
 5461:         $datatable .= &print_validation_rows('selfenroll',$dom,$settings,\$itemcount);
 5462:     }
 5463:     $$rowtotal += $itemcount;
 5464:     return $datatable;
 5465: }
 5466: 
 5467: sub print_validation_rows {
 5468:     my ($caller,$dom,$settings,$rowtotal) = @_;
 5469:     my ($itemsref,$namesref,$fieldsref);
 5470:     if ($caller eq 'selfenroll') { 
 5471:         ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
 5472:     } elsif ($caller eq 'requestcourses') {
 5473:         ($itemsref,$namesref,$fieldsref) = &Apache::loncoursequeueadmin::requestcourses_validation_types();
 5474:     }
 5475:     my %currvalidation;
 5476:     if (ref($settings) eq 'HASH') {
 5477:         if (ref($settings->{'validation'}) eq 'HASH') {
 5478:             %currvalidation = %{$settings->{'validation'}};
 5479:         }
 5480:     }
 5481:     my $datatable;
 5482:     my $itemcount = 0;
 5483:     foreach my $item (@{$itemsref}) {
 5484:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 5485:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 5486:                       $namesref->{$item}.
 5487:                       '</span></td>'.
 5488:                       '<td class="LC_left_item">';
 5489:         if (($item eq 'url') || ($item eq 'button')) {
 5490:             $datatable .= '<span class="LC_nobreak">'.
 5491:                           '<input type="text" name="'.$caller.'_validation_'.$item.'"'.
 5492:                           ' value="'.$currvalidation{$item}.'" size="50" /></span>';
 5493:         } elsif ($item eq 'fields') {
 5494:             my @currfields;
 5495:             if (ref($currvalidation{$item}) eq 'ARRAY') {
 5496:                 @currfields = @{$currvalidation{$item}};
 5497:             }
 5498:             foreach my $field (@{$fieldsref}) {
 5499:                 my $check = '';
 5500:                 if (grep(/^\Q$field\E$/,@currfields)) {
 5501:                     $check = ' checked="checked"';
 5502:                 }
 5503:                 $datatable .= '<span class="LC_nobreak"><label>'.
 5504:                               '<input type="checkbox" name="'.$caller.'_validation_fields"'.
 5505:                               ' value="'.$field.'"'.$check.' />'.$field.
 5506:                               '</label></span> ';
 5507:             }
 5508:         } elsif ($item eq 'markup') {
 5509:             $datatable .= '<textarea name="'.$caller.'_validation_markup" cols="50" rows="5">'.
 5510:                            $currvalidation{$item}.
 5511:                               '</textarea>';
 5512:         }
 5513:         $datatable .= '</td></tr>'."\n";
 5514:         if (ref($rowtotal)) {
 5515:             $itemcount ++;
 5516:         }
 5517:     }
 5518:     if ($caller eq 'requestcourses') {
 5519:         my %currhash;
 5520:         if (ref($settings) eq 'HASH') {
 5521:             if (ref($settings->{'validation'}) eq 'HASH') {
 5522:                 if ($settings->{'validation'}{'dc'} ne '') {
 5523:                     $currhash{$settings->{'validation'}{'dc'}} = 1;
 5524:                 }
 5525:             }
 5526:         }
 5527:         my $numinrow = 2;
 5528:         my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 5529:                                                        'validationdc',%currhash);
 5530:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 5531:         $datatable .= '<tr'.$css_class.'><td>';
 5532:         if ($numdc > 1) {
 5533:             $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)');
 5534:         } else {
 5535:             $datatable .=  &mt('Course creation processed as: ');
 5536:         }
 5537:         $datatable .= '</td><td class="LC_left_item">'.$dctable.'</td></tr>';
 5538:         $itemcount ++;
 5539:     }
 5540:     if (ref($rowtotal)) {
 5541:         $$rowtotal += $itemcount;
 5542:     }
 5543:     return $datatable;
 5544: }
 5545: 
 5546: sub print_passwords {
 5547:     my ($position,$dom,$confname,$settings,$rowtotal) = @_;
 5548:     my ($datatable,$css_class);
 5549:     my $itemcount = 0;
 5550:     my %titles = &Apache::lonlocal::texthash (
 5551:         captcha        => '"Forgot Password" CAPTCHA validation',
 5552:         link           => 'Reset link expiration (hours)',
 5553:         case           => 'Case-sensitive usernames/e-mail',
 5554:         prelink        => 'Information required (form 1)',
 5555:         postlink       => 'Information required (form 2)',
 5556:         emailsrc       => 'LON-CAPA e-mail address type(s)',
 5557:         customtext     => 'Domain specific text (HTML)',
 5558:         intauth_cost   => 'Encryption cost for bcrypt (positive integer)',
 5559:         intauth_check  => 'Check bcrypt cost if authenticated',
 5560:         intauth_switch => 'Existing crypt-based switched to bcrypt on authentication',
 5561:         permanent      => 'Permanent e-mail address',
 5562:         critical       => 'Critical notification address',
 5563:         notify         => 'Notification address',
 5564:         min            => 'Minimum password length',
 5565:         max            => 'Maximum password length',
 5566:         chars          => 'Required characters',
 5567:         numsaved       => 'Number of previous passwords to save and disallow reuse',
 5568:     );
 5569:     if ($position eq 'top') {
 5570:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 5571:         my $shownlinklife = 2;
 5572:         my $prelink = 'both';
 5573:         my (%casesens,%postlink,%emailsrc,$nostdtext,$customurl);
 5574:         if (ref($settings) eq 'HASH') {
 5575:             if ($settings->{resetlink} =~ /^\d+(|\.\d*)$/) {
 5576:                 $shownlinklife = $settings->{resetlink};
 5577:             }
 5578:             if (ref($settings->{resetcase}) eq 'ARRAY') {
 5579:                 map { $casesens{$_} = 1; } (@{$settings->{resetcase}});
 5580:             }
 5581:             if ($settings->{resetprelink} =~ /^(both|either)$/) {
 5582:                 $prelink = $settings->{resetprelink};
 5583:             }
 5584:             if (ref($settings->{resetpostlink}) eq 'HASH') {
 5585:                 %postlink = %{$settings->{resetpostlink}};
 5586:             }
 5587:             if (ref($settings->{resetemail}) eq 'ARRAY') {
 5588:                 map { $emailsrc{$_} = 1; } (@{$settings->{resetemail}});
 5589:             }
 5590:             if ($settings->{resetremove}) {
 5591:                 $nostdtext = 1;
 5592:             }
 5593:             if ($settings->{resetcustom}) {
 5594:                 $customurl = $settings->{resetcustom};
 5595:             }
 5596:         } else {
 5597:             if (ref($types) eq 'ARRAY') {
 5598:                 foreach my $item (@{$types}) {
 5599:                     $casesens{$item} = 1;
 5600:                     $postlink{$item} = ['username','email'];
 5601:                 }
 5602:             }
 5603:             $casesens{'default'} = 1;
 5604:             $postlink{'default'} = ['username','email'];
 5605:             $prelink = 'both';
 5606:             %emailsrc = (
 5607:                           permanent => 1,
 5608:                           critical  => 1,
 5609:                           notify    => 1,
 5610:             );
 5611:         }
 5612:         $datatable = &captcha_choice('passwords',$settings,$$rowtotal);
 5613:         $itemcount ++;
 5614:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5615:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'link'}.'</td>'.
 5616:                       '<td class="LC_left_item">'.
 5617:                       '<input type="textbox" value="'.$shownlinklife.'" '.
 5618:                       'name="passwords_link" size="3" /></td></tr>';
 5619:         $itemcount ++;
 5620:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5621:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'case'}.'</td>'.
 5622:                       '<td class="LC_left_item">';
 5623:         if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 5624:             foreach my $item (@{$types}) {
 5625:                 my $checkedcase;
 5626:                 if ($casesens{$item}) {
 5627:                     $checkedcase = ' checked="checked"';
 5628:                 }
 5629:                 $datatable .= '<span class="LC_nobreak"><label>'.
 5630:                               '<input type="checkbox" name="passwords_case_sensitive" value="'.
 5631:                               $item.'"'.$checkedcase.' />'.$usertypes->{$item}.'</label>'.
 5632:                               '</span>&nbsp;&nbsp; ';
 5633:             }
 5634:         }
 5635:         my $checkedcase;
 5636:         if ($casesens{'default'}) {
 5637:             $checkedcase = ' checked="checked"';
 5638:         }
 5639:         $datatable .= '<span class="LC_nobreak"><label><input type="checkbox" '.
 5640:                       'name="passwords_case_sensitive" value="default"'.$checkedcase.' />'.
 5641:                       $othertitle.'</label></span></td>';
 5642:         $itemcount ++;
 5643:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5644:         my %checkedpre = (
 5645:                              both => ' checked="checked"',
 5646:                              either => '',
 5647:                          );
 5648:         if ($prelink eq 'either') {
 5649:             $checkedpre{either} = ' checked="checked"';
 5650:             $checkedpre{both} = '';
 5651:         }
 5652:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'prelink'}.'</td>'.
 5653:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 5654:                       '<label><input type="radio" name="passwords_prelink" value="both"'.$checkedpre{'both'}.' />'.
 5655:                       &mt('Both username and e-mail address').'</label></span>&nbsp;&nbsp; '.
 5656:                       '<span class="LC_nobreak"><label>'.
 5657:                       '<input type="radio" name="passwords_prelink" value="either"'.$checkedpre{'either'}.' />'.
 5658:                       &mt('Either username or e-mail address').'</label></span></td></tr>';
 5659:         $itemcount ++;
 5660:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5661:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'postlink'}.'</td>'.
 5662:                       '<td class="LC_left_item">';
 5663:         my %postlinked;
 5664:         if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 5665:             foreach my $item (@{$types}) {
 5666:                 undef(%postlinked);
 5667:                 $datatable .= '<fieldset style="display: inline-block;">'.
 5668:                               '<legend>'.$usertypes->{$item}.'</legend>';
 5669:                 if (ref($postlink{$item}) eq 'ARRAY') {
 5670:                     map { $postlinked{$_} = 1; } (@{$postlink{$item}});
 5671:                 }
 5672:                 foreach my $field ('email','username') {
 5673:                     my $checked;
 5674:                     if ($postlinked{$field}) {
 5675:                         $checked = ' checked="checked"';
 5676:                     }
 5677:                     $datatable .= '<span class="LC_nobreak"><label>'.
 5678:                                   '<input type="checkbox" name="passwords_postlink_'.$item.'" value="'.
 5679:                                   $field.'"'.$checked.' />'.$field.'</label>'.
 5680:                                   '<span>&nbsp;&nbsp; ';
 5681:                 }
 5682:                 $datatable .= '</fieldset>';
 5683:             }
 5684:         }
 5685:         if (ref($postlink{'default'}) eq 'ARRAY') {
 5686:             map { $postlinked{$_} = 1; } (@{$postlink{'default'}});
 5687:         }
 5688:         $datatable .= '<fieldset style="display: inline-block;">'.
 5689:                       '<legend>'.$othertitle.'</legend>';
 5690:         foreach my $field ('email','username') {
 5691:             my $checked;
 5692:             if ($postlinked{$field}) {
 5693:                 $checked = ' checked="checked"';
 5694:             }
 5695:             $datatable .= '<span class="LC_nobreak"><label>'.
 5696:                           '<input type="checkbox" name="passwords_postlink_default" value="'.
 5697:                           $field.'"'.$checked.' />'.$field.'</label>'.
 5698:                           '<span>&nbsp;&nbsp; ';
 5699:         }
 5700:         $datatable .= '</fieldset></td></tr>';
 5701:         $itemcount ++;
 5702:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5703:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'emailsrc'}.'</td>'.
 5704:                       '<td class="LC_left_item">';
 5705:         foreach my $type ('permanent','critical','notify') {
 5706:             my $checkedemail;
 5707:             if ($emailsrc{$type}) {
 5708:                 $checkedemail = ' checked="checked"';
 5709:             }
 5710:             $datatable .= '<span class="LC_nobreak"><label>'.
 5711:                           '<input type="checkbox" name="passwords_emailsrc" value="'.
 5712:                           $type.'"'.$checkedemail.' />'.$titles{$type}.'</label>'.
 5713:                           '<span>&nbsp;&nbsp; ';
 5714:         }
 5715:         $datatable .= '</td></tr>';
 5716:         $itemcount ++;
 5717:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5718:         my $switchserver = &check_switchserver($dom,$confname);
 5719:         my ($showstd,$noshowstd);
 5720:         if ($nostdtext) {
 5721:             $noshowstd = ' checked="checked"';
 5722:         } else {
 5723:             $showstd = ' checked="checked"';
 5724:         }
 5725:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'customtext'}.'</td>'.
 5726:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 5727:                       &mt('Retain standard text:').
 5728:                       '<label><input type="radio" name="passwords_stdtext" value="1"'.$showstd.' />'.
 5729:                       &mt('Yes').'</label>'.'&nbsp;'.
 5730:                       '<label><input type="radio" name="passwords_stdtext" value="0"'.$noshowstd.' />'.
 5731:                       &mt('No').'</label></span><br />'.
 5732:                       '<span class="LC_fontsize_small">'.
 5733:                       &mt('(If you use the same account ...  reset a password from this page.)').'</span><br /><br />'.
 5734:                       &mt('Include custom text:');
 5735:         if ($customurl) {
 5736:             my $link =  &Apache::loncommon::modal_link($customurl,&mt('custom text'),600,500,
 5737:                                                        undef,undef,undef,undef,'background-color:#ffffff');
 5738:             $datatable .= '<span class="LC_nobreak">&nbsp;'.$link.
 5739:                           '<label><input type="checkbox" name="passwords_custom_del"'.
 5740:                           ' value="1" />'.&mt('Delete?').'</label></span>'.
 5741:                           ' <span class="LC_nobreak">&nbsp;'.&mt('Replace:').'</span>';
 5742:         }
 5743:         if ($switchserver) {
 5744:             $datatable .= '<span class="LC_nobreak">&nbsp;'.&mt('Upload to library server: [_1]',$switchserver).'</span>';
 5745:         } else {
 5746:             $datatable .='<span class="LC_nobreak">&nbsp;'.
 5747:                          '<input type="file" name="passwords_customfile" /></span>';
 5748:         }
 5749:         $datatable .= '</td></tr>';
 5750:     } elsif ($position eq 'middle') {
 5751:         my %domconf = &Apache::lonnet::get_dom('configuration',['defaults'],$dom);
 5752:         my @items = ('intauth_cost','intauth_check','intauth_switch');
 5753:         my %defaults;
 5754:         if (ref($domconf{'defaults'}) eq 'HASH') {
 5755:             %defaults = %{$domconf{'defaults'}};
 5756:             if ($defaults{'intauth_cost'} !~ /^\d+$/) {
 5757:                 $defaults{'intauth_cost'} = 10;
 5758:             }
 5759:             if ($defaults{'intauth_check'} !~ /^(0|1|2)$/) {
 5760:                 $defaults{'intauth_check'} = 0;
 5761:             }
 5762:             if ($defaults{'intauth_switch'} !~ /^(0|1|2)$/) {
 5763:                 $defaults{'intauth_switch'} = 0;
 5764:             }
 5765:         } else {
 5766:             %defaults = (
 5767:                           'intauth_cost'   => 10,
 5768:                           'intauth_check'  => 0,
 5769:                           'intauth_switch' => 0,
 5770:                         );
 5771:         }
 5772:         foreach my $item (@items) {
 5773:             if ($itemcount%2) {
 5774:                 $css_class = '';
 5775:             } else {
 5776:                 $css_class = ' class="LC_odd_row" ';
 5777:             }
 5778:             $datatable .= '<tr'.$css_class.'>'.
 5779:                           '<td><span class="LC_nobreak">'.$titles{$item}.
 5780:                           '</span></td><td class="LC_left_item" colspan="3">';
 5781:             if ($item eq 'intauth_switch') {
 5782:                 my @options = (0,1,2);
 5783:                 my %optiondesc = &Apache::lonlocal::texthash (
 5784:                                    0 => 'No',
 5785:                                    1 => 'Yes',
 5786:                                    2 => 'Yes, and copy existing passwd file to passwd.bak file',
 5787:                                  );
 5788:                 $datatable .= '<table width="100%">';
 5789:                 foreach my $option (@options) {
 5790:                     my $checked = ' ';
 5791:                     if ($defaults{$item} eq $option) {
 5792:                         $checked = ' checked="checked"';
 5793:                     }
 5794:                     $datatable .= '<tr><td class="LC_left_item"><span class="LC_nobreak">'.
 5795:                                   '<label><input type="radio" name="'.$item.
 5796:                                   '" value="'.$option.'"'.$checked.' />'.
 5797:                                   $optiondesc{$option}.'</label></span></td></tr>';
 5798:                 }
 5799:                 $datatable .= '</table>';
 5800:             } elsif ($item eq 'intauth_check') {
 5801:                 my @options = (0,1,2);
 5802:                 my %optiondesc = &Apache::lonlocal::texthash (
 5803:                                    0 => 'No',
 5804:                                    1 => 'Yes, allow login then update passwd file using default cost (if higher)',
 5805:                                    2 => 'Yes, disallow login if stored cost is less than domain default',
 5806:                                  );
 5807:                 $datatable .= '<table width="100%">';
 5808:                 foreach my $option (@options) {
 5809:                     my $checked = ' ';
 5810:                     my $onclick;
 5811:                     if ($defaults{$item} eq $option) {
 5812:                         $checked = ' checked="checked"';
 5813:                     }
 5814:                     if ($option == 2) {
 5815:                         $onclick = ' onclick="javascript:warnIntAuth(this);"';
 5816:                     }
 5817:                     $datatable .= '<tr><td class="LC_left_item"><span class="LC_nobreak">'.
 5818:                                   '<label><input type="radio" name="'.$item.
 5819:                                   '" value="'.$option.'"'.$checked.$onclick.' />'.
 5820:                                   $optiondesc{$option}.'</label></span></td></tr>';
 5821:                 }
 5822:                 $datatable .= '</table>';
 5823:             } else {
 5824:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
 5825:                               $defaults{$item}.'" size="3" onblur="javascript:warnIntAuth(this);" />';
 5826:             }
 5827:             $datatable .= '</td></tr>';
 5828:             $itemcount ++;
 5829:         }
 5830:     } elsif ($position eq 'lower') {
 5831:         my ($min,$max,%chars,$numsaved);
 5832:         $min = $Apache::lonnet::passwdmin;
 5833:         if (ref($settings) eq 'HASH') {
 5834:             if ($settings->{min}) {
 5835:                 $min = $settings->{min};
 5836:             }
 5837:             if ($settings->{max}) {
 5838:                 $max = $settings->{max};
 5839:             }
 5840:             if (ref($settings->{chars}) eq 'ARRAY') {
 5841:                 map { $chars{$_} = 1; } (@{$settings->{chars}});
 5842:             }
 5843:             if ($settings->{numsaved}) {
 5844:                 $numsaved = $settings->{numsaved};
 5845:             }
 5846:         }
 5847:         my %rulenames = &Apache::lonlocal::texthash(
 5848:                                                      uc => 'At least one upper case letter',
 5849:                                                      lc => 'At least one lower case letter',
 5850:                                                      num => 'At least one number',
 5851:                                                      spec => 'At least one non-alphanumeric',
 5852:                                                    );
 5853:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5854:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'min'}.'</td>'.
 5855:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 5856:                       '<input type="text" name="passwords_min" value="'.$min.'" size="3" '.
 5857:                       'onblur="javascript:warnIntPass(this);" />'.
 5858:                       '<span class="LC_fontsize_small"> '.&mt('(Enter an integer: 7 or larger)').'</span>'.
 5859:                       '</span></td></tr>';
 5860:         $itemcount ++;
 5861:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5862:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'max'}.'</td>'.
 5863:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 5864:                       '<input type="text" name="passwords_max" value="'.$max.'" size="3" '.
 5865:                       'onblur="javascript:warnIntPass(this);" />'.
 5866:                       '<span class="LC_fontsize_small"> '.&mt('(Leave blank for no maximum)').'</span>'.
 5867:                       '</span></td></tr>';
 5868:         $itemcount ++;
 5869:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5870:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'chars'}.'<br />'.
 5871:                       '<span class="LC_nobreak LC_fontsize_small">'.&mt('(Leave unchecked if not required)').
 5872:                       '</span></td>';
 5873:         my $numinrow = 2;
 5874:         my @possrules = ('uc','lc','num','spec');
 5875:         $datatable .= '<td class="LC_left_item"><table>';
 5876:         for (my $i=0; $i<@possrules; $i++) {
 5877:             my ($rem,$checked);
 5878:             if ($chars{$possrules[$i]}) {
 5879:                 $checked = ' checked="checked"';
 5880:             }
 5881:             $rem = $i%($numinrow);
 5882:             if ($rem == 0) {
 5883:                 if ($i > 0) {
 5884:                     $datatable .= '</tr>';
 5885:                 }
 5886:                 $datatable .= '<tr>';
 5887:             }
 5888:             $datatable .= '<td><span class="LC_nobreak"><label>'.
 5889:                           '<input type="checkbox" name="passwords_chars" value="'.$possrules[$i].'"'.$checked.' />'.
 5890:                           $rulenames{$possrules[$i]}.'</label></span></td>';
 5891:         }
 5892:         my $rem = @possrules%($numinrow);
 5893:         my $colsleft = $numinrow - $rem;
 5894:         if ($colsleft > 1 ) {
 5895:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 5896:                           '&nbsp;</td>';
 5897:         } elsif ($colsleft == 1) {
 5898:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 5899:         }
 5900:         $datatable .='</table></td></tr>';
 5901:         $itemcount ++;
 5902:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5903:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'numsaved'}.'</td>'.
 5904:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 5905:                       '<input type="text" name="passwords_numsaved" value="'.$numsaved.'" size="3" '.
 5906:                       'onblur="javascript:warnIntPass(this);" />'.
 5907:                       '<span class="LC_fontsize_small"> '.&mt('(Leave blank to not save previous passwords)').'</span>'.
 5908:                       '</span></td></tr>';
 5909:     } else {
 5910:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 5911:         my %ownerchg = (
 5912:                           by  => {},
 5913:                           for => {},
 5914:                        );
 5915:         my %ownertitles = &Apache::lonlocal::texthash (
 5916:                             by  => 'Course owner status(es) allowed',
 5917:                             for => 'Student status(es) allowed',
 5918:                           );
 5919:         if (ref($settings) eq 'HASH') {
 5920:             if (ref($settings->{crsownerchg}) eq 'HASH') {
 5921:                 if (ref($settings->{crsownerchg}{'by'}) eq 'ARRAY') {
 5922:                     map { $ownerchg{by}{$_} = 1; } (@{$settings->{crsownerchg}{'by'}});
 5923:                 }
 5924:                 if (ref($settings->{crsownerchg}{'for'}) eq 'ARRAY') {
 5925:                     map { $ownerchg{for}{$_} = 1; } (@{$settings->{crsownerchg}{'for'}});
 5926:                 }
 5927:             }
 5928:         }
 5929:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5930:         $datatable .= '<tr '.$css_class.'>'.
 5931:                       '<td>'.
 5932:                       &mt('Requirements').'<ul>'.
 5933:                       '<li>'.&mt("Course 'type' is not a Community").'</li>'.
 5934:                       '<li>'.&mt('User is Course Coordinator and also course owner').'</li>'.
 5935:                       '<li>'.&mt("Student's only active roles are student role(s) in course(s) owned by this user").'</li>'.
 5936:                       '<li>'.&mt('User, course, and student share same domain').'</li>'.
 5937:                       '</ul>'.
 5938:                       '</td>'.
 5939:                       '<td class="LC_left_item">';
 5940:         foreach my $item ('by','for') {
 5941:             $datatable .= '<fieldset style="display: inline-block;">'.
 5942:                           '<legend>'.$ownertitles{$item}.'</legend>';
 5943:             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 5944:                 foreach my $type (@{$types}) {
 5945:                     my $checked;
 5946:                     if ($ownerchg{$item}{$type}) {
 5947:                         $checked = ' checked="checked"';
 5948:                     }
 5949:                     $datatable .= '<span class="LC_nobreak"><label>'.
 5950:                                   '<input type="checkbox" name="passwords_crsowner_'.$item.'" value="'.
 5951:                                   $type.'"'.$checked.' />'.$usertypes->{$type}.'</label>'.
 5952:                                   '</span>&nbsp;&nbsp; ';
 5953:                 }
 5954:             }
 5955:             my $checked;
 5956:             if ($ownerchg{$item}{'default'}) {
 5957:                 $checked = ' checked="checked"';
 5958:             }
 5959:             $datatable .= '<span class="LC_nobreak"><label><input type="checkbox" '.
 5960:                           'name="passwords_crsowner_'.$item.'" value="default"'.$checked.' />'.
 5961:                           $othertitle.'</label></span></fieldset>';
 5962:         }
 5963:         $datatable .= '</td></tr>';
 5964:     }
 5965:     return $datatable;
 5966: }
 5967: 
 5968: sub print_wafproxy {
 5969:     my ($position,$dom,$settings,$rowtotal) = @_;
 5970:     my $css_class;
 5971:     my $itemcount = 0;
 5972:     my $datatable;
 5973:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 5974:     my (%othercontrol,%otherdoms,%aliases,%saml,%values,$setdom,$showdom);
 5975:     my %lt = &wafproxy_titles();
 5976:     foreach my $server (sort(keys(%servers))) {
 5977:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
 5978:         next if ($serverhome eq '');
 5979:         my $serverdom;
 5980:         if ($serverhome ne $server) {
 5981:             $serverdom = &Apache::lonnet::host_domain($serverhome);
 5982:             if (($serverdom ne '') && (&Apache::lonnet::domain($serverdom) ne '')) {
 5983:                 $othercontrol{$server} = $serverdom;
 5984:             }
 5985:         } else {
 5986:             $serverdom = &Apache::lonnet::host_domain($server);
 5987:             next if (($serverdom eq '') || (&Apache::lonnet::domain($serverdom) eq ''));
 5988:             if ($serverdom ne $dom) {
 5989:                 $othercontrol{$server} = $serverdom;
 5990:             } else {
 5991:                 $setdom = 1;
 5992:                 if (ref($settings) eq 'HASH') {
 5993:                     if (ref($settings->{'alias'}) eq 'HASH') {
 5994:                         $aliases{$dom} = $settings->{'alias'};
 5995:                         if ($aliases{$dom} ne '') {
 5996:                             $showdom = 1;
 5997:                         }
 5998:                     }
 5999:                     if (ref($settings->{'saml'}) eq 'HASH') {
 6000:                         $saml{$dom} = $settings->{'saml'};
 6001:                     }
 6002:                 }
 6003:             }
 6004:         }
 6005:     }
 6006:     if ($setdom) {
 6007:         %{$values{$dom}} = ();
 6008:         if (ref($settings) eq 'HASH') {
 6009:             foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext') {
 6010:                 $values{$dom}{$item} = $settings->{$item};
 6011:             }
 6012:         }
 6013:     }
 6014:     if (keys(%othercontrol)) {
 6015:         %otherdoms = reverse(%othercontrol);
 6016:         foreach my $domain (keys(%otherdoms)) {
 6017:             %{$values{$domain}} = ();
 6018:             my %config = &Apache::lonnet::get_dom('configuration',['wafproxy'],$domain);
 6019:             if (ref($config{'wafproxy'}) eq 'HASH') {
 6020:                 $aliases{$domain} = $config{'wafproxy'}{'alias'};
 6021:                 if (exists($config{'wafproxy'}{'saml'})) {
 6022:                     $saml{$domain} = $config{'wafproxy'}{'saml'};
 6023:                 }
 6024:                 foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext') {
 6025:                     $values{$domain}{$item} = $config{'wafproxy'}{$item};
 6026:                 }
 6027:             }
 6028:         }
 6029:     }
 6030:     if ($position eq 'top') {
 6031:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 6032:         my %aliasinfo;
 6033:         foreach my $server (sort(keys(%servers))) {
 6034:             $itemcount ++;
 6035:             my $dom_in_effect;
 6036:             my $aliasrows = '<tr>'.
 6037:                             '<td class="LC_left_item" style="vertical-align: baseline;">'.
 6038:                             &mt('Hostname').':&nbsp;'.
 6039:                             '<i>'.&Apache::lonnet::hostname($server).'</i></td><td>&nbsp;</td>';
 6040:             if ($othercontrol{$server}) {
 6041:                 $dom_in_effect = $othercontrol{$server};
 6042:                 my ($current,$forsaml);
 6043:                 if (ref($aliases{$dom_in_effect}) eq 'HASH') {
 6044:                     $current = $aliases{$dom_in_effect}{$server};
 6045:                 }
 6046:                 if (ref($saml{$dom_in_effect}) eq 'HASH') {
 6047:                     if ($saml{$dom_in_effect}{$server}) {
 6048:                         $forsaml = 1;
 6049:                     }
 6050:                 }
 6051:                 $aliasrows .= '<td class="LC_left_item" style="vertical-align: baseline;">'.
 6052:                               &mt('Alias').':&nbsp';
 6053:                 if ($current) {
 6054:                     $aliasrows .= $current;
 6055:                     if ($forsaml) {
 6056:                          $aliasrows .= '&nbsp;('.&mt('also for SSO Auth').')';
 6057:                     }
 6058:                 } else {
 6059:                     $aliasrows .= &mt('None');
 6060:                 }
 6061:                 $aliasrows .= '&nbsp;<span class="LC_small">('.
 6062:                               &mt('controlled by domain: [_1]',
 6063:                                   '<b>'.$dom_in_effect.'</b>').')</span></td>';
 6064:             } else {
 6065:                 $dom_in_effect = $dom;
 6066:                 my ($current,$samlon,$samloff);
 6067:                 $samloff = ' checked="checked"';
 6068:                 if (ref($aliases{$dom}) eq 'HASH') {
 6069:                     if ($aliases{$dom}{$server}) {
 6070:                         $current = $aliases{$dom}{$server};
 6071:                     }
 6072:                 }
 6073:                 if (ref($saml{$dom}) eq 'HASH') {
 6074:                     if ($saml{$dom}{$server}) {
 6075:                         $samlon = $samloff;
 6076:                         undef($samloff);
 6077:                     }
 6078:                 }
 6079:                 $aliasrows .= '<td class="LC_left_item" style="vertical-align: baseline;">'.
 6080:                               &mt('Alias').':&nbsp;'.
 6081:                               '<input type="text" name="wafproxy_alias_'.$server.'" '.
 6082:                               'value="'.$current.'" size="30" />'.
 6083:                               ('&nbsp;'x2).'<span class="LC_nobreak">'.
 6084:                               &mt('Alias used for SSO Auth').':&nbsp;<label>'.
 6085:                               '<input type="radio" value="0"'.$samloff.' name="wafproxy_alias_saml_'.$server.'" />'.
 6086:                               &mt('No').'</label>&nbsp;<label>'.
 6087:                               '<input type="radio" value="1"'.$samlon.' name="wafproxy_alias_saml_'.$server.'" />'.
 6088:                               &mt('Yes').'</label></span>'.
 6089:                               '</td>';
 6090:             }
 6091:             $aliasrows .= '</tr>';
 6092:             $aliasinfo{$dom_in_effect} .= $aliasrows;
 6093:         }
 6094:         if ($aliasinfo{$dom}) {
 6095:             my ($onclick,$wafon,$wafoff,$showtable);
 6096:             $onclick = ' onclick="javascript:toggleWAF();"';
 6097:             $wafoff = ' checked="checked"';
 6098:             $showtable = ' style="display:none";';
 6099:             if ($showdom) {
 6100:                 $wafon = $wafoff;
 6101:                 $wafoff = '';
 6102:                 $showtable = ' style="display:inline;"';
 6103:             }
 6104:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6105:             $datatable = '<tr'.$css_class.'>'.
 6106:                          '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'<br />'.
 6107:                          '<span class="LC_nobreak">'.&mt('WAF in use?').'&nbsp;<label>'.
 6108:                          '<input type="radio" name="wafproxy_'.$dom.'" value="1"'.$wafon.$onclick.' />'.
 6109:                          &mt('Yes').'</label>'.('&nbsp;'x2).'<label>'.
 6110:                          '<input type="radio" name="wafproxy_'.$dom.'" value="0"'.$wafoff.$onclick.' />'.
 6111:                          &mt('No').'</label></span></td>'.
 6112:                          '<td class="LC_left_item">'.
 6113:                          '<table id="wafproxy_table"'.$showtable.'>'.$aliasinfo{$dom}.
 6114:                          '</table></td></tr>';
 6115:             $itemcount++;
 6116:         }
 6117:         if (keys(%otherdoms)) {
 6118:             foreach my $key (sort(keys(%otherdoms))) {
 6119:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6120:                 $datatable .= '<tr'.$css_class.'>'.
 6121:                               '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$key.'</b>').'</td>'.
 6122:                               '<td class="LC_left_item"><table>'.$aliasinfo{$key}.
 6123:                               '</table></td></tr>';
 6124:                 $itemcount++;
 6125:             }
 6126:         }
 6127:     } else {
 6128:         my %ip_methods = &remoteip_methods();
 6129:         if ($setdom) {
 6130:             $itemcount ++;
 6131:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6132:             my ($nowafstyle,$wafstyle,$curr_remotip,$currwafdisplay,$vpndircheck,$vpnaliascheck,
 6133:                 $currwafvpn,$wafrangestyle,$alltossl,$ssltossl);
 6134:             $wafstyle = ' style="display:none;"';
 6135:             $nowafstyle = ' style="display:table-row;"';
 6136:             $currwafdisplay = ' style="display: none"';
 6137:             $wafrangestyle = ' style="display: none"';
 6138:             $curr_remotip = 'n';
 6139:             $ssltossl = ' checked="checked"';
 6140:             if ($showdom) {
 6141:                 $wafstyle = ' style="display:table-row;"';
 6142:                 $nowafstyle =  ' style="display:none;"';
 6143:                 if (keys(%{$values{$dom}})) {
 6144:                     if ($values{$dom}{remoteip} =~ /^[nmh]$/) {
 6145:                         $curr_remotip = $values{$dom}{remoteip};
 6146:                     }
 6147:                     if ($curr_remotip eq 'h') {
 6148:                         $currwafdisplay = ' style="display:table-row"';
 6149:                         $wafrangestyle = ' style="display:inline-block;"';
 6150:                     }
 6151:                     if ($values{$dom}{'sslopt'}) {
 6152:                         $alltossl = ' checked="checked"';
 6153:                         $ssltossl = '';
 6154:                     }
 6155:                 }
 6156:                 if (($values{$dom}{'vpnint'} ne '') || ($values{$dom}{'vpnext'} ne '')) {
 6157:                     $vpndircheck = ' checked="checked"';
 6158:                     $currwafvpn = ' style="display:table-row;"';
 6159:                     $wafrangestyle = ' style="display:inline-block;"';
 6160:                 } else {
 6161:                     $vpnaliascheck = ' checked="checked"';
 6162:                     $currwafvpn = ' style="display:none;"';
 6163:                 }
 6164:             }
 6165:             $datatable .= '<tr'.$css_class.' id="nowafproxyrow_'.$dom.'"'.$wafstyle.'>'.
 6166:                           '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'</td>'.
 6167:                           '<td class="LC_right_item">'.&mt('WAF not in use, nothing to set').'</td>'.
 6168:                           '</tr>'.
 6169:                           '<tr'.$css_class.' id="wafproxyrow_'.$dom.'"'.$wafstyle.'>'.
 6170:                           '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'<br /><br />'.
 6171:                           '<div id="wafproxyranges_'.$dom.'">'.&mt('Format for comma separated IP ranges').':<br />'.
 6172:                           &mt('A.B.C.D/N or A.B.C.D-E.F.G.H').'<br />'.
 6173:                           &mt('Range(s) stored in CIDR notation').'</div></td>'.
 6174:                           '<td class="LC_left_item"><table>'.
 6175:                           '<tr>'.
 6176:                           '<td valign="top">'.$lt{'remoteip'}.':&nbsp;'.
 6177:                           '<select name="wafproxy_remoteip" id="wafproxy_remoteip" onchange="javascript:updateWAF();">';
 6178:             foreach my $option ('m','h','n') {
 6179:                 my $sel;
 6180:                 if ($option eq $curr_remotip) {
 6181:                    $sel = ' selected="selected"';
 6182:                 }
 6183:                 $datatable .= '<option value="'.$option.'"'.$sel.'>'.
 6184:                               $ip_methods{$option}.'</option>';
 6185:             }
 6186:             $datatable .= '</select></td></tr>'."\n".
 6187:                           '<tr id="wafproxy_header"'.$currwafdisplay.'><td>'.
 6188:                           $lt{'ipheader'}.':&nbsp;'.
 6189:                           '<input type="text" value="'.$values{$dom}{'ipheader'}.'" '.
 6190:                           'name="wafproxy_ipheader" />'.
 6191:                           '</td></tr>'."\n".
 6192:                           '<tr id="wafproxy_trust"'.$currwafdisplay.'><td>'.
 6193:                           $lt{'trusted'}.':<br />'.
 6194:                           '<textarea name="wafproxy_trusted" rows="3" cols="80">'.
 6195:                           $values{$dom}{'trusted'}.'</textarea>'.
 6196:                           '</td></tr>'."\n".
 6197:                           '<tr><td><hr /></td></tr>'."\n".
 6198:                           '<tr>'.
 6199:                           '<td valign="top">'.$lt{'vpnaccess'}.':<br /><span class="LC_nobreak">'.
 6200:                           '<label><input type="radio" name="wafproxy_vpnaccess"'.$vpndircheck.' value="1" onclick="javascript:checkWAF();" />'.
 6201:                           $lt{'vpndirect'}.'</label>'.('&nbsp;'x2).
 6202:                           '<label><input type="radio" name="wafproxy_vpnaccess"'.$vpnaliascheck.' value="0" onclick="javascript:checkWAF();" />'.
 6203:                           $lt{'vpnaliased'}.'</label></span></td></tr>';
 6204:             foreach my $item ('vpnint','vpnext') {
 6205:                 $datatable .= '<tr id="wafproxy_show_'.$item.'"'.$currwafvpn.'>'.
 6206:                               '<td valign="top">'.$lt{$item}.':<br />'.
 6207:                               '<textarea name="wafproxy_'.$item.'" rows="3" cols="80">'.
 6208:                               $values{$dom}{$item}.'</textarea>'.
 6209:                               '</td></tr>'."\n";
 6210:             }
 6211:             $datatable .= '<tr><td><hr /></td></tr>'."\n".
 6212:                           '<tr>'.
 6213:                           '<td valign="top">'.$lt{'sslopt'}.':<br /><span class="LC_nobreak">'.
 6214:                           '<label><input type="radio" name="wafproxy_sslopt"'.$alltossl.' value="1" />'.
 6215:                           $lt{'alltossl'}.'</label>'.('&nbsp;'x2).
 6216:                           '<label><input type="radio" name="wafproxy_sslopt"'.$ssltossl.' value="0" />'.
 6217:                           $lt{'ssltossl'}.'</label></span></td></tr>'."\n".
 6218:                           '</table></td></tr>';
 6219:         }
 6220:         if (keys(%otherdoms)) {
 6221:             foreach my $domain (sort(keys(%otherdoms))) {
 6222:                 $itemcount ++;
 6223:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6224:                 $datatable .= '<tr'.$css_class.'>'.
 6225:                               '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$domain.'</b>').'</td>'.
 6226:                               '<td class="LC_left_item"><table>';
 6227:                 foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
 6228:                     my $showval = &mt('None');
 6229:                     if ($item eq 'ssl') {
 6230:                         $showval = $lt{'ssltossl'};
 6231:                     }
 6232:                     if ($values{$domain}{$item}) {
 6233:                         $showval = $values{$domain}{$item};
 6234:                         if ($item eq 'ssl') {
 6235:                             $showval = $lt{'alltossl'};
 6236:                         } elsif ($item eq 'remoteip') {
 6237:                             $showval = $ip_methods{$values{$domain}{$item}};
 6238:                         }
 6239:                     }
 6240:                     $datatable .= '<tr>'.
 6241:                                   '<td>'.$lt{$item}.':&nbsp;'.$showval.'</td></tr>';
 6242:                 }
 6243:                 $datatable .= '</table></td></tr>';
 6244:             }
 6245:         }
 6246:     }
 6247:     $$rowtotal += $itemcount;
 6248:     return $datatable;
 6249: }
 6250: 
 6251: sub wafproxy_titles {
 6252:     return &Apache::lonlocal::texthash(
 6253:                remoteip   => "Method for determining user's IP",
 6254:                ipheader   => 'Request header containing remote IP',
 6255:                trusted    => 'Trusted IP range(s)',
 6256:                vpnaccess  => 'Access from institutional VPN',
 6257:                vpndirect  => 'via regular hostname (no WAF)',
 6258:                vpnaliased => 'via aliased hostname (WAF)',
 6259:                vpnint     => 'Internal IP Range(s) for VPN sessions',
 6260:                vpnext     => 'IP Range(s) for backend WAF connections',
 6261:                sslopt     => 'Forwarding http/https',
 6262:                alltossl   => 'WAF forwards both http and https requests to https',
 6263:                ssltossl   => 'WAF forwards http requests to http and https to https',
 6264:            );
 6265: }
 6266: 
 6267: sub remoteip_methods {
 6268:     return &Apache::lonlocal::texthash(
 6269:               m => 'Use Apache mod_remoteip',
 6270:               h => 'Use headers parsed by LON-CAPA',
 6271:               n => 'Not in use',
 6272:            );
 6273: }
 6274: 
 6275: sub print_usersessions {
 6276:     my ($position,$dom,$settings,$rowtotal) = @_;
 6277:     my ($css_class,$datatable,%checked,%choices);
 6278:     my (%by_ip,%by_location,@intdoms);
 6279:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location);
 6280: 
 6281:     my @alldoms = &Apache::lonnet::all_domains();
 6282:     my %serverhomes = %Apache::lonnet::serverhomeIDs;
 6283:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 6284:     my %altids = &id_for_thisdom(%servers);
 6285:     my $itemcount = 1;
 6286:     if ($position eq 'top') {
 6287:         if (keys(%serverhomes) > 1) {
 6288:             my %spareid = &current_offloads_to($dom,$settings,\%servers);
 6289:             my ($curroffloadnow,$curroffloadoth);
 6290:             if (ref($settings) eq 'HASH') {
 6291:                 if (ref($settings->{'offloadnow'}) eq 'HASH') {
 6292:                     $curroffloadnow = $settings->{'offloadnow'};
 6293:                 }
 6294:                 if (ref($settings->{'offloadoth'}) eq 'HASH') {
 6295:                     $curroffloadoth = $settings->{'offloadoth'};
 6296:                 }
 6297:             }
 6298:             my $other_insts = scalar(keys(%by_location));
 6299:             $datatable .= &spares_row($dom,\%servers,\%spareid,\%serverhomes,\%altids,
 6300:                                       $other_insts,$curroffloadnow,$curroffloadoth,$rowtotal);
 6301:         } else {
 6302:             $datatable .= '<tr'.$css_class.'><td colspan="2">'.
 6303:                           &mt('Nothing to set here, as the cluster to which this domain belongs only contains one server.');
 6304:         }
 6305:     } else {
 6306:         if (keys(%by_location) == 0) {
 6307:             $datatable .= '<tr'.$css_class.'><td colspan="2">'.
 6308:                           &mt('Nothing to set here, as the cluster to which this domain belongs only contains one institution.');
 6309:         } else {
 6310:             my %lt = &usersession_titles();
 6311:             my $numinrow = 5;
 6312:             my $prefix;
 6313:             my @types;
 6314:             if ($position eq 'bottom') {
 6315:                 $prefix = 'remote';
 6316:                 @types = ('version','excludedomain','includedomain');
 6317:             } else {
 6318:                 $prefix = 'hosted';
 6319:                 @types = ('excludedomain','includedomain');
 6320:             }
 6321:             my (%current,%checkedon,%checkedoff);
 6322:             my @lcversions = &Apache::lonnet::all_loncaparevs();
 6323:             my @locations = sort(keys(%by_location));
 6324:             foreach my $type (@types) {
 6325:                 $checkedon{$type} = '';
 6326:                 $checkedoff{$type} = ' checked="checked"';
 6327:             }
 6328:             if (ref($settings) eq 'HASH') {
 6329:                 if (ref($settings->{$prefix}) eq 'HASH') {
 6330:                     foreach my $key (keys(%{$settings->{$prefix}})) {
 6331:                         $current{$key} = $settings->{$prefix}{$key};
 6332:                         if ($key eq 'version') {
 6333:                             if ($current{$key} ne '') {
 6334:                                 $checkedon{$key} = ' checked="checked"';
 6335:                                 $checkedoff{$key} = '';
 6336:                             }
 6337:                         } elsif (ref($current{$key}) eq 'ARRAY') {
 6338:                             $checkedon{$key} = ' checked="checked"';
 6339:                             $checkedoff{$key} = '';
 6340:                         }
 6341:                     }
 6342:                 }
 6343:             }
 6344:             foreach my $type (@types) {
 6345:                 next if ($type ne 'version' && !@locations);
 6346:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6347:                 $datatable .= '<tr'.$css_class.'>
 6348:                                <td><span class="LC_nobreak">'.$lt{$type}.'</span><br />
 6349:                                <span class="LC_nobreak">&nbsp;
 6350:                                <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedoff{$type}.' value="0" />'.&mt('Not in use').'</label>&nbsp;
 6351:                                <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedon{$type}.' value="1" />'.&mt('In use').'</label></span></td><td>';
 6352:                 if ($type eq 'version') {
 6353:                     my $selector = '<select name="'.$prefix.'_version">';
 6354:                     foreach my $version (@lcversions) {
 6355:                         my $selected = '';
 6356:                         if ($current{'version'} eq $version) {
 6357:                             $selected = ' selected="selected"';
 6358:                         }
 6359:                         $selector .= ' <option value="'.$version.'"'.
 6360:                                      $selected.'>'.$version.'</option>';
 6361:                     }
 6362:                     $selector .= '</select> ';
 6363:                     $datatable .= &mt('remote server must be version: [_1] or later',$selector);
 6364:                 } else {
 6365:                     $datatable.= '<div><input type="button" value="'.&mt('check all').'" '.
 6366:                                  'onclick="javascript:checkAll(document.display.'.$prefix.'_'.$type.')"'.
 6367:                                  ' />'.('&nbsp;'x2).
 6368:                                  '<input type="button" value="'.&mt('uncheck all').'" '.
 6369:                                  'onclick="javascript:uncheckAll(document.display.'.$prefix.'_'.$type.')" />'.
 6370:                                  "\n".
 6371:                                  '</div><div><table>';
 6372:                     my $rem;
 6373:                     for (my $i=0; $i<@locations; $i++) {
 6374:                         my ($showloc,$value,$checkedtype);
 6375:                         if (ref($by_location{$locations[$i]}) eq 'ARRAY') {
 6376:                             my $ip = $by_location{$locations[$i]}->[0];
 6377:                             if (ref($by_ip{$ip}) eq 'ARRAY') {
 6378:                                  $value = join(':',@{$by_ip{$ip}});
 6379:                                 $showloc = join(', ',@{$by_ip{$ip}});
 6380:                                 if (ref($current{$type}) eq 'ARRAY') {
 6381:                                     foreach my $loc (@{$by_ip{$ip}}) {  
 6382:                                         if (grep(/^\Q$loc\E$/,@{$current{$type}})) {
 6383:                                             $checkedtype = ' checked="checked"';
 6384:                                             last;
 6385:                                         }
 6386:                                     }
 6387:                                 }
 6388:                             }
 6389:                         }
 6390:                         $rem = $i%($numinrow);
 6391:                         if ($rem == 0) {
 6392:                             if ($i > 0) {
 6393:                                 $datatable .= '</tr>';
 6394:                             }
 6395:                             $datatable .= '<tr>';
 6396:                         }
 6397:                         $datatable .= '<td class="LC_left_item">'.
 6398:                                       '<span class="LC_nobreak"><label>'.
 6399:                                       '<input type="checkbox" name="'.$prefix.'_'.$type.
 6400:                                       '" value="'.$value.'"'.$checkedtype.' />'.$showloc.
 6401:                                       '</label></span></td>';
 6402:                     }
 6403:                     $rem = @locations%($numinrow);
 6404:                     my $colsleft = $numinrow - $rem;
 6405:                     if ($colsleft > 1 ) {
 6406:                         $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 6407:                                       '&nbsp;</td>';
 6408:                     } elsif ($colsleft == 1) {
 6409:                         $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 6410:                     }
 6411:                     $datatable .= '</tr></table>';
 6412:                 }
 6413:                 $datatable .= '</td></tr>';
 6414:                 $itemcount ++;
 6415:             }
 6416:         }
 6417:     }
 6418:     $$rowtotal += $itemcount;
 6419:     return $datatable;
 6420: }
 6421: 
 6422: sub build_location_hashes {
 6423:     my ($intdoms,$by_ip,$by_location) = @_;
 6424:     return unless((ref($intdoms) eq 'ARRAY') && (ref($by_ip) eq 'HASH') &&
 6425:                   (ref($by_location) eq 'HASH')); 
 6426:     my %iphost = &Apache::lonnet::get_iphost();
 6427:     my $primary_id = &Apache::lonnet::domain($env{'request.role.domain'},'primary');
 6428:     my $primary_ip = &Apache::lonnet::get_host_ip($primary_id);
 6429:     if (ref($iphost{$primary_ip}) eq 'ARRAY') {
 6430:         foreach my $id (@{$iphost{$primary_ip}}) {
 6431:             my $intdom = &Apache::lonnet::internet_dom($id);
 6432:             unless(grep(/^\Q$intdom\E$/,@{$intdoms})) {
 6433:                 push(@{$intdoms},$intdom);
 6434:             }
 6435:         }
 6436:     }
 6437:     foreach my $ip (keys(%iphost)) {
 6438:         if (ref($iphost{$ip}) eq 'ARRAY') {
 6439:             foreach my $id (@{$iphost{$ip}}) {
 6440:                 my $location = &Apache::lonnet::internet_dom($id);
 6441:                 if ($location) {
 6442:                     next if (grep(/^\Q$location\E$/,@{$intdoms}));
 6443:                     if (ref($by_ip->{$ip}) eq 'ARRAY') {
 6444:                         unless(grep(/^\Q$location\E$/,@{$by_ip->{$ip}})) {
 6445:                             push(@{$by_ip->{$ip}},$location);
 6446:                         }
 6447:                     } else {
 6448:                         $by_ip->{$ip} = [$location];
 6449:                     }
 6450:                 }
 6451:             }
 6452:         }
 6453:     }
 6454:     foreach my $ip (sort(keys(%{$by_ip}))) {
 6455:         if (ref($by_ip->{$ip}) eq 'ARRAY') {
 6456:             @{$by_ip->{$ip}} = sort(@{$by_ip->{$ip}});
 6457:             my $first = $by_ip->{$ip}->[0];
 6458:             if (ref($by_location->{$first}) eq 'ARRAY') {
 6459:                 unless (grep(/^\Q$ip\E$/,@{$by_location->{$first}})) {
 6460:                     push(@{$by_location->{$first}},$ip);
 6461:                 }
 6462:             } else {
 6463:                 $by_location->{$first} = [$ip];
 6464:             }
 6465:         }
 6466:     }
 6467:     return;
 6468: }
 6469: 
 6470: sub current_offloads_to {
 6471:     my ($dom,$settings,$servers) = @_;
 6472:     my (%spareid,%otherdomconfigs);
 6473:     if (ref($servers) eq 'HASH') {
 6474:         foreach my $lonhost (sort(keys(%{$servers}))) {
 6475:             my $gotspares;
 6476:             if (ref($settings) eq 'HASH') {
 6477:                 if (ref($settings->{'spares'}) eq 'HASH') {
 6478:                     if (ref($settings->{'spares'}{$lonhost}) eq 'HASH') {
 6479:                         $spareid{$lonhost}{'primary'} = $settings->{'spares'}{$lonhost}{'primary'};
 6480:                         $spareid{$lonhost}{'default'} = $settings->{'spares'}{$lonhost}{'default'};
 6481:                         $gotspares = 1;
 6482:                     }
 6483:                 }
 6484:             }
 6485:             unless ($gotspares) {
 6486:                 my $gotspares;
 6487:                 my $serverhomeID =
 6488:                     &Apache::lonnet::get_server_homeID($servers->{$lonhost});
 6489:                 my $serverhomedom =
 6490:                     &Apache::lonnet::host_domain($serverhomeID);
 6491:                 if ($serverhomedom ne $dom) {
 6492:                     if (ref($otherdomconfigs{$serverhomedom} eq 'HASH')) {
 6493:                         if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 6494:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 6495:                                 $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 6496:                                 $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 6497:                                 $gotspares = 1;
 6498:                             }
 6499:                         }
 6500:                     } else {
 6501:                         $otherdomconfigs{$serverhomedom} =
 6502:                             &Apache::lonnet::get_dom('configuration',['usersessions'],$serverhomedom);
 6503:                         if (ref($otherdomconfigs{$serverhomedom}) eq 'HASH') {
 6504:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 6505:                                 if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 6506:                                     if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{$lonhost}) eq 'HASH') {
 6507:                                         $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 6508:                                         $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 6509:                                         $gotspares = 1;
 6510:                                     }
 6511:                                 }
 6512:                             }
 6513:                         }
 6514:                     }
 6515:                 }
 6516:             }
 6517:             unless ($gotspares) {
 6518:                 if ($lonhost eq $Apache::lonnet::perlvar{'lonHostID'}) {
 6519:                     $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 6520:                     $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 6521:                } else {
 6522:                     my $server_hostname = &Apache::lonnet::hostname($lonhost);
 6523:                     my $server_homeID = &Apache::lonnet::get_server_homeID($server_hostname);
 6524:                     if ($server_homeID eq $Apache::lonnet::perlvar{'lonHostID'}) {
 6525:                         $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 6526:                         $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 6527:                     } else {
 6528:                         my %what = (
 6529:                              spareid => 1,
 6530:                         );
 6531:                         my ($result,$returnhash) = 
 6532:                             &Apache::lonnet::get_remote_globals($lonhost,\%what);
 6533:                         if ($result eq 'ok') { 
 6534:                             if (ref($returnhash) eq 'HASH') {
 6535:                                 if (ref($returnhash->{'spareid'}) eq 'HASH') {
 6536:                                     $spareid{$lonhost}{'primary'} = $returnhash->{'spareid'}->{'primary'};
 6537:                                     $spareid{$lonhost}{'default'} = $returnhash->{'spareid'}->{'default'};
 6538:                                 }
 6539:                             }
 6540:                         }
 6541:                     }
 6542:                 }
 6543:             }
 6544:         }
 6545:     }
 6546:     return %spareid;
 6547: }
 6548: 
 6549: sub spares_row {
 6550:     my ($dom,$servers,$spareid,$serverhomes,$altids,$other_insts,
 6551:         $curroffloadnow,$curroffloadoth,$rowtotal) = @_;
 6552:     my $css_class;
 6553:     my $numinrow = 4;
 6554:     my $itemcount = 1;
 6555:     my $datatable;
 6556:     my %typetitles = &sparestype_titles();
 6557:     if ((ref($servers) eq 'HASH') && (ref($spareid) eq 'HASH') && (ref($altids) eq 'HASH')) {
 6558:         foreach my $server (sort(keys(%{$servers}))) {
 6559:             my $serverhome = &Apache::lonnet::get_server_homeID($servers->{$server});
 6560:             my ($othercontrol,$serverdom);
 6561:             if ($serverhome ne $server) {
 6562:                 $serverdom = &Apache::lonnet::host_domain($serverhome);
 6563:                 $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 6564:             } else {
 6565:                 $serverdom = &Apache::lonnet::host_domain($server);
 6566:                 if ($serverdom ne $dom) {
 6567:                     $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 6568:                 }
 6569:             }
 6570:             next unless (ref($spareid->{$server}) eq 'HASH');
 6571:             my ($checkednow,$checkedoth);
 6572:             if (ref($curroffloadnow) eq 'HASH') {
 6573:                 if ($curroffloadnow->{$server}) {
 6574:                     $checkednow = ' checked="checked"';
 6575:                 }
 6576:             }
 6577:             if (ref($curroffloadoth) eq 'HASH') {
 6578:                 if ($curroffloadoth->{$server}) {
 6579:                     $checkedoth = ' checked="checked"';
 6580:                 }
 6581:             }
 6582:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6583:             $datatable .= '<tr'.$css_class.'>
 6584:                            <td rowspan="2">
 6585:                             <span class="LC_nobreak">'.
 6586:                           &mt('[_1] when busy, offloads to:'
 6587:                               ,'<b>'.$server.'</b>').'</span><br />'.
 6588:                           '<span class="LC_nobreak">'."\n".
 6589:                           '<label><input type="checkbox" name="offloadnow" value="'.$server.'"'.$checkednow.' />'.
 6590:                           '&nbsp;'.&mt('Switch any active user on next access').'</label></span>'.
 6591:                           "\n";
 6592:             if ($other_insts) {
 6593:                 $datatable .= '<br />'.
 6594:                               '<span class="LC_nobreak">'."\n".
 6595:                           '<label><input type="checkbox" name="offloadoth" value="'.$server.'"'.$checkedoth.' />'.
 6596:                           '&nbsp;'.&mt('Switch other institutions on next access').'</label></span>'.
 6597:                           "\n";
 6598:             }
 6599:             my (%current,%canselect);
 6600:             my @choices = 
 6601:                 &possible_newspares($server,$spareid->{$server},$serverhomes,$altids);
 6602:             foreach my $type ('primary','default') {
 6603:                 if (ref($spareid->{$server}) eq 'HASH') {
 6604:                     if (ref($spareid->{$server}{$type}) eq 'ARRAY') {
 6605:                         my @spares = @{$spareid->{$server}{$type}};
 6606:                         if (@spares > 0) {
 6607:                             if ($othercontrol) {
 6608:                                 $current{$type} = join(', ',@spares);
 6609:                             } else {
 6610:                                 $current{$type} .= '<table>';
 6611:                                 my $numspares = scalar(@spares);
 6612:                                 for (my $i=0;  $i<@spares; $i++) {
 6613:                                     my $rem = $i%($numinrow);
 6614:                                     if ($rem == 0) {
 6615:                                         if ($i > 0) {
 6616:                                             $current{$type} .= '</tr>';
 6617:                                         }
 6618:                                         $current{$type} .= '<tr>';
 6619:                                     }
 6620:                                     $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;'.
 6621:                                                        $spareid->{$server}{$type}[$i].
 6622:                                                        '</label></td>'."\n";
 6623:                                 }
 6624:                                 my $rem = @spares%($numinrow);
 6625:                                 my $colsleft = $numinrow - $rem;
 6626:                                 if ($colsleft > 1 ) {
 6627:                                     $current{$type} .= '<td colspan="'.$colsleft.
 6628:                                                        '" class="LC_left_item">'.
 6629:                                                        '&nbsp;</td>';
 6630:                                 } elsif ($colsleft == 1) {
 6631:                                     $current{$type} .= '<td class="LC_left_item">&nbsp;</td>'."\n";
 6632:                                 }
 6633:                                 $current{$type} .= '</tr></table>';
 6634:                             }
 6635:                         }
 6636:                     }
 6637:                     if ($current{$type} eq '') {
 6638:                         $current{$type} = &mt('None specified');
 6639:                     }
 6640:                     if ($othercontrol) {
 6641:                         if ($type eq 'primary') {
 6642:                             $canselect{$type} = $othercontrol;
 6643:                         }
 6644:                     } else {
 6645:                         $canselect{$type} = 
 6646:                             &mt('Add new [_1]'.$type.'[_2]:','<i>','</i>').'&nbsp;'.
 6647:                             '<select name="newspare_'.$type.'_'.$server.'" '.
 6648:                             'id="newspare_'.$type.'_'.$server.'" onchange="checkNewSpares('."'$server','$type'".');">'."\n".
 6649:                             '<option value="" selected ="selected">'.&mt('Select').'</option>'."\n";
 6650:                         if (@choices > 0) {
 6651:                             foreach my $lonhost (@choices) {
 6652:                                 $canselect{$type} .= '<option value="'.$lonhost.'">'.$lonhost.'</option>'."\n";
 6653:                             }
 6654:                         }
 6655:                         $canselect{$type} .= '</select>'."\n";
 6656:                     }
 6657:                 } else {
 6658:                     $current{$type} = &mt('Could not be determined');
 6659:                     if ($type eq 'primary') {
 6660:                         $canselect{$type} =  $othercontrol;
 6661:                     }
 6662:                 }
 6663:                 if ($type eq 'default') {
 6664:                     $datatable .= '<tr'.$css_class.'>';
 6665:                 }
 6666:                 $datatable .= '<td><i>'.$typetitles{$type}.'</i></td>'."\n".
 6667:                               '<td>'.$current{$type}.'</td>'."\n".
 6668:                               '<td>'.$canselect{$type}.'</td></tr>'."\n";
 6669:             }
 6670:             $itemcount ++;
 6671:         }
 6672:     }
 6673:     $$rowtotal += $itemcount;
 6674:     return $datatable;
 6675: }
 6676: 
 6677: sub possible_newspares {
 6678:     my ($server,$currspares,$serverhomes,$altids) = @_;
 6679:     my $serverhostname = &Apache::lonnet::hostname($server);
 6680:     my %excluded;
 6681:     if ($serverhostname ne '') {
 6682:         %excluded = (
 6683:                        $serverhostname => 1,
 6684:                     );
 6685:     }
 6686:     if (ref($currspares) eq 'HASH') {
 6687:         foreach my $type (keys(%{$currspares})) {
 6688:             if (ref($currspares->{$type}) eq 'ARRAY') {
 6689:                 if (@{$currspares->{$type}} > 0) {
 6690:                     foreach my $curr (@{$currspares->{$type}}) {
 6691:                         my $hostname = &Apache::lonnet::hostname($curr);
 6692:                         $excluded{$hostname} = 1;
 6693:                     }
 6694:                 }
 6695:             }
 6696:         }
 6697:     }
 6698:     my @choices;
 6699:     if ((ref($serverhomes) eq 'HASH') && (ref($altids) eq 'HASH')) {
 6700:         if (keys(%{$serverhomes}) > 1) {
 6701:             foreach my $name (sort(keys(%{$serverhomes}))) {
 6702:                 unless ($excluded{$name}) {
 6703:                     if (exists($altids->{$serverhomes->{$name}})) {
 6704:                         push(@choices,$altids->{$serverhomes->{$name}});
 6705:                     } else {
 6706:                         push(@choices,$serverhomes->{$name});
 6707:                     }
 6708:                 }
 6709:             }
 6710:         }
 6711:     }
 6712:     return sort(@choices);
 6713: }
 6714: 
 6715: sub print_loadbalancing {
 6716:     my ($dom,$settings,$rowtotal) = @_;
 6717:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
 6718:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
 6719:     my $numinrow = 1;
 6720:     my $datatable;
 6721:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 6722:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
 6723:     if (ref($settings) eq 'HASH') {
 6724:         %existing = %{$settings};
 6725:     }
 6726:     if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
 6727:         &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
 6728:                                   \%currtargets,\%currrules,\%currcookies);
 6729:     } else {
 6730:         return;
 6731:     }
 6732:     my ($othertitle,$usertypes,$types) =
 6733:         &Apache::loncommon::sorted_inst_types($dom);
 6734:     my $rownum = 8;
 6735:     if (ref($types) eq 'ARRAY') {
 6736:         $rownum += scalar(@{$types});
 6737:     }
 6738:     my @css_class = ('LC_odd_row','LC_even_row');
 6739:     my $balnum = 0;
 6740:     my $islast;
 6741:     my (@toshow,$disabledtext);
 6742:     if (keys(%currbalancer) > 0) {
 6743:         @toshow = sort(keys(%currbalancer));
 6744:         if (scalar(@toshow) < scalar(keys(%servers)) + 1) {
 6745:             push(@toshow,'');
 6746:         }
 6747:     } else {
 6748:         @toshow = ('');
 6749:         $disabledtext = &mt('No existing load balancer');
 6750:     }
 6751:     foreach my $lonhost (@toshow) {
 6752:         if ($balnum == scalar(@toshow)-1) {
 6753:             $islast = 1;
 6754:         } else {
 6755:             $islast = 0;
 6756:         }
 6757:         my $cssidx = $balnum%2;
 6758:         my $targets_div_style = 'display: none';
 6759:         my $disabled_div_style = 'display: block';
 6760:         my $homedom_div_style = 'display: none';
 6761:         $datatable .= '<tr class="'.$css_class[$cssidx].'">'.
 6762:                       '<td rowspan="'.$rownum.'" valign="top">'.
 6763:                       '<p>';
 6764:         if ($lonhost eq '') {
 6765:             $datatable .= '<span class="LC_nobreak">';
 6766:             if (keys(%currbalancer) > 0) {
 6767:                 $datatable .= &mt('Add balancer:');
 6768:             } else {
 6769:                 $datatable .= &mt('Enable balancer:');
 6770:             }
 6771:             $datatable .= '&nbsp;'.
 6772:                           '<select name="loadbalancing_lonhost_'.$balnum.'"'.
 6773:                           ' id="loadbalancing_lonhost_'.$balnum.'"'.
 6774:                           ' onchange="toggleTargets('."'$balnum'".');">'."\n".
 6775:                           '<option value="" selected="selected">'.&mt('None').
 6776:                           '</option>'."\n";
 6777:             foreach my $server (sort(keys(%servers))) {
 6778:                 next if ($currbalancer{$server});
 6779:                 $datatable .= '<option value="'.$server.'">'.$server.'</option>'."\n";
 6780:             }
 6781:             $datatable .=
 6782:                 '</select>'."\n".
 6783:                 '<input type="hidden" name="loadbalancing_prevlonhost_'.$balnum.'" id="loadbalancing_prevlonhost_'.$balnum.'" value="" />&nbsp;</span>'."\n";
 6784:         } else {
 6785:             $datatable .= '<i>'.$lonhost.'</i><br /><span class="LC_nobreak">'.
 6786:                           '<label><input type="checkbox" name="loadbalancing_delete" value="'.$balnum.'" id="loadbalancing_delete_'.$balnum.'" onclick="javascript:balancerDeleteChange('."'$balnum'".');" />&nbsp;'.
 6787:                            &mt('Stop balancing').'</label>'.
 6788:                            '<input type="hidden" name="loadbalancing_lonhost_'.$balnum.'" value="'.$lonhost.'" id="loadbalancing_lonhost_'.$balnum.'" /></span>';
 6789:             $targets_div_style = 'display: block';
 6790:             $disabled_div_style = 'display: none';
 6791:             if ($dom eq &Apache::lonnet::host_domain($lonhost)) {
 6792:                 $homedom_div_style = 'display: block';
 6793:             }
 6794:         }
 6795:         $datatable .= '</p></td><td rowspan="'.$rownum.'" valign="top">'.
 6796:                   '<div id="loadbalancing_disabled_'.$balnum.'" style="'.
 6797:                   $disabled_div_style.'">'.$disabledtext.'</div>'."\n".
 6798:                   '<div id="loadbalancing_targets_'.$balnum.'" style="'.$targets_div_style.'">'.&mt('Offloads to:').'<br />';
 6799:         my ($numspares,@spares) = &count_servers($lonhost,%servers);
 6800:         my @sparestypes = ('primary','default');
 6801:         my %typetitles = &sparestype_titles();
 6802:         my %hostherechecked = (
 6803:                                   no => ' checked="checked"',
 6804:                               );
 6805:         my %balcookiechecked = (
 6806:                                   no => ' checked="checked"',
 6807:                                );
 6808:         foreach my $sparetype (@sparestypes) {
 6809:             my $targettable;
 6810:             for (my $i=0; $i<$numspares; $i++) {
 6811:                 my $checked;
 6812:                 if (ref($currtargets{$lonhost}) eq 'HASH') {
 6813:                     if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 6814:                         if (grep(/^\Q$spares[$i]\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 6815:                             $checked = ' checked="checked"';
 6816:                         }
 6817:                     }
 6818:                 }
 6819:                 my ($chkboxval,$disabled);
 6820:                 if (($lonhost ne '') && (exists($servers{$lonhost}))) {
 6821:                     $chkboxval = $spares[$i];
 6822:                 }
 6823:                 if (exists($currbalancer{$spares[$i]})) {
 6824:                     $disabled = ' disabled="disabled"';
 6825:                 }
 6826:                 $targettable .=
 6827:                     '<td><span class="LC_nobreak"><label>'.
 6828:                     '<input type="checkbox" name="loadbalancing_target_'.$balnum.'_'.$sparetype.'"'.
 6829:                     $checked.$disabled.' value="'.$chkboxval.'" id="loadbalancing_target_'.$balnum.'_'.$sparetype.'_'.$i.'" onclick="checkOffloads('."this,'$balnum','$sparetype'".');" /><span id="loadbalancing_targettxt_'.$balnum.'_'.$sparetype.'_'.$i.'">&nbsp;'.$chkboxval.
 6830:                     '</span></label></span></td>';
 6831:                 my $rem = $i%($numinrow);
 6832:                 if ($rem == 0) {
 6833:                     if (($i > 0) && ($i < $numspares-1)) {
 6834:                         $targettable .= '</tr>';
 6835:                     }
 6836:                     if ($i < $numspares-1) {
 6837:                         $targettable .= '<tr>';
 6838:                     }
 6839:                 }
 6840:             }
 6841:             if ($targettable ne '') {
 6842:                 my $rem = $numspares%($numinrow);
 6843:                 my $colsleft = $numinrow - $rem;
 6844:                 if ($colsleft > 1 ) {
 6845:                     $targettable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 6846:                                     '&nbsp;</td>';
 6847:                 } elsif ($colsleft == 1) {
 6848:                     $targettable .= '<td class="LC_left_item">&nbsp;</td>';
 6849:                 }
 6850:                 $datatable .=  '<i>'.$typetitles{$sparetype}.'</i><br />'.
 6851:                                '<table><tr>'.$targettable.'</tr></table><br />';
 6852:             }
 6853:             $hostherechecked{$sparetype} = '';
 6854:             if (ref($currtargets{$lonhost}) eq 'HASH') {
 6855:                 if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 6856:                     if (grep(/^\Q$lonhost\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 6857:                         $hostherechecked{$sparetype} = ' checked="checked"';
 6858:                         $hostherechecked{'no'} = '';
 6859:                     }
 6860:                 }
 6861:             }
 6862:         }
 6863:         if ($currcookies{$lonhost}) {
 6864:             %balcookiechecked = (
 6865:                                     yes => ' checked="checked"',
 6866:                                 );
 6867:         }
 6868:         $datatable .= &mt('Hosting on balancer itself').'<br />'.
 6869:                       '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" value="no"'.
 6870:                       $hostherechecked{'no'}.' />'.&mt('No').'</label><br />';
 6871:         foreach my $sparetype (@sparestypes) {
 6872:             $datatable .= '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" '.
 6873:                           'value="'.$sparetype.'"'.$hostherechecked{$sparetype}.' /><i>'.$typetitles{$sparetype}.
 6874:                           '</i></label><br />';
 6875:         }
 6876:         $datatable .= &mt('Use balancer cookie').'<br />'.
 6877:                       '<label><input type="radio" name="loadbalancing_cookie_'.$balnum.'" value="1"'.
 6878:                       $balcookiechecked{'yes'}.' />'.&mt('Yes').'</label><br />'.
 6879:                       '<label><input type="radio" name="loadbalancing_cookie_'.$balnum.'" value="0"'.
 6880:                       $balcookiechecked{'no'}.' />'.&mt('No').'</label><br />'.
 6881:                       '</div></td></tr>'.
 6882:                       &loadbalancing_rules($dom,$intdom,$currrules{$lonhost},
 6883:                                            $othertitle,$usertypes,$types,\%servers,
 6884:                                            \%currbalancer,$lonhost,
 6885:                                            $targets_div_style,$homedom_div_style,
 6886:                                            $css_class[$cssidx],$balnum,$islast);
 6887:         $$rowtotal += $rownum;
 6888:         $balnum ++;
 6889:     }
 6890:     $datatable .= '<input type="hidden" name="loadbalancing_total" id="loadbalancing_total" value="'.$balnum.'" />';
 6891:     return $datatable;
 6892: }
 6893: 
 6894: sub get_loadbalancers_config {
 6895:     my ($servers,$existing,$currbalancer,$currtargets,$currrules,$currcookies) = @_;
 6896:     return unless ((ref($servers) eq 'HASH') &&
 6897:                    (ref($existing) eq 'HASH') && (ref($currbalancer) eq 'HASH') &&
 6898:                    (ref($currtargets) eq 'HASH') && (ref($currrules) eq 'HASH') &&
 6899:                    (ref($currcookies) eq 'HASH'));
 6900:     if (keys(%{$existing}) > 0) {
 6901:         my $oldlonhost;
 6902:         foreach my $key (sort(keys(%{$existing}))) {
 6903:             if ($key eq 'lonhost') {
 6904:                 $oldlonhost = $existing->{'lonhost'};
 6905:                 $currbalancer->{$oldlonhost} = 1;
 6906:             } elsif ($key eq 'targets') {
 6907:                 if ($oldlonhost) {
 6908:                     $currtargets->{$oldlonhost} = $existing->{'targets'};
 6909:                 }
 6910:             } elsif ($key eq 'rules') {
 6911:                 if ($oldlonhost) {
 6912:                     $currrules->{$oldlonhost} = $existing->{'rules'};
 6913:                 }
 6914:             } elsif (ref($existing->{$key}) eq 'HASH') {
 6915:                 $currbalancer->{$key} = 1;
 6916:                 $currtargets->{$key} = $existing->{$key}{'targets'};
 6917:                 $currrules->{$key} = $existing->{$key}{'rules'};
 6918:                 if ($existing->{$key}{'cookie'}) {
 6919:                     $currcookies->{$key} = 1;
 6920:                 }
 6921:             }
 6922:         }
 6923:     } else {
 6924:         my ($balancerref,$targetsref) =
 6925:                 &Apache::lonnet::get_lonbalancer_config($servers);
 6926:         if ((ref($balancerref) eq 'HASH') && (ref($targetsref) eq 'HASH')) {
 6927:             foreach my $server (sort(keys(%{$balancerref}))) {
 6928:                 $currbalancer->{$server} = 1;
 6929:                 $currtargets->{$server} = $targetsref->{$server};
 6930:             }
 6931:         }
 6932:     }
 6933:     return;
 6934: }
 6935: 
 6936: sub loadbalancing_rules {
 6937:     my ($dom,$intdom,$currrules,$othertitle,$usertypes,$types,$servers,
 6938:         $currbalancer,$lonhost,$targets_div_style,$homedom_div_style,
 6939:         $css_class,$balnum,$islast) = @_;
 6940:     my $output;
 6941:     my $num = 0;
 6942:     my ($alltypes,$othertypes,$titles) =
 6943:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
 6944:     if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH'))  {
 6945:         foreach my $type (@{$alltypes}) {
 6946:             $num ++;
 6947:             my $current;
 6948:             if (ref($currrules) eq 'HASH') {
 6949:                 $current = $currrules->{$type};
 6950:             }
 6951:             if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 6952:                 if ($dom ne &Apache::lonnet::host_domain($lonhost)) {
 6953:                     $current = '';
 6954:                 }
 6955:             }
 6956:             $output .= &loadbalance_rule_row($type,$titles->{$type},$current,
 6957:                                              $servers,$currbalancer,$lonhost,$dom,
 6958:                                              $targets_div_style,$homedom_div_style,
 6959:                                              $css_class,$balnum,$num,$islast);
 6960:         }
 6961:     }
 6962:     return $output;
 6963: }
 6964: 
 6965: sub loadbalancing_titles {
 6966:     my ($dom,$intdom,$usertypes,$types) = @_;
 6967:     my %othertypes = (
 6968:            '_LC_adv'         => &mt('Advanced users from [_1]',$dom),
 6969:            '_LC_author'      => &mt('Users from [_1] with author role',$dom),
 6970:            '_LC_internetdom' => &mt('Users not from [_1], but from [_2]',$dom,$intdom),
 6971:            '_LC_external'    => &mt('Users not from [_1]',$intdom),
 6972:            '_LC_ipchangesso' => &mt('SSO users from [_1], with IP mismatch',$dom),
 6973:            '_LC_ipchange'    => &mt('Non-SSO users with IP mismatch'),
 6974:                      );
 6975:     my @alltypes = ('_LC_adv','_LC_author','_LC_internetdom','_LC_external','_LC_ipchangesso','_LC_ipchange');
 6976:     my @available;
 6977:     if (ref($types) eq 'ARRAY') {
 6978:         @available = @{$types};
 6979:     }
 6980:     unless (grep(/^default$/,@available)) {
 6981:         push(@available,'default');
 6982:     }
 6983:     unshift(@alltypes,@available);
 6984:     my %titles;
 6985:     foreach my $type (@alltypes) {
 6986:         if ($type =~ /^_LC_/) {
 6987:             $titles{$type} = $othertypes{$type};
 6988:         } elsif ($type eq 'default') {
 6989:             $titles{$type} = &mt('All users from [_1]',$dom);
 6990:             if (ref($types) eq 'ARRAY') {
 6991:                 if (@{$types} > 0) {
 6992:                     $titles{$type} = &mt('Other users from [_1]',$dom);
 6993:                 }
 6994:             }
 6995:         } elsif (ref($usertypes) eq 'HASH') {
 6996:             $titles{$type} = $usertypes->{$type};
 6997:         }
 6998:     }
 6999:     return (\@alltypes,\%othertypes,\%titles);
 7000: }
 7001: 
 7002: sub loadbalance_rule_row {
 7003:     my ($type,$title,$current,$servers,$currbalancer,$lonhost,$dom,
 7004:         $targets_div_style,$homedom_div_style,$css_class,$balnum,$num,$islast) = @_;
 7005:     my @rulenames;
 7006:     my %ruletitles = &offloadtype_text();
 7007:     if (($type eq '_LC_ipchangesso') || ($type eq '_LC_ipchange')) {
 7008:         @rulenames = ('balancer','offloadedto','specific');
 7009:     } else {
 7010:         @rulenames = ('default','homeserver');
 7011:         if ($type eq '_LC_external') {
 7012:             push(@rulenames,'externalbalancer');
 7013:         } else {
 7014:             push(@rulenames,'specific');
 7015:         }
 7016:         push(@rulenames,'none');
 7017:     }
 7018:     my $style = $targets_div_style;
 7019:     if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 7020:         $style = $homedom_div_style;
 7021:     }
 7022:     my $space;
 7023:     if ($islast && $num == 1) {
 7024:         $space = '<div display="inline-block">&nbsp;</div>';
 7025:     }
 7026:     my $output =
 7027:         '<tr class="'.$css_class.'" id="balanceruletr_'.$balnum.'_'.$num.'"><td valign="top">'.$space.
 7028:         '<div id="balanceruletitle_'.$balnum.'_'.$type.'" style="'.$style.'">'.$title.'</div></td>'."\n".
 7029:         '<td valaign="top">'.$space.
 7030:         '<div id="balancerule_'.$balnum.'_'.$type.'" style="'.$style.'">'."\n";
 7031:     for (my $i=0; $i<@rulenames; $i++) {
 7032:         my $rule = $rulenames[$i];
 7033:         my ($checked,$extra);
 7034:         if ($rulenames[$i] eq 'default') {
 7035:             $rule = '';
 7036:         }
 7037:         if ($rulenames[$i] eq 'specific') {
 7038:             if (ref($servers) eq 'HASH') {
 7039:                 my $default;
 7040:                 if (($current ne '') && (exists($servers->{$current}))) {
 7041:                     $checked = ' checked="checked"';
 7042:                 }
 7043:                 unless ($checked) {
 7044:                     $default = ' selected="selected"';
 7045:                 }
 7046:                 $extra =
 7047:                     ':&nbsp;<select name="loadbalancing_singleserver_'.$balnum.'_'.$type.
 7048:                     '" id="loadbalancing_singleserver_'.$balnum.'_'.$type.
 7049:                     '" onchange="singleServerToggle('."'$balnum','$type'".')">'."\n".
 7050:                     '<option value=""'.$default.'></option>'."\n";
 7051:                 foreach my $server (sort(keys(%{$servers}))) {
 7052:                     if (ref($currbalancer) eq 'HASH') {
 7053:                         next if (exists($currbalancer->{$server}));
 7054:                     }
 7055:                     my $selected;
 7056:                     if ($server eq $current) {
 7057:                         $selected = ' selected="selected"';
 7058:                     }
 7059:                     $extra .= '<option value="'.$server.'"'.$selected.'>'.$server.'</option>';
 7060:                 }
 7061:                 $extra .= '</select>';
 7062:             }
 7063:         } elsif ($rule eq $current) {
 7064:             $checked = ' checked="checked"';
 7065:         }
 7066:         $output .= '<span class="LC_nobreak"><label>'.
 7067:                    '<input type="radio" name="loadbalancing_rules_'.$balnum.'_'.$type.
 7068:                    '" id="loadbalancing_rules_'.$balnum.'_'.$type.'_'.$i.'" value="'.
 7069:                    $rule.'" onclick="balanceruleChange('."this.form,'$balnum','$type'".
 7070:                    ')"'.$checked.' />&nbsp;';
 7071:         if (($rulenames[$i] eq 'specific') && ($type =~ /^_LC_ipchange/)) {
 7072:             $output .= $ruletitles{'particular'};
 7073:         } else {
 7074:             $output .= $ruletitles{$rulenames[$i]};
 7075:         }
 7076:         $output .= '</label>'.$extra.'</span><br />'."\n";
 7077:     }
 7078:     $output .= '</div></td></tr>'."\n";
 7079:     return $output;
 7080: }
 7081: 
 7082: sub offloadtype_text {
 7083:     my %ruletitles = &Apache::lonlocal::texthash (
 7084:            'default'          => 'Offloads to default destinations',
 7085:            'homeserver'       => "Offloads to user's home server",
 7086:            'externalbalancer' => "Offloads to Load Balancer in user's domain",
 7087:            'specific'         => 'Offloads to specific server',
 7088:            'none'             => 'No offload',
 7089:            'balancer'         => 'Session hosted on Load Balancer, after re-authentication',
 7090:            'offloadedto'      => 'Session hosted on offload server, after re-authentication',
 7091:            'particular'       => 'Session hosted (after re-auth) on server:',
 7092:     );
 7093:     return %ruletitles;
 7094: }
 7095: 
 7096: sub sparestype_titles {
 7097:     my %typestitles = &Apache::lonlocal::texthash (
 7098:                           'primary' => 'primary',
 7099:                           'default' => 'default',
 7100:                       );
 7101:     return %typestitles;
 7102: }
 7103: 
 7104: sub contact_titles {
 7105:     my %titles = &Apache::lonlocal::texthash (
 7106:                    'supportemail'    => 'Support E-mail address',
 7107:                    'adminemail'      => 'Default Server Admin E-mail address',
 7108:                    'errormail'       => 'Error reports to be e-mailed to',
 7109:                    'packagesmail'    => 'Package update alerts to be e-mailed to',
 7110:                    'helpdeskmail'    => "Helpdesk requests from all users in this domain",
 7111:                    'otherdomsmail'   => 'Helpdesk requests from users in other (unconfigured) domains',
 7112:                    'lonstatusmail'   => 'E-mail from nightly status check (warnings/errors)',
 7113:                    'requestsmail'    => 'E-mail from course requests requiring approval',
 7114:                    'updatesmail'     => 'E-mail from nightly check of LON-CAPA module integrity/updates',
 7115:                    'idconflictsmail' => 'E-mail from bi-nightly check for multiple users sharing same student/employee ID',
 7116:                    'hostipmail'      => 'E-mail from nightly check of hostname/IP network changes',
 7117:                    'errorthreshold'  => 'Error count threshold for status e-mail to admin(s)',
 7118:                    'errorsysmail'    => 'Error count threshold for e-mail to developer group',
 7119:                    'errorweights'    => 'Weights used to compute error count',
 7120:                    'errorexcluded'   => 'Servers with unsent updates excluded from count',
 7121:                  );
 7122:     my %short_titles = &Apache::lonlocal::texthash (
 7123:                            adminemail   => 'Admin E-mail address',
 7124:                            supportemail => 'Support E-mail',
 7125:                        );   
 7126:     return (\%titles,\%short_titles);
 7127: }
 7128: 
 7129: sub helpform_fields {
 7130:     my %titles =  &Apache::lonlocal::texthash (
 7131:                        'username'   => 'Name',
 7132:                        'user'       => 'Username/domain',
 7133:                        'phone'      => 'Phone',
 7134:                        'cc'         => 'Cc e-mail',
 7135:                        'course'     => 'Course Details',
 7136:                        'section'    => 'Sections',
 7137:                        'screenshot' => 'File upload',
 7138:     );
 7139:     my @fields = ('username','phone','user','course','section','cc','screenshot');
 7140:     my %possoptions = (
 7141:                         username     => ['yes','no','req'],
 7142:                         phone        => ['yes','no','req'],
 7143:                         user         => ['yes','no'],
 7144:                         cc           => ['yes','no'],
 7145:                         course       => ['yes','no'],
 7146:                         section      => ['yes','no'],
 7147:                         screenshot   => ['yes','no'],
 7148:                       );
 7149:     my %fieldoptions = &Apache::lonlocal::texthash (
 7150:                          'yes'  => 'Optional',
 7151:                          'req'  => 'Required',
 7152:                          'no'   => "Not shown",
 7153:     );
 7154:     return (\@fields,\%titles,\%fieldoptions,\%possoptions);
 7155: }
 7156: 
 7157: sub tool_titles {
 7158:     my %titles = &Apache::lonlocal::texthash (
 7159:                      aboutme    => 'Personal web page',
 7160:                      blog       => 'Blog',
 7161:                      webdav     => 'WebDAV',
 7162:                      portfolio  => 'Portfolio',
 7163:                      official   => 'Official courses (with institutional codes)',
 7164:                      unofficial => 'Unofficial courses',
 7165:                      community  => 'Communities',
 7166:                      textbook   => 'Textbook courses',
 7167:                  );
 7168:     return %titles;
 7169: }
 7170: 
 7171: sub courserequest_titles {
 7172:     my %titles = &Apache::lonlocal::texthash (
 7173:                                    official   => 'Official',
 7174:                                    unofficial => 'Unofficial',
 7175:                                    community  => 'Communities',
 7176:                                    textbook   => 'Textbook',
 7177:                                    norequest  => 'Not allowed',
 7178:                                    approval   => 'Approval by Dom. Coord.',
 7179:                                    validate   => 'With validation',
 7180:                                    autolimit  => 'Numerical limit',
 7181:                                    unlimited  => '(blank for unlimited)',
 7182:                  );
 7183:     return %titles;
 7184: }
 7185: 
 7186: sub authorrequest_titles {
 7187:     my %titles = &Apache::lonlocal::texthash (
 7188:                                    norequest  => 'Not allowed',
 7189:                                    approval   => 'Approval by Dom. Coord.',
 7190:                                    automatic  => 'Automatic approval',
 7191:                  );
 7192:     return %titles;
 7193: }
 7194: 
 7195: sub courserequest_conditions {
 7196:     my %conditions = &Apache::lonlocal::texthash (
 7197:        approval    => '(Processing of request subject to approval by Domain Coordinator).',
 7198:        validate   => '(Processing of request subject to institutional validation).',
 7199:                  );
 7200:     return %conditions;
 7201: }
 7202: 
 7203: 
 7204: sub print_usercreation {
 7205:     my ($position,$dom,$settings,$rowtotal) = @_;
 7206:     my $numinrow = 4;
 7207:     my $datatable;
 7208:     if ($position eq 'top') {
 7209:         $$rowtotal ++;
 7210:         my $rowcount = 0;
 7211:         my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($dom,'username');
 7212:         if (ref($rules) eq 'HASH') {
 7213:             if (keys(%{$rules}) > 0) {
 7214:                 $datatable .= &user_formats_row('username',$settings,$rules,
 7215:                                                 $ruleorder,$numinrow,$rowcount);
 7216:                 $$rowtotal ++;
 7217:                 $rowcount ++;
 7218:             }
 7219:         }
 7220:         my ($idrules,$idruleorder) = &Apache::lonnet::inst_userrules($dom,'id');
 7221:         if (ref($idrules) eq 'HASH') {
 7222:             if (keys(%{$idrules}) > 0) {
 7223:                 $datatable .= &user_formats_row('id',$settings,$idrules,
 7224:                                                 $idruleorder,$numinrow,$rowcount);
 7225:                 $$rowtotal ++;
 7226:                 $rowcount ++;
 7227:             }
 7228:         }
 7229:         if ($rowcount == 0) {
 7230:             $datatable .= '<tr><td colspan="2">'.&mt('No format rules have been defined for usernames or IDs in this domain.').'</td></tr>';  
 7231:             $$rowtotal ++;
 7232:             $rowcount ++;
 7233:         }
 7234:     } elsif ($position eq 'middle') {
 7235:         my @creators = ('author','course','requestcrs');
 7236:         my ($rules,$ruleorder) =
 7237:             &Apache::lonnet::inst_userrules($dom,'username');
 7238:         my %lt = &usercreation_types();
 7239:         my %checked;
 7240:         if (ref($settings) eq 'HASH') {
 7241:             if (ref($settings->{'cancreate'}) eq 'HASH') {
 7242:                 foreach my $item (@creators) {
 7243:                     $checked{$item} = $settings->{'cancreate'}{$item};
 7244:                 }
 7245:             } elsif (ref($settings->{'cancreate'}) eq 'ARRAY') {
 7246:                 foreach my $item (@creators) {
 7247:                     if (grep(/^\Q$item\E$/,@{$settings->{'cancreate'}})) {
 7248:                         $checked{$item} = 'none';
 7249:                     }
 7250:                 }
 7251:             }
 7252:         }
 7253:         my $rownum = 0;
 7254:         foreach my $item (@creators) {
 7255:             $rownum ++;
 7256:             if ($checked{$item} eq '') {
 7257:                 $checked{$item} = 'any';
 7258:             }
 7259:             my $css_class;
 7260:             if ($rownum%2) {
 7261:                 $css_class = '';
 7262:             } else {
 7263:                 $css_class = ' class="LC_odd_row" ';
 7264:             }
 7265:             $datatable .= '<tr'.$css_class.'>'.
 7266:                          '<td><span class="LC_nobreak">'.$lt{$item}.
 7267:                          '</span></td><td align="right">';
 7268:             my @options = ('any');
 7269:             if (ref($rules) eq 'HASH') {
 7270:                 if (keys(%{$rules}) > 0) {
 7271:                     push(@options,('official','unofficial'));
 7272:                 }
 7273:             }
 7274:             push(@options,'none');
 7275:             foreach my $option (@options) {
 7276:                 my $type = 'radio';
 7277:                 my $check = ' ';
 7278:                 if ($checked{$item} eq $option) {
 7279:                     $check = ' checked="checked" ';
 7280:                 } 
 7281:                 $datatable .= '<span class="LC_nobreak"><label>'.
 7282:                               '<input type="'.$type.'" name="can_createuser_'.
 7283:                               $item.'" value="'.$option.'"'.$check.'/>&nbsp;'.
 7284:                               $lt{$option}.'</label>&nbsp;&nbsp;</span>';
 7285:             }
 7286:             $datatable .= '</td></tr>';
 7287:         }
 7288:     } else {
 7289:         my @contexts = ('author','course','domain');
 7290:         my @authtypes = ('int','krb4','krb5','loc');
 7291:         my %checked;
 7292:         if (ref($settings) eq 'HASH') {
 7293:             if (ref($settings->{'authtypes'}) eq 'HASH') {
 7294:                 foreach my $item (@contexts) {
 7295:                     if (ref($settings->{'authtypes'}{$item}) eq 'HASH') {
 7296:                         foreach my $auth (@authtypes) {
 7297:                             if ($settings->{'authtypes'}{$item}{$auth}) {
 7298:                                 $checked{$item}{$auth} = ' checked="checked" ';
 7299:                             }
 7300:                         }
 7301:                     }
 7302:                 }
 7303:             }
 7304:         } else {
 7305:             foreach my $item (@contexts) {
 7306:                 foreach my $auth (@authtypes) {
 7307:                     $checked{$item}{$auth} = ' checked="checked" ';
 7308:                 }
 7309:             }
 7310:         }
 7311:         my %title = &context_names();
 7312:         my %authname = &authtype_names();
 7313:         my $rownum = 0;
 7314:         my $css_class; 
 7315:         foreach my $item (@contexts) {
 7316:             if ($rownum%2) {
 7317:                 $css_class = '';
 7318:             } else {
 7319:                 $css_class = ' class="LC_odd_row" ';
 7320:             }
 7321:             $datatable .=   '<tr'.$css_class.'>'.
 7322:                             '<td>'.$title{$item}.
 7323:                             '</td><td class="LC_left_item">'.
 7324:                             '<span class="LC_nobreak">';
 7325:             foreach my $auth (@authtypes) {
 7326:                 $datatable .= '<label>'. 
 7327:                               '<input type="checkbox" name="'.$item.'_auth" '.
 7328:                               $checked{$item}{$auth}.' value="'.$auth.'" />'.
 7329:                               $authname{$auth}.'</label>&nbsp;';
 7330:             }
 7331:             $datatable .= '</span></td></tr>';
 7332:             $rownum ++;
 7333:         }
 7334:         $$rowtotal += $rownum;
 7335:     }
 7336:     return $datatable;
 7337: }
 7338: 
 7339: sub print_selfcreation {
 7340:     my ($position,$dom,$settings,$rowtotal) = @_;
 7341:     my (@selfcreate,$createsettings,$processing,$emailoptions,$emailverified,
 7342:         $emaildomain,$datatable);
 7343:     if (ref($settings) eq 'HASH') {
 7344:         if (ref($settings->{'cancreate'}) eq 'HASH') {
 7345:             $createsettings = $settings->{'cancreate'};
 7346:             if (ref($createsettings) eq 'HASH') {
 7347:                 if (ref($createsettings->{'selfcreate'}) eq 'ARRAY') {
 7348:                     @selfcreate = @{$createsettings->{'selfcreate'}};
 7349:                 } elsif ($createsettings->{'selfcreate'} ne '') {
 7350:                     if ($settings->{'cancreate'}{'selfcreate'} eq 'any') {
 7351:                         @selfcreate = ('email','login','sso');
 7352:                     } elsif ($createsettings->{'selfcreate'} ne 'none') {
 7353:                         @selfcreate = ($createsettings->{'selfcreate'});
 7354:                     }
 7355:                 }
 7356:                 if (ref($createsettings->{'selfcreateprocessing'}) eq 'HASH') {
 7357:                     $processing = $createsettings->{'selfcreateprocessing'};
 7358:                 }
 7359:                 if (ref($createsettings->{'emailoptions'}) eq 'HASH') {
 7360:                     $emailoptions = $createsettings->{'emailoptions'};
 7361:                 }
 7362:                 if (ref($createsettings->{'emailverified'}) eq 'HASH') {
 7363:                     $emailverified = $createsettings->{'emailverified'};
 7364:                 }
 7365:                 if (ref($createsettings->{'emaildomain'}) eq 'HASH') {
 7366:                     $emaildomain = $createsettings->{'emaildomain'};
 7367:                 }
 7368:             }
 7369:         }
 7370:     }
 7371:     my %radiohash;
 7372:     my $numinrow = 4;
 7373:     map { $radiohash{'cancreate_'.$_} = 1; } @selfcreate;
 7374:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 7375:     if ($position eq 'top') {
 7376:         my %choices = &Apache::lonlocal::texthash (
 7377:                                                       cancreate_login      => 'Institutional Login',
 7378:                                                       cancreate_sso        => 'Institutional Single Sign On',
 7379:                                                   );
 7380:         my @toggles = sort(keys(%choices));
 7381:         my %defaultchecked = (
 7382:                                'cancreate_login' => 'off',
 7383:                                'cancreate_sso'   => 'off',
 7384:                              );
 7385:         my ($onclick,$itemcount);
 7386:         ($datatable,$itemcount) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 7387:                                                      \%choices,$itemcount,$onclick);
 7388:         $$rowtotal += $itemcount;
 7389: 
 7390:         if (ref($usertypes) eq 'HASH') {
 7391:             if (keys(%{$usertypes}) > 0) {
 7392:                 $datatable .= &insttypes_row($createsettings,$types,$usertypes,
 7393:                                              $dom,$numinrow,$othertitle,
 7394:                                              'statustocreate',$rowtotal);
 7395:                 $$rowtotal ++;
 7396:             }
 7397:         }
 7398:         my @fields = ('lastname','firstname','middlename','permanentemail','id','inststatus');
 7399:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 7400:         $fieldtitles{'inststatus'} = &mt('Institutional status');
 7401:         my $rem;
 7402:         my $numperrow = 2;
 7403:         my $css_class = $$rowtotal%2?' class="LC_odd_row"':'';
 7404:         $datatable .= '<tr'.$css_class.'>'.
 7405:                      '<td class="LC_left_item">'.&mt('Mapping of Shibboleth environment variable names to user data fields (SSO auth)').'</td>'.
 7406:                      '<td class="LC_left_item">'."\n".
 7407:                      '<table>'."\n";
 7408:         for (my $i=0; $i<@fields; $i++) {
 7409:             $rem = $i%($numperrow);
 7410:             if ($rem == 0) {
 7411:                 if ($i > 0) {
 7412:                     $datatable .= '</tr>';
 7413:                 }
 7414:                 $datatable .= '<tr>';
 7415:             }
 7416:             my $currval;
 7417:             if (ref($createsettings) eq 'HASH') {
 7418:                 if (ref($createsettings->{'shibenv'}) eq 'HASH') {
 7419:                     $currval = $createsettings->{'shibenv'}{$fields[$i]};
 7420:                 }
 7421:             }
 7422:             $datatable .= '<td class="LC_left_item">'.
 7423:                           '<span class="LC_nobreak">'.
 7424:                           '<input type="text" name="shibenv_'.$fields[$i].'" '.
 7425:                           'value="'.$currval.'" size="10" />&nbsp;'.
 7426:                           $fieldtitles{$fields[$i]}.'</span></td>';
 7427:         }
 7428:         my $colsleft = $numperrow - $rem;
 7429:         if ($colsleft > 1 ) {
 7430:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 7431:                          '&nbsp;</td>';
 7432:         } elsif ($colsleft == 1) {
 7433:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 7434:         }
 7435:         $datatable .= '</tr></table></td></tr>';
 7436:         $$rowtotal ++;
 7437:     } elsif ($position eq 'middle') {
 7438:         my %domconf = &Apache::lonnet::get_dom('configuration',['usermodification'],$dom);
 7439:         my @posstypes;
 7440:         if (ref($types) eq 'ARRAY') {
 7441:             @posstypes = @{$types};
 7442:         }
 7443:         unless (grep(/^default$/,@posstypes)) {
 7444:             push(@posstypes,'default');
 7445:         }
 7446:         my %usertypeshash;
 7447:         if (ref($usertypes) eq 'HASH') {
 7448:             %usertypeshash = %{$usertypes};
 7449:         }
 7450:         $usertypeshash{'default'} = $othertitle;
 7451:         foreach my $status (@posstypes) {
 7452:             $datatable .= &modifiable_userdata_row('selfcreate',$status,$domconf{'usermodification'},
 7453:                                                    $numinrow,$$rowtotal,\%usertypeshash);
 7454:             $$rowtotal ++;
 7455:         }
 7456:     } else {
 7457:         my %choices = &Apache::lonlocal::texthash (
 7458:                           'cancreate_email' => 'Non-institutional username (via e-mail verification)',
 7459:                                                   );
 7460:         my @toggles = sort(keys(%choices));
 7461:         my %defaultchecked = (
 7462:                                'cancreate_email' => 'off',
 7463:                              );
 7464:         my $customclass = 'LC_selfcreate_email';
 7465:         my $classprefix = 'LC_canmodify_emailusername_';
 7466:         my $optionsprefix = 'LC_options_emailusername_';
 7467:         my $display = 'none';
 7468:         my $rowstyle = 'display:none';
 7469:         if (grep(/^\Qemail\E$/,@selfcreate)) {
 7470:             $display = 'block';
 7471:             $rowstyle = 'display:table-row';
 7472:         }
 7473:         my $onclick = "toggleRows(this.form,'cancreate_email','selfassign','$customclass','$classprefix','$optionsprefix');";
 7474:         ($datatable,$$rowtotal) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 7475:                                                      \%choices,$$rowtotal,$onclick);
 7476:         $datatable .= &print_requestmail($dom,'selfcreation',$createsettings,$rowtotal,$customclass,
 7477:                                          $rowstyle);
 7478:         $$rowtotal ++;
 7479:         $datatable .= &captcha_choice('cancreate',$createsettings,$$rowtotal,$customclass,
 7480:                                       $rowstyle);
 7481:         $$rowtotal ++;
 7482:         my (@ordered,@posstypes,%usertypeshash);
 7483:         my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
 7484:         my ($emailrules,$emailruleorder) =
 7485:             &Apache::lonnet::inst_userrules($dom,'email');
 7486:         my $primary_id = &Apache::lonnet::domain($dom,'primary');
 7487:         my $intdom = &Apache::lonnet::internet_dom($primary_id);
 7488:         if (ref($types) eq 'ARRAY') {
 7489:             @posstypes = @{$types};
 7490:         }
 7491:         if (@posstypes) {
 7492:             unless (grep(/^default$/,@posstypes)) {
 7493:                 push(@posstypes,'default');
 7494:             }
 7495:             if (ref($usertypes) eq 'HASH') {
 7496:                 %usertypeshash = %{$usertypes};
 7497:             }
 7498:             my $currassign;
 7499:             if (ref($domdefaults{'inststatusguest'}) eq 'ARRAY') {
 7500:                 $currassign = {
 7501:                                   selfassign => $domdefaults{'inststatusguest'},
 7502:                               };
 7503:                 @ordered = @{$domdefaults{'inststatusguest'}};
 7504:             } else {
 7505:                 $currassign = { selfassign => [] };
 7506:             }
 7507:             my $onclicktypes = "toggleDataRow(this.form,'selfassign','$customclass','$optionsprefix',);".
 7508:                                "toggleDataRow(this.form,'selfassign','$customclass','$classprefix',1);";
 7509:             $datatable .= &insttypes_row($currassign,$types,$usertypes,$dom,
 7510:                                          $numinrow,$othertitle,'selfassign',
 7511:                                          $rowtotal,$onclicktypes,$customclass,
 7512:                                          $rowstyle);
 7513:             $$rowtotal ++;
 7514:             $usertypeshash{'default'} = $othertitle;
 7515:             foreach my $status (@posstypes) {
 7516:                 my $css_class;
 7517:                 if ($$rowtotal%2) {
 7518:                     $css_class = 'LC_odd_row ';
 7519:                 }
 7520:                 $css_class .= $customclass;
 7521:                 my $rowid = $optionsprefix.$status;
 7522:                 my $hidden = 1;
 7523:                 my $currstyle = 'display:none';
 7524:                 if (grep(/^\Q$status\E$/,@ordered)) {
 7525:                     $currstyle = $rowstyle;
 7526:                     $hidden = 0;
 7527:                 }
 7528:                 $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
 7529:                                              $emailrules,$emailruleorder,$settings,$status,$rowid,
 7530:                                              $usertypeshash{$status},$css_class,$currstyle,$intdom);
 7531:                 unless ($hidden) {
 7532:                     $$rowtotal ++;
 7533:                 }
 7534:             }
 7535:         } else {
 7536:             my $css_class;
 7537:             if ($$rowtotal%2) {
 7538:                 $css_class = 'LC_odd_row ';
 7539:             }
 7540:             $css_class .= $customclass;
 7541:             $usertypeshash{'default'} = $othertitle;
 7542:             $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
 7543:                                          $emailrules,$emailruleorder,$settings,'default','',
 7544:                                          $othertitle,$css_class,$rowstyle,$intdom);
 7545:             $$rowtotal ++;
 7546:         }
 7547:         my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 7548:         $numinrow = 1;
 7549:         if (@posstypes) {
 7550:             foreach my $status (@posstypes) {
 7551:                 my $rowid = $classprefix.$status;
 7552:                 my $datarowstyle = 'display:none';
 7553:                 if (grep(/^\Q$status\E$/,@ordered)) {
 7554:                     $datarowstyle = $rowstyle;
 7555:                 }
 7556:                 $datatable .= &modifiable_userdata_row('cancreate','emailusername_'.$status,$settings,
 7557:                                                        $numinrow,$$rowtotal,\%usertypeshash,$infofields,
 7558:                                                        $infotitles,$rowid,$customclass,$datarowstyle);
 7559:                 unless ($datarowstyle eq 'display:none') {
 7560:                     $$rowtotal ++;
 7561:                 }
 7562:             }
 7563:         } else {
 7564:             $datatable .= &modifiable_userdata_row('cancreate','emailusername_default',$settings,
 7565:                                                    $numinrow,$$rowtotal,\%usertypeshash,$infofields,
 7566:                                                    $infotitles,'',$customclass,$rowstyle);
 7567:         }
 7568:     }
 7569:     return $datatable;
 7570: }
 7571: 
 7572: sub selfcreate_javascript {
 7573:     return <<"ENDSCRIPT";
 7574: 
 7575: <script type="text/javascript">
 7576: // <![CDATA[
 7577: 
 7578: function toggleRows(form,radio,checkbox,target,prefix,altprefix) {
 7579:     var x = document.getElementsByClassName(target);
 7580:     var insttypes = 0;
 7581:     var insttypeRegExp = new RegExp(prefix);
 7582:     if ((x.length != undefined) && (x.length > 0)) {
 7583:         if (form.elements[radio].length != undefined) {
 7584:             for (var i=0; i<form.elements[radio].length; i++) {
 7585:                 if (form.elements[radio][i].checked) {
 7586:                     if (form.elements[radio][i].value == 1) {
 7587:                         for (var j=0; j<x.length; j++) {
 7588:                             if (x[j].id == 'undefined') {
 7589:                                 x[j].style.display = 'table-row';
 7590:                             } else if (insttypeRegExp.test(x[j].id)) {
 7591:                                 insttypes ++;
 7592:                             } else {
 7593:                                 x[j].style.display = 'table-row';
 7594:                             }
 7595:                         }
 7596:                     } else {
 7597:                         for (var j=0; j<x.length; j++) {
 7598:                             x[j].style.display = 'none';
 7599:                         }
 7600:                     }
 7601:                     break;
 7602:                 }
 7603:             }
 7604:             if (insttypes > 0) {
 7605:                 toggleDataRow(form,checkbox,target,altprefix);
 7606:                 toggleDataRow(form,checkbox,target,prefix,1);
 7607:             }
 7608:         }
 7609:     }
 7610:     return;
 7611: }
 7612: 
 7613: function toggleDataRow(form,checkbox,target,prefix,docount) {
 7614:     if (form.elements[checkbox].length != undefined) {
 7615:         var count = 0;
 7616:         if (docount) {
 7617:             for (var i=0; i<form.elements[checkbox].length; i++) {
 7618:                 if (form.elements[checkbox][i].checked) {
 7619:                     count ++;
 7620:                 }
 7621:             }
 7622:         }
 7623:         for (var i=0; i<form.elements[checkbox].length; i++) {
 7624:             var type = form.elements[checkbox][i].value;
 7625:             if (document.getElementById(prefix+type)) {
 7626:                 if (form.elements[checkbox][i].checked) {
 7627:                     document.getElementById(prefix+type).style.display = 'table-row';
 7628:                     if (count % 2 == 1) {
 7629:                         document.getElementById(prefix+type).className = target+' LC_odd_row';
 7630:                     } else {
 7631:                         document.getElementById(prefix+type).className = target;
 7632:                     }
 7633:                     count ++;
 7634:                 } else {
 7635:                     document.getElementById(prefix+type).style.display = 'none';
 7636:                 }
 7637:             }
 7638:         }
 7639:     }
 7640:     return;
 7641: }
 7642: 
 7643: function toggleEmailOptions(form,radio,prefix,altprefix,status) {
 7644:     var caller = radio+'_'+status;
 7645:     if (form.elements[caller].length != undefined) {
 7646:         for (var i=0; i<form.elements[caller].length; i++) {
 7647:             if (form.elements[caller][i].checked) {
 7648:                 if (document.getElementById(altprefix+'_inst_'+status)) {
 7649:                     var curr = form.elements[caller][i].value;
 7650:                     if (prefix) {
 7651:                         document.getElementById(prefix+'_'+status).style.display = 'none';
 7652:                     }
 7653:                     document.getElementById(altprefix+'_inst_'+status).style.display = 'none';
 7654:                     document.getElementById(altprefix+'_noninst_'+status).style.display = 'none';
 7655:                     if (curr == 'custom') {
 7656:                         if (prefix) {
 7657:                             document.getElementById(prefix+'_'+status).style.display = 'inline';
 7658:                         }
 7659:                     } else if (curr == 'inst') {
 7660:                         document.getElementById(altprefix+'_inst_'+status).style.display = 'inline';
 7661:                     } else if (curr == 'noninst') {
 7662:                         document.getElementById(altprefix+'_noninst_'+status).style.display = 'inline';
 7663:                     }
 7664:                     break;
 7665:                 }
 7666:             }
 7667:         }
 7668:     }
 7669: }
 7670: 
 7671: // ]]>
 7672: </script>
 7673: 
 7674: ENDSCRIPT
 7675: }
 7676: 
 7677: sub noninst_users {
 7678:     my ($processing,$emailverified,$emailoptions,$emaildomain,$emailrules,
 7679:         $emailruleorder,$settings,$type,$rowid,$typetitle,$css_class,$rowstyle,$intdom) = @_;
 7680:     my $class = 'LC_left_item';
 7681:     if ($css_class) {
 7682:         $css_class = ' class="'.$css_class.'"';
 7683:     }
 7684:     if ($rowid) {
 7685:         $rowid = ' id="'.$rowid.'"';
 7686:     }
 7687:     if ($rowstyle) {
 7688:         $rowstyle = ' style="'.$rowstyle.'"';
 7689:     }
 7690:     my ($output,$description);
 7691:     if ($type eq 'default') {
 7692:         $description = &mt('Requests for: [_1]',$typetitle);
 7693:     } else {
 7694:         $description = &mt('Requests for: [_1] (status self-reported)',$typetitle);
 7695:     }
 7696:     $output = '<tr'.$css_class.$rowid.$rowstyle.'>'.
 7697:               "<td>$description</td>\n".
 7698:               '<td class="'.$class.'" colspan="2">'.
 7699:               '<table><tr>';
 7700:     my %headers = &Apache::lonlocal::texthash(
 7701:               approve  => 'Processing',
 7702:               email    => 'E-mail',
 7703:               username => 'Username',
 7704:     );
 7705:     foreach my $item ('approve','email','username') {
 7706:         $output .= '<th>'.$headers{$item}.'</th>';
 7707:     }
 7708:     $output .= '</tr><tr>';
 7709:     foreach my $item ('approve','email','username') {
 7710:         $output .= '<td valign="top">';
 7711:         my (%choices,@options,$hashref,$defoption,$name,$onclick,$hascustom);
 7712:         if ($item eq 'approve') {
 7713:             %choices = &Apache::lonlocal::texthash (
 7714:                                                      automatic => 'Automatically approved',
 7715:                                                      approval  => 'Queued for approval',
 7716:                                                    );
 7717:             @options = ('automatic','approval');
 7718:             $hashref = $processing;
 7719:             $defoption = 'automatic';
 7720:             $name = 'cancreate_emailprocess_'.$type;
 7721:         } elsif ($item eq 'email') {
 7722:             %choices = &Apache::lonlocal::texthash (
 7723:                                                      any     => 'Any e-mail',
 7724:                                                      inst    => 'Institutional only',
 7725:                                                      noninst => 'Non-institutional only',
 7726:                                                      custom  => 'Custom restrictions',
 7727:                                                    );
 7728:             @options = ('any','inst','noninst');
 7729:             my $showcustom;
 7730:             if (ref($emailrules) eq 'HASH') {
 7731:                 if (keys(%{$emailrules}) > 0) {
 7732:                     push(@options,'custom');
 7733:                     $showcustom = 'cancreate_emailrule';
 7734:                     if (ref($settings) eq 'HASH') {
 7735:                         if (ref($settings->{'email_rule'}) eq 'ARRAY') {
 7736:                             foreach my $rule (@{$settings->{'email_rule'}}) {
 7737:                                 if (exists($emailrules->{$rule})) {
 7738:                                     $hascustom ++;
 7739:                                 }
 7740:                             }
 7741:                         } elsif (ref($settings->{'email_rule'}) eq 'HASH') {
 7742:                             if (ref($settings->{'email_rule'}{$type}) eq 'ARRAY') {
 7743:                                 foreach my $rule (@{$settings->{'email_rule'}{$type}}) {
 7744:                                     if (exists($emailrules->{$rule})) {
 7745:                                         $hascustom ++;
 7746:                                     }
 7747:                                 }
 7748:                             }
 7749:                         }
 7750:                     }
 7751:                 }
 7752:             }
 7753:             $onclick = ' onclick="toggleEmailOptions(this.form,'."'cancreate_emailoptions','$showcustom',".
 7754:                                                      "'cancreate_emaildomain','$type'".');"';
 7755:             $hashref = $emailoptions;
 7756:             $defoption = 'any';
 7757:             $name = 'cancreate_emailoptions_'.$type;
 7758:         } elsif ($item eq 'username') {
 7759:             %choices = &Apache::lonlocal::texthash (
 7760:                                                      all    => 'Same as e-mail',
 7761:                                                      first  => 'Omit @domain',
 7762:                                                      free   => 'Free to choose',
 7763:                                                    );
 7764:             @options = ('all','first','free');
 7765:             $hashref = $emailverified;
 7766:             $defoption = 'all';
 7767:             $name = 'cancreate_usernameoptions_'.$type;
 7768:         }
 7769:         foreach my $option (@options) {
 7770:             my $checked;
 7771:             if (ref($hashref) eq 'HASH') {
 7772:                 if ($type eq '') {
 7773:                     if (!exists($hashref->{'default'})) {
 7774:                         if ($option eq $defoption) {
 7775:                             $checked = ' checked="checked"';
 7776:                         }
 7777:                     } else {
 7778:                         if ($hashref->{'default'} eq $option) {
 7779:                             $checked = ' checked="checked"';
 7780:                         }
 7781:                     }
 7782:                 } else {
 7783:                     if (!exists($hashref->{$type})) {
 7784:                         if ($option eq $defoption) {
 7785:                             $checked = ' checked="checked"';
 7786:                         }
 7787:                     } else {
 7788:                         if ($hashref->{$type} eq $option) {
 7789:                             $checked = ' checked="checked"';
 7790:                         }
 7791:                     }
 7792:                 }
 7793:             } elsif (($item eq 'email') && ($hascustom)) {
 7794:                 if ($option eq 'custom') {
 7795:                     $checked = ' checked="checked"';
 7796:                 }
 7797:             } elsif ($option eq $defoption) {
 7798:                 $checked = ' checked="checked"';
 7799:             }
 7800:             $output .= '<span class="LC_nobreak"><label>'.
 7801:                        '<input type="radio" name="'.$name.'"'.
 7802:                        $checked.' value="'.$option.'"'.$onclick.' />'.
 7803:                        $choices{$option}.'</label></span><br />';
 7804:             if ($item eq 'email') {
 7805:                 if ($option eq 'custom') {
 7806:                     my $id = 'cancreate_emailrule_'.$type;
 7807:                     my $display = 'none';
 7808:                     if ($checked) {
 7809:                         $display = 'inline';
 7810:                     }
 7811:                     my $numinrow = 2;
 7812:                     $output .= '<fieldset id="'.$id.'" style="display:'.$display.';">'.
 7813:                                '<legend>'.&mt('Disallow').'</legend><table>'.
 7814:                                &user_formats_row('email',$settings,$emailrules,
 7815:                                                  $emailruleorder,$numinrow,'',$type);
 7816:                               '</table></fieldset>';
 7817:                 } elsif (($option eq 'inst') || ($option eq 'noninst')) {
 7818:                     my %text = &Apache::lonlocal::texthash (
 7819:                                                              inst    => 'must end:',
 7820:                                                              noninst => 'cannot end:',
 7821:                                                            );
 7822:                     my $value;
 7823:                     if (ref($emaildomain) eq 'HASH') {
 7824:                         if (ref($emaildomain->{$type}) eq 'HASH') {
 7825:                             $value = $emaildomain->{$type}->{$option};
 7826:                         }
 7827:                     }
 7828:                     if ($value eq '') {
 7829:                         $value = '@'.$intdom;
 7830:                     }
 7831:                     my $condition = 'cancreate_emaildomain_'.$option.'_'.$type;
 7832:                     my $display = 'none';
 7833:                     if ($checked) {
 7834:                         $display = 'inline';
 7835:                     }
 7836:                     $output .= '<div id="'.$condition.'" style="display:'.$display.';">'.
 7837:                                '<span class="LC_domprefs_email">'.$text{$option}.'</span> '.
 7838:                                '<input type="text" name="'.$condition.'" value="'.$value.'" size="10" />'.
 7839:                                '</div>';
 7840:                 }
 7841:             }
 7842:         }
 7843:         $output .= '</td>'."\n";
 7844:     }
 7845:     $output .= "</tr></table></td></tr>\n";
 7846:     return $output;
 7847: }
 7848: 
 7849: sub captcha_choice {
 7850:     my ($context,$settings,$itemcount,$customcss,$rowstyle) = @_;
 7851:     my ($keyentry,$currpub,$currpriv,%checked,$rowname,$pubtext,$privtext,
 7852:         $vertext,$currver); 
 7853:     my %lt = &captcha_phrases();
 7854:     $keyentry = 'hidden';
 7855:     my $colspan=2;
 7856:     if ($context eq 'cancreate') {
 7857:         $rowname = &mt('CAPTCHA validation');
 7858:     } elsif ($context eq 'login') {
 7859:         $rowname =  &mt('"Contact helpdesk" CAPTCHA validation');
 7860:     } elsif ($context eq 'passwords') {
 7861:         $rowname = &mt('"Forgot Password" CAPTCHA validation');
 7862:         $colspan=1;
 7863:     }
 7864:     if (ref($settings) eq 'HASH') {
 7865:         if ($settings->{'captcha'}) {
 7866:             $checked{$settings->{'captcha'}} = ' checked="checked"';
 7867:         } else {
 7868:             $checked{'original'} = ' checked="checked"';
 7869:         }
 7870:         if ($settings->{'captcha'} eq 'recaptcha') {
 7871:             $pubtext = $lt{'pub'};
 7872:             $privtext = $lt{'priv'};
 7873:             $keyentry = 'text';
 7874:             $vertext = $lt{'ver'};
 7875:             $currver = $settings->{'recaptchaversion'};
 7876:             if ($currver ne '2') {
 7877:                 $currver = 1;
 7878:             }
 7879:         }
 7880:         if (ref($settings->{'recaptchakeys'}) eq 'HASH') {
 7881:             $currpub = $settings->{'recaptchakeys'}{'public'};
 7882:             $currpriv = $settings->{'recaptchakeys'}{'private'};
 7883:         }
 7884:     } else {
 7885:         $checked{'original'} = ' checked="checked"';
 7886:     }
 7887:     my $css_class;
 7888:     if ($itemcount%2) {
 7889:         $css_class = 'LC_odd_row';
 7890:     }
 7891:     if ($customcss) {
 7892:         $css_class .= " $customcss";
 7893:     }
 7894:     $css_class =~ s/^\s+//;
 7895:     if ($css_class) {
 7896:         $css_class = ' class="'.$css_class.'"';
 7897:     }
 7898:     if ($rowstyle) {
 7899:         $css_class .= ' style="'.$rowstyle.'"';
 7900:     }
 7901:     my $output = '<tr'.$css_class.'>'.
 7902:                  '<td class="LC_left_item">'.$rowname.'</td><td class="LC_left_item" colspan="'.$colspan.'">'."\n".
 7903:                  '<table><tr><td>'."\n";
 7904:     foreach my $option ('original','recaptcha','notused') {
 7905:         $output .= '<span class="LC_nobreak"><label><input type="radio" name="'.$context.'_captcha" value="'.
 7906:                    $option.'" '.$checked{$option}.' onchange="javascript:updateCaptcha('."this,'$context'".');" />'.
 7907:                    $lt{$option}.'</label></span>';
 7908:         unless ($option eq 'notused') {
 7909:             $output .= ('&nbsp;'x2)."\n";
 7910:         }
 7911:     }
 7912: #
 7913: # Note: If reCAPTCHA is to be used for LON-CAPA servers in a domain, a domain coordinator should visit:
 7914: # https://www.google.com/recaptcha and generate a Public and Private key. For domains with multiple
 7915: # servers a single key pair will be used for all servers, so the internet domain (e.g., yourcollege.edu)
 7916: # specified for use with the key should be broad enough to accommodate all servers in the LON-CAPA domain.
 7917: #
 7918:     $output .= '</td></tr>'."\n".
 7919:                '<tr><td class="LC_zero_height">'."\n".
 7920:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchapubtxt">'.$pubtext.'</span>&nbsp;'."\n".
 7921:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapub" name="'.$context.'_recaptchapub" value="'.
 7922:                $currpub.'" size="40" /></span><br />'."\n".
 7923:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchaprivtxt">'.$privtext.'</span>&nbsp;'."\n".
 7924:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapriv" name="'.$context.'_recaptchapriv" value="'.
 7925:                $currpriv.'" size="40" /></span><br />'.
 7926:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchavertxt">'.$vertext.'</span>&nbsp;'."\n".
 7927:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchaversion" name="'.$context.'_recaptchaversion" value="'.
 7928:                $currver.'" size="3" /></span><br />'.
 7929:                '</td></tr></table>'."\n".
 7930:                '</td></tr>';
 7931:     return $output;
 7932: }
 7933: 
 7934: sub user_formats_row {
 7935:     my ($type,$settings,$rules,$ruleorder,$numinrow,$rowcount,$status) = @_;
 7936:     my $output;
 7937:     my %text = (
 7938:                    'username' => 'new usernames',
 7939:                    'id'       => 'IDs',
 7940:                );
 7941:     unless ($type eq 'email') {
 7942:         my $css_class = $rowcount%2?' class="LC_odd_row"':'';
 7943:         $output = '<tr '.$css_class.'>'.
 7944:                   '<td><span class="LC_nobreak">'.
 7945:                   &mt("Format rules to check for $text{$type}: ").
 7946:                   '</td><td class="LC_left_item" colspan="2"><table>';
 7947:     }
 7948:     my $rem;
 7949:     if (ref($ruleorder) eq 'ARRAY') {
 7950:         for (my $i=0; $i<@{$ruleorder}; $i++) {
 7951:             if (ref($rules->{$ruleorder->[$i]}) eq 'HASH') {
 7952:                 my $rem = $i%($numinrow);
 7953:                 if ($rem == 0) {
 7954:                     if ($i > 0) {
 7955:                         $output .= '</tr>';
 7956:                     }
 7957:                     $output .= '<tr>';
 7958:                 }
 7959:                 my $check = ' ';
 7960:                 if (ref($settings) eq 'HASH') {
 7961:                     if (ref($settings->{$type.'_rule'}) eq 'ARRAY') {
 7962:                         if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}})) {
 7963:                             $check = ' checked="checked" ';
 7964:                         }
 7965:                     } elsif ((ref($settings->{$type.'_rule'}) eq 'HASH') && ($status ne '')) {
 7966:                         if (ref($settings->{$type.'_rule'}->{$status}) eq 'ARRAY') {
 7967:                             if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}->{$status}})) {
 7968:                                 $check = ' checked="checked" ';
 7969:                             }
 7970:                         }
 7971:                     }
 7972:                 }
 7973:                 my $name = $type.'_rule';
 7974:                 if ($type eq 'email') {
 7975:                     $name .= '_'.$status;
 7976:                 }
 7977:                 $output .= '<td class="LC_left_item">'.
 7978:                            '<span class="LC_nobreak"><label>'.
 7979:                            '<input type="checkbox" name="'.$name.'" '.
 7980:                            'value="'.$ruleorder->[$i].'"'.$check.'/>'.
 7981:                            $rules->{$ruleorder->[$i]}{'name'}.'</label></span></td>';
 7982:             }
 7983:         }
 7984:         $rem = @{$ruleorder}%($numinrow);
 7985:     }
 7986:     my $colsleft;
 7987:     if ($rem) {
 7988:         $colsleft = $numinrow - $rem;
 7989:     }
 7990:     if ($colsleft > 1 ) {
 7991:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 7992:                    '&nbsp;</td>';
 7993:     } elsif ($colsleft == 1) {
 7994:         $output .= '<td class="LC_left_item">&nbsp;</td>';
 7995:     }
 7996:     $output .= '</tr></table>';
 7997:     unless ($type eq 'email') {
 7998:         $output .= '</td></tr>';
 7999:     }
 8000:     return $output;
 8001: }
 8002: 
 8003: sub usercreation_types {
 8004:     my %lt = &Apache::lonlocal::texthash (
 8005:                     author     => 'When adding a co-author',
 8006:                     course     => 'When adding a user to a course',
 8007:                     requestcrs => 'When requesting a course',
 8008:                     any        => 'Any',
 8009:                     official   => 'Institutional only ',
 8010:                     unofficial => 'Non-institutional only',
 8011:                     none       => 'None',
 8012:     );
 8013:     return %lt;
 8014: }
 8015: 
 8016: sub selfcreation_types {
 8017:     my %lt = &Apache::lonlocal::texthash (
 8018:                     selfcreate => 'User creates own account',
 8019:                     any        => 'Any',
 8020:                     official   => 'Institutional only ',
 8021:                     unofficial => 'Non-institutional only',
 8022:                     email      => 'E-mail address',
 8023:                     login      => 'Institutional Login',
 8024:                     sso        => 'SSO',
 8025:              );
 8026: }
 8027: 
 8028: sub authtype_names {
 8029:     my %lt = &Apache::lonlocal::texthash(
 8030:                       int    => 'Internal',
 8031:                       krb4   => 'Kerberos 4',
 8032:                       krb5   => 'Kerberos 5',
 8033:                       loc    => 'Local',
 8034:                   );
 8035:     return %lt;
 8036: }
 8037: 
 8038: sub context_names {
 8039:     my %context_title = &Apache::lonlocal::texthash(
 8040:        author => 'Creating users when an Author',
 8041:        course => 'Creating users when in a course',
 8042:        domain => 'Creating users when a Domain Coordinator',
 8043:     );
 8044:     return %context_title;
 8045: }
 8046: 
 8047: sub print_usermodification {
 8048:     my ($position,$dom,$settings,$rowtotal) = @_;
 8049:     my $numinrow = 4;
 8050:     my ($context,$datatable,$rowcount);
 8051:     if ($position eq 'top') {
 8052:         $rowcount = 0;
 8053:         $context = 'author'; 
 8054:         foreach my $role ('ca','aa') {
 8055:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
 8056:                                                    $numinrow,$rowcount);
 8057:             $$rowtotal ++;
 8058:             $rowcount ++;
 8059:         }
 8060:     } elsif ($position eq 'bottom') {
 8061:         $context = 'course';
 8062:         $rowcount = 0;
 8063:         foreach my $role ('st','ep','ta','in','cr') {
 8064:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
 8065:                                                    $numinrow,$rowcount);
 8066:             $$rowtotal ++;
 8067:             $rowcount ++;
 8068:         }
 8069:     }
 8070:     return $datatable;
 8071: }
 8072: 
 8073: sub print_defaults {
 8074:     my ($position,$dom,$settings,$rowtotal) = @_;
 8075:     my $rownum = 0;
 8076:     my ($datatable,$css_class,$titles);
 8077:     unless ($position eq 'bottom') {
 8078:         $titles = &defaults_titles($dom);
 8079:     }
 8080:     if ($position eq 'top') {
 8081:         my @items = ('auth_def','auth_arg_def','lang_def','timezone_def',
 8082:                      'datelocale_def','portal_def');
 8083:         my %defaults;
 8084:         if (ref($settings) eq 'HASH') {
 8085:             %defaults = %{$settings};
 8086:         } else {
 8087:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
 8088:             foreach my $item (@items) {
 8089:                 $defaults{$item} = $domdefaults{$item};
 8090:             }
 8091:         }
 8092:         foreach my $item (@items) {
 8093:             if ($rownum%2) {
 8094:                 $css_class = '';
 8095:             } else {
 8096:                 $css_class = ' class="LC_odd_row" ';
 8097:             }
 8098:             $datatable .= '<tr'.$css_class.'>'.
 8099:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
 8100:                           '</span></td><td class="LC_right_item" colspan="3">';
 8101:             if ($item eq 'auth_def') {
 8102:                 my @authtypes = ('internal','krb4','krb5','localauth');
 8103:                 my %shortauth = (
 8104:                                  internal => 'int',
 8105:                                  krb4 => 'krb4',
 8106:                                  krb5 => 'krb5',
 8107:                                  localauth  => 'loc'
 8108:                                 );
 8109:                 my %authnames = &authtype_names();
 8110:                 foreach my $auth (@authtypes) {
 8111:                     my $checked = ' ';
 8112:                     if ($defaults{$item} eq $auth) {
 8113:                         $checked = ' checked="checked" ';
 8114:                     }
 8115:                     $datatable .= '<label><input type="radio" name="'.$item.
 8116:                                   '" value="'.$auth.'"'.$checked.'/>'.
 8117:                                   $authnames{$shortauth{$auth}}.'</label>&nbsp;&nbsp;';
 8118:                 }
 8119:             } elsif ($item eq 'timezone_def') {
 8120:                 my $includeempty = 1;
 8121:                 $datatable .= &Apache::loncommon::select_timezone($item,$defaults{$item},undef,$includeempty);
 8122:             } elsif ($item eq 'datelocale_def') {
 8123:                 my $includeempty = 1;
 8124:                 $datatable .= &Apache::loncommon::select_datelocale($item,$defaults{$item},undef,$includeempty);
 8125:             } elsif ($item eq 'lang_def') {
 8126:                 my $includeempty = 1;
 8127:                 $datatable .= &Apache::loncommon::select_language($item,$defaults{$item},$includeempty);
 8128:             } else {
 8129:                 my $size;
 8130:                 if ($item eq 'portal_def') {
 8131:                     $size = ' size="25"';
 8132:                 }
 8133:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
 8134:                               $defaults{$item}.'"'.$size.' />';
 8135:             }
 8136:             $datatable .= '</td></tr>';
 8137:             $rownum ++;
 8138:         }
 8139:     } else {
 8140:         my %defaults;
 8141:         if (ref($settings) eq 'HASH') {
 8142:             if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
 8143:                 my $maxnum = @{$settings->{'inststatusorder'}};
 8144:                 for (my $i=0; $i<$maxnum; $i++) {
 8145:                     $css_class = $rownum%2?' class="LC_odd_row"':'';
 8146:                     my $item = $settings->{'inststatusorder'}->[$i];
 8147:                     my $title = $settings->{'inststatustypes'}->{$item};
 8148:                     my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'$item'".');"';
 8149:                     $datatable .= '<tr'.$css_class.'>'.
 8150:                                   '<td><span class="LC_nobreak">'.
 8151:                                   '<select name="inststatus_pos_'.$item.'"'.$chgstr.'>';
 8152:                     for (my $k=0; $k<=$maxnum; $k++) {
 8153:                         my $vpos = $k+1;
 8154:                         my $selstr;
 8155:                         if ($k == $i) {
 8156:                             $selstr = ' selected="selected" ';
 8157:                         }
 8158:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 8159:                     }
 8160:                     $datatable .= '</select>&nbsp;'.&mt('Internal ID:').'&nbsp;<b>'.$item.'</b>&nbsp;'.
 8161:                                   '<input type="checkbox" name="inststatus_delete" value="'.$item.'" />'.
 8162:                                   &mt('delete').'</span></td>'.
 8163:                                   '<td class="LC_left_item"><span class="LC_nobreak">'.&mt('Name displayed').':'.
 8164:                                   '<input type="text" size="20" name="inststatus_title_'.$item.'" value="'.$title.'" />'.
 8165:                                   '</span></td></tr>';
 8166:                 }
 8167:                 $css_class = $rownum%2?' class="LC_odd_row"':'';
 8168:                 my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'addinststatus_pos'".');"';
 8169:                 $datatable .= '<tr '.$css_class.'>'.
 8170:                               '<td><span class="LC_nobreak"><select name="addinststatus_pos"'.$chgstr.'>';
 8171:                 for (my $k=0; $k<=$maxnum; $k++) {
 8172:                     my $vpos = $k+1;
 8173:                     my $selstr;
 8174:                     if ($k == $maxnum) {
 8175:                         $selstr = ' selected="selected" ';
 8176:                     }
 8177:                     $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 8178:                 }
 8179:                 $datatable .= '</select>&nbsp;'.&mt('Internal ID:').
 8180:                               '<input type="text" size="10" name="addinststatus" value="" />'.
 8181:                               '&nbsp;'.&mt('(new)').
 8182:                               '</span></td><td class="LC_left_item"><span class="LC_nobreak">'.
 8183:                               &mt('Name displayed').':'.
 8184:                               '<input type="text" size="20" name="addinststatus_title" value="" /></span></td>'.
 8185:                               '</tr>'."\n";
 8186:                 $rownum ++;
 8187:             }
 8188:         }
 8189:     }
 8190:     $$rowtotal += $rownum;
 8191:     return $datatable;
 8192: }
 8193: 
 8194: sub get_languages_hash {
 8195:     my %langchoices;
 8196:     foreach my $id (&Apache::loncommon::languageids()) {
 8197:         my $code = &Apache::loncommon::supportedlanguagecode($id);
 8198:         if ($code ne '') {
 8199:             $langchoices{$code} =  &Apache::loncommon::plainlanguagedescription($id);
 8200:         }
 8201:     }
 8202:     return %langchoices;
 8203: }
 8204: 
 8205: sub defaults_titles {
 8206:     my ($dom) = @_;
 8207:     my %titles = &Apache::lonlocal::texthash (
 8208:                    'auth_def'      => 'Default authentication type',
 8209:                    'auth_arg_def'  => 'Default authentication argument',
 8210:                    'lang_def'      => 'Default language',
 8211:                    'timezone_def'  => 'Default timezone',
 8212:                    'datelocale_def' => 'Default locale for dates',
 8213:                    'portal_def'     => 'Portal/Default URL',
 8214:                    'intauth_cost'   => 'Encryption cost for bcrypt (positive integer)',
 8215:                    'intauth_check'  => 'Check bcrypt cost if authenticated',
 8216:                    'intauth_switch' => 'Existing crypt-based switched to bcrypt on authentication',
 8217:                  );
 8218:     if ($dom) {
 8219:         my $uprimary_id = &Apache::lonnet::domain($dom,'primary');
 8220:         my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 8221:         my $protocol = $Apache::lonnet::protocol{$uprimary_id};
 8222:         $protocol = 'http' if ($protocol ne 'https');
 8223:         if ($uint_dom) {
 8224:             $titles{'portal_def'} .= ' '.&mt('(for example: [_1])',$protocol.'://loncapa.'.
 8225:                                          $uint_dom);
 8226:         }
 8227:     }
 8228:     return (\%titles);
 8229: }
 8230: 
 8231: sub print_scantron {
 8232:     my ($r,$position,$dom,$confname,$settings,$rowtotal) = @_;
 8233:     if ($position eq 'top') {
 8234:         return &print_scantronformat($r,$dom,$confname,$settings,\$rowtotal);
 8235:     } else {
 8236:         return &print_scantronconfig($dom,$settings,\$rowtotal);
 8237:     }
 8238: }
 8239: 
 8240: sub scantron_javascript {
 8241:     return <<"ENDSCRIPT";
 8242: 
 8243: <script type="text/javascript">
 8244: // <![CDATA[
 8245: 
 8246: function toggleScantron(form) {
 8247:     var csvfieldset = new Array();
 8248:     if (document.getElementById('scantroncsv_cols')) {
 8249:         csvfieldset.push(document.getElementById('scantroncsv_cols'));
 8250:     }
 8251:     if (document.getElementById('scantroncsv_options')) {
 8252:         csvfieldset.push(document.getElementById('scantroncsv_options'));
 8253:     }
 8254:     if (csvfieldset.length) {
 8255:         if (document.getElementById('scantronconfcsv')) {
 8256:             var scantroncsv = document.getElementById('scantronconfcsv');
 8257:             if (scantroncsv.checked) {
 8258:                 for (var i=0; i<csvfieldset.length; i++) {
 8259:                     csvfieldset[i].style.display = 'block';
 8260:                 }
 8261:             } else {
 8262:                 for (var i=0; i<csvfieldset.length; i++) {
 8263:                     csvfieldset[i].style.display = 'none';
 8264:                 }
 8265:                 var csvselects = document.getElementsByClassName('scantronconfig_csv');
 8266:                 if (csvselects.length) {
 8267:                     for (var j=0; j<csvselects.length; j++) {
 8268:                         csvselects[j].selectedIndex = 0;
 8269:                     }
 8270:                 }
 8271:             }
 8272:         }
 8273:     }
 8274:     return;
 8275: }
 8276: // ]]>
 8277: </script>
 8278: 
 8279: ENDSCRIPT
 8280: 
 8281: }
 8282: 
 8283: sub print_scantronformat {
 8284:     my ($r,$dom,$confname,$settings,$rowtotal) = @_;
 8285:     my $itemcount = 1;
 8286:     my ($datatable,$css_class,$scantronurl,$is_custom,%error,%scantronurls,
 8287:         %confhash);
 8288:     my $switchserver = &check_switchserver($dom,$confname);
 8289:     my %lt = &Apache::lonlocal::texthash (
 8290:                 default => 'Default bubblesheet format file error',
 8291:                 custom  => 'Custom bubblesheet format file error',
 8292:              );
 8293:     my %scantronfiles = (
 8294:         default => 'default.tab',
 8295:         custom => 'custom.tab',
 8296:     );
 8297:     foreach my $key (keys(%scantronfiles)) {
 8298:         $scantronurls{$key} = '/res/'.$dom.'/'.$confname.'/scantron/'
 8299:                               .$scantronfiles{$key};
 8300:     }
 8301:     my @defaultinfo = &Apache::lonnet::stat_file($scantronurls{'default'});
 8302:     if ((!@defaultinfo) || ($defaultinfo[0] eq 'no_such_dir')) {
 8303:         if (!$switchserver) {
 8304:             my $servadm = $r->dir_config('lonAdmEMail');
 8305:             my ($configuserok,$author_ok) = &config_check($dom,$confname,$servadm);
 8306:             if ($configuserok eq 'ok') {
 8307:                 if ($author_ok eq 'ok') {
 8308:                     my %legacyfile = (
 8309:  default => $Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab',
 8310:  custom  => $Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab',
 8311:                     );
 8312:                     my %md5chk;
 8313:                     foreach my $type (keys(%legacyfile)) {
 8314:                         ($md5chk{$type}) = split(/ /,`md5sum $legacyfile{$type}`);
 8315:                         chomp($md5chk{$type});
 8316:                     }
 8317:                     if ($md5chk{'default'} ne $md5chk{'custom'}) {
 8318:                         foreach my $type (keys(%legacyfile)) {
 8319:                             ($scantronurls{$type},my $error) =
 8320:                                 &legacy_scantronformat($r,$dom,$confname,
 8321:                                                  $type,$legacyfile{$type},
 8322:                                                  $scantronurls{$type},
 8323:                                                  $scantronfiles{$type});
 8324:                             if ($error ne '') {
 8325:                                 $error{$type} = $error;
 8326:                             }
 8327:                         }
 8328:                         if (keys(%error) == 0) {
 8329:                             $is_custom = 1;
 8330:                             $confhash{'scantron'}{'scantronformat'} =
 8331:                                 $scantronurls{'custom'};
 8332:                             my $putresult =
 8333:                                 &Apache::lonnet::put_dom('configuration',
 8334:                                                          \%confhash,$dom);
 8335:                             if ($putresult ne 'ok') {
 8336:                                 $error{'custom'} =
 8337:                                     '<span class="LC_error">'.
 8338:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
 8339:                             }
 8340:                         }
 8341:                     } else {
 8342:                         ($scantronurls{'default'},my $error) =
 8343:                             &legacy_scantronformat($r,$dom,$confname,
 8344:                                           'default',$legacyfile{'default'},
 8345:                                           $scantronurls{'default'},
 8346:                                           $scantronfiles{'default'});
 8347:                         if ($error eq '') {
 8348:                             $confhash{'scantron'}{'scantronformat'} = ''; 
 8349:                             my $putresult =
 8350:                                 &Apache::lonnet::put_dom('configuration',
 8351:                                                          \%confhash,$dom);
 8352:                             if ($putresult ne 'ok') {
 8353:                                 $error{'default'} =
 8354:                                     '<span class="LC_error">'.
 8355:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
 8356:                             }
 8357:                         } else {
 8358:                             $error{'default'} = $error;
 8359:                         }
 8360:                     }
 8361:                 }
 8362:             }
 8363:         } else {
 8364:             $error{'default'} = &mt("Unable to copy default bubblesheet formatfile to domain's RES space: [_1]",$switchserver);
 8365:         }
 8366:     }
 8367:     if (ref($settings) eq 'HASH') {
 8368:         if ($settings->{'scantronformat'} eq "/res/$dom/$confname/scantron/custom.tab") {
 8369:             my @info = &Apache::lonnet::stat_file($settings->{'scantronformat'});
 8370:             if ((!@info) || ($info[0] eq 'no_such_dir')) {
 8371:                 $scantronurl = '';
 8372:             } else {
 8373:                 $scantronurl = $settings->{'scantronformat'};
 8374:             }
 8375:             $is_custom = 1;
 8376:         } else {
 8377:             $scantronurl = $scantronurls{'default'};
 8378:         }
 8379:     } else {
 8380:         if ($is_custom) {
 8381:             $scantronurl = $scantronurls{'custom'};
 8382:         } else {
 8383:             $scantronurl = $scantronurls{'default'};
 8384:         }
 8385:     }
 8386:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8387:     $datatable .= '<tr'.$css_class.'>';
 8388:     if (!$is_custom) {
 8389:         $datatable .= '<td>'.&mt('Default in use:').'<br />'.
 8390:                       '<span class="LC_nobreak">';
 8391:         if ($scantronurl) {
 8392:             $datatable .= &Apache::loncommon::modal_link($scantronurl,&mt('Default bubblesheet format file'),600,500,
 8393:                                                          undef,undef,undef,undef,'background-color:#ffffff');
 8394:         } else {
 8395:             $datatable = &mt('File unavailable for display');
 8396:         }
 8397:         $datatable .= '</span></td>';
 8398:         if (keys(%error) == 0) { 
 8399:             $datatable .= '<td valign="bottom">';
 8400:             if (!$switchserver) {
 8401:                 $datatable .= &mt('Upload:').'<br />';
 8402:             }
 8403:         } else {
 8404:             my $errorstr;
 8405:             foreach my $key (sort(keys(%error))) {
 8406:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
 8407:             }
 8408:             $datatable .= '<td>'.$errorstr;
 8409:         }
 8410:     } else {
 8411:         if (keys(%error) > 0) {
 8412:             my $errorstr;
 8413:             foreach my $key (sort(keys(%error))) {
 8414:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
 8415:             } 
 8416:             $datatable .= '<td>'.$errorstr.'</td><td>&nbsp;';
 8417:         } elsif ($scantronurl) {
 8418:             my $link =  &Apache::loncommon::modal_link($scantronurl,&mt('Custom bubblesheet format file'),600,500,
 8419:                                                        undef,undef,undef,undef,'background-color:#ffffff');
 8420:             $datatable .= '<td><span class="LC_nobreak">'.
 8421:                           $link.
 8422:                           '<label><input type="checkbox" name="scantronformat_del"'.
 8423:                           ' value="1" />'.&mt('Delete?').'</label></span></td>'.
 8424:                           '<td><span class="LC_nobreak">&nbsp;'.
 8425:                           &mt('Replace:').'</span><br />';
 8426:         }
 8427:     }
 8428:     if (keys(%error) == 0) {
 8429:         if ($switchserver) {
 8430:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 8431:         } else {
 8432:             $datatable .='<span class="LC_nobreak">&nbsp;'.
 8433:                          '<input type="file" name="scantronformat" /></span>';
 8434:         }
 8435:     }
 8436:     $datatable .= '</td></tr>';
 8437:     $$rowtotal ++;
 8438:     return $datatable;
 8439: }
 8440: 
 8441: sub legacy_scantronformat {
 8442:     my ($r,$dom,$confname,$file,$legacyfile,$newurl,$newfile) = @_;
 8443:     my ($url,$error);
 8444:     my @statinfo = &Apache::lonnet::stat_file($newurl);
 8445:     if ((!@statinfo) || ($statinfo[0] eq 'no_such_dir')) {
 8446:         (my $result,$url) =
 8447:             &publishlogo($r,'copy',$legacyfile,$dom,$confname,'scantron',
 8448:                          '','',$newfile);
 8449:         if ($result ne 'ok') {
 8450:             $error = &mt("An error occurred publishing the [_1] bubblesheet format file in RES space. Error was: [_2].",$newfile,$result);
 8451:         }
 8452:     }
 8453:     return ($url,$error);
 8454: }
 8455: 
 8456: sub print_scantronconfig {
 8457:     my ($dom,$settings,$rowtotal) = @_;
 8458:     my $itemcount = 2;
 8459:     my $is_checked = ' checked="checked"';
 8460:     my %optionson = (
 8461:                      hdr => ' checked="checked"',
 8462:                      pad => ' checked="checked"',
 8463:                      rem => ' checked="checked"',
 8464:                     );
 8465:     my %optionsoff = (
 8466:                       hdr => '',
 8467:                       pad => '',
 8468:                       rem => '',
 8469:                      );
 8470:     my $currcsvsty = 'none';
 8471:     my ($datatable,%csvfields,%checked,%onclick,%csvoptions);
 8472:     my @fields = &scantroncsv_fields();
 8473:     my %titles = &scantronconfig_titles();
 8474:     if (ref($settings) eq 'HASH') {
 8475:         if (ref($settings->{config}) eq 'HASH') {
 8476:             if ($settings->{config}->{dat}) {
 8477:                 $checked{'dat'} = $is_checked;
 8478:             }
 8479:             if (ref($settings->{config}->{csv}) eq 'HASH') {
 8480:                 if (ref($settings->{config}->{csv}->{fields}) eq 'HASH') {
 8481:                     %csvfields = %{$settings->{config}->{csv}->{fields}};
 8482:                     if (keys(%csvfields) > 0) {
 8483:                         $checked{'csv'} = $is_checked;
 8484:                         $currcsvsty = 'block';
 8485:                     }
 8486:                 }
 8487:                 if (ref($settings->{config}->{csv}->{options}) eq 'HASH') {
 8488:                     %csvoptions = %{$settings->{config}->{csv}->{options}};
 8489:                     foreach my $option (keys(%optionson)) {
 8490:                         unless ($csvoptions{$option}) {
 8491:                             $optionsoff{$option} = $optionson{$option};
 8492:                             $optionson{$option} = '';
 8493:                         }
 8494:                     }
 8495:                 }
 8496:             }
 8497:         } else {
 8498:             $checked{'dat'} = $is_checked;
 8499:         }
 8500:     } else {
 8501:         $checked{'dat'} = $is_checked;
 8502:     }
 8503:     $onclick{'csv'} = ' onclick="toggleScantron(this.form);"';
 8504:     my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
 8505:     $datatable = '<tr '.$css_class.'><td>'.&mt('Supported formats').'</td>'.
 8506:                  '<td class="LC_left_item" valign="top"><span class="LC_nobreak">';
 8507:     foreach my $item ('dat','csv') {
 8508:         my $id;
 8509:         if ($item eq 'csv') {
 8510:             $id = 'id="scantronconfcsv" ';
 8511:         }
 8512:         $datatable .= '<label><input type="checkbox" name="scantronconfig" '.$id.'value="'.$item.'"'.$checked{$item}.$onclick{$item}.' />'.
 8513:                       $titles{$item}.'</label>'.('&nbsp;'x3);
 8514:         if ($item eq 'csv') {
 8515:             $datatable .= '<fieldset style="display:'.$currcsvsty.'" id="scantroncsv_cols">'.
 8516:                           '<legend>'.&mt('CSV Column Mapping').'</legend>'.
 8517:                           '<table><tr><th>'.&mt('Field').'</th><th>'.&mt('Location').'</th></tr>'."\n";
 8518:             foreach my $col (@fields) {
 8519:                 my $selnone;
 8520:                 if ($csvfields{$col} eq '') {
 8521:                     $selnone = ' selected="selected"';
 8522:                 }
 8523:                 $datatable .= '<tr><td>'.$titles{$col}.'</td>'.
 8524:                               '<td><select name="scantronconfig_csv_'.$col.'" class="scantronconfig_csv">'.
 8525:                               '<option value=""'.$selnone.'></option>';
 8526:                 for (my $i=0; $i<20; $i++) {
 8527:                     my $shown = $i+1;
 8528:                     my $sel;
 8529:                     unless ($selnone) {
 8530:                         if (exists($csvfields{$col})) {
 8531:                             if ($csvfields{$col} == $i) {
 8532:                                 $sel = ' selected="selected"';
 8533:                             }
 8534:                         }
 8535:                     }
 8536:                     $datatable .= '<option value="'.$i.'"'.$sel.'>'.$shown.'</option>';
 8537:                 }
 8538:                 $datatable .= '</select></td></tr>';
 8539:            }
 8540:            $datatable .= '</table></fieldset>'.
 8541:                          '<fieldset style="display:'.$currcsvsty.'" id="scantroncsv_options">'.
 8542:                          '<legend>'.&mt('CSV Options').'</legend>';
 8543:            foreach my $option ('hdr','pad','rem') {
 8544:                $datatable .= '<span class="LC_nobreak">'.$titles{$option}.':'.
 8545:                          '<label><input type="radio" name="scantroncsv_'.$option.'" value="1"'.$optionson{$option}.' />'.
 8546:                          &mt('Yes').'</label>'.('&nbsp;'x2)."\n".
 8547:                          '<label><input type="radio" name="scantroncsv_'.$option.'" value="0"'.$optionsoff{$option}.' />'.&mt('No').'</label></span><br />';
 8548:            }
 8549:            $datatable .= '</fieldset>';
 8550:            $itemcount ++;
 8551:         }
 8552:     }
 8553:     $datatable .= '</td></tr>';
 8554:     $$rowtotal ++;
 8555:     return $datatable;
 8556: }
 8557: 
 8558: sub scantronconfig_titles {
 8559:     return &Apache::lonlocal::texthash(
 8560:                                           dat => 'Standard format (.dat)',
 8561:                                           csv => 'Comma separated values (.csv)',
 8562:                                           hdr => 'Remove first line in file (contains column titles)',
 8563:                                           pad => 'Prepend 0s to PaperID',
 8564:                                           rem => 'Remove leading spaces (except Question Response columns)',
 8565:                                           CODE => 'CODE',
 8566:                                           ID   => 'Student ID',
 8567:                                           PaperID => 'Paper ID',
 8568:                                           FirstName => 'First Name',
 8569:                                           LastName => 'Last Name',
 8570:                                           FirstQuestion => 'First Question Response',
 8571:                                           Section => 'Section',
 8572:     );
 8573: }
 8574: 
 8575: sub scantroncsv_fields {
 8576:     return ('PaperID','LastName','FirstName','ID','Section','CODE','FirstQuestion');
 8577: }
 8578: 
 8579: sub print_coursecategories {
 8580:     my ($position,$dom,$hdritem,$settings,$rowtotal) = @_;
 8581:     my $datatable;
 8582:     if ($position eq 'top') {
 8583:         my (%checked);
 8584:         my @catitems = ('unauth','auth');
 8585:         my @cattypes = ('std','domonly','codesrch','none');
 8586:         $checked{'unauth'} = 'std';
 8587:         $checked{'auth'} = 'std';
 8588:         if (ref($settings) eq 'HASH') {
 8589:             foreach my $type (@cattypes) {
 8590:                 if ($type eq $settings->{'unauth'}) {
 8591:                     $checked{'unauth'} = $type;
 8592:                 }
 8593:                 if ($type eq $settings->{'auth'}) {
 8594:                     $checked{'auth'} = $type;
 8595:                 }
 8596:             }
 8597:         }
 8598:         my %lt = &Apache::lonlocal::texthash (
 8599:                                                unauth   => 'Catalog type for unauthenticated users',
 8600:                                                auth     => 'Catalog type for authenticated users',
 8601:                                                none     => 'No catalog',
 8602:                                                std      => 'Standard catalog',
 8603:                                                domonly  => 'Domain-only catalog',
 8604:                                                codesrch => "Code search form",
 8605:                                              );
 8606:        my $itemcount = 0;
 8607:        foreach my $item (@catitems) {
 8608:            my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
 8609:            $datatable .= '<tr '.$css_class.'>'.
 8610:                          '<td>'.$lt{$item}.'</td>'.
 8611:                          '<td class="LC_right_item"><span class="LC_nobreak">';
 8612:            foreach my $type (@cattypes) {
 8613:                my $ischecked;
 8614:                if ($checked{$item} eq $type) {
 8615:                    $ischecked=' checked="checked"';
 8616:                }
 8617:                $datatable .= '<label>'.
 8618:                              '<input type="radio" name="coursecat_'.$item.'" value="'.$type.'"'.$ischecked.
 8619:                              ' />'.$lt{$type}.'</label>&nbsp;';
 8620:            }
 8621:            $datatable .= '</span></td></tr>';
 8622:            $itemcount ++;
 8623:         }
 8624:         $$rowtotal += $itemcount;
 8625:     } elsif ($position eq 'middle') {
 8626:         my $toggle_cats_crs = ' ';
 8627:         my $toggle_cats_dom = ' checked="checked" ';
 8628:         my $can_cat_crs = ' ';
 8629:         my $can_cat_dom = ' checked="checked" ';
 8630:         my $toggle_catscomm_comm = ' ';
 8631:         my $toggle_catscomm_dom = ' checked="checked" ';
 8632:         my $can_catcomm_comm = ' ';
 8633:         my $can_catcomm_dom = ' checked="checked" ';
 8634: 
 8635:         if (ref($settings) eq 'HASH') {
 8636:             if ($settings->{'togglecats'} eq 'crs') {
 8637:                 $toggle_cats_crs = $toggle_cats_dom;
 8638:                 $toggle_cats_dom = ' ';
 8639:             }
 8640:             if ($settings->{'categorize'} eq 'crs') {
 8641:                 $can_cat_crs = $can_cat_dom;
 8642:                 $can_cat_dom = ' ';
 8643:             }
 8644:             if ($settings->{'togglecatscomm'} eq 'comm') {
 8645:                 $toggle_catscomm_comm = $toggle_catscomm_dom;
 8646:                 $toggle_catscomm_dom = ' ';
 8647:             }
 8648:             if ($settings->{'categorizecomm'} eq 'comm') {
 8649:                 $can_catcomm_comm = $can_catcomm_dom;
 8650:                 $can_catcomm_dom = ' ';
 8651:             }
 8652:         }
 8653:         my %title = &Apache::lonlocal::texthash (
 8654:                      togglecats     => 'Show/Hide a course in catalog',
 8655:                      togglecatscomm => 'Show/Hide a community in catalog',
 8656:                      categorize     => 'Assign a category to a course',
 8657:                      categorizecomm => 'Assign a category to a community',
 8658:                     );
 8659:         my %level = &Apache::lonlocal::texthash (
 8660:                      dom  => 'Set in Domain',
 8661:                      crs  => 'Set in Course',
 8662:                      comm => 'Set in Community',
 8663:                     );
 8664:         $datatable = '<tr class="LC_odd_row">'.
 8665:                   '<td>'.$title{'togglecats'}.'</td>'.
 8666:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 8667:                   '<input type="radio" name="togglecats"'.
 8668:                   $toggle_cats_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 8669:                   '<label><input type="radio" name="togglecats"'.
 8670:                   $toggle_cats_crs.' value="crs" />'.$level{'crs'}.'</label></span></td>'.
 8671:                   '</tr><tr>'.
 8672:                   '<td>'.$title{'categorize'}.'</td>'.
 8673:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 8674:                   '<label><input type="radio" name="categorize"'.
 8675:                   $can_cat_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 8676:                   '<label><input type="radio" name="categorize"'.
 8677:                   $can_cat_crs.'value="crs" />'.$level{'crs'}.'</label></span></td>'.
 8678:                   '</tr><tr class="LC_odd_row">'.
 8679:                   '<td>'.$title{'togglecatscomm'}.'</td>'.
 8680:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 8681:                   '<input type="radio" name="togglecatscomm"'.
 8682:                   $toggle_catscomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 8683:                   '<label><input type="radio" name="togglecatscomm"'.
 8684:                   $toggle_catscomm_comm.' value="comm" />'.$level{'comm'}.'</label></span></td>'.
 8685:                   '</tr><tr>'.
 8686:                   '<td>'.$title{'categorizecomm'}.'</td>'.
 8687:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 8688:                   '<label><input type="radio" name="categorizecomm"'.
 8689:                   $can_catcomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 8690:                   '<label><input type="radio" name="categorizecomm"'.
 8691:                   $can_catcomm_comm.'value="comm" />'.$level{'comm'}.'</label></span></td>'.
 8692:                   '</tr>';
 8693:         $$rowtotal += 4;
 8694:     } else {
 8695:         my $css_class;
 8696:         my $itemcount = 1;
 8697:         my $cathash; 
 8698:         if (ref($settings) eq 'HASH') {
 8699:             $cathash = $settings->{'cats'};
 8700:         }
 8701:         if (ref($cathash) eq 'HASH') {
 8702:             my (@cats,@trails,%allitems,%idx,@jsarray);
 8703:             &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,
 8704:                                                    \%allitems,\%idx,\@jsarray);
 8705:             my $maxdepth = scalar(@cats);
 8706:             my $colattrib = '';
 8707:             if ($maxdepth > 2) {
 8708:                 $colattrib = ' colspan="2" ';
 8709:             }
 8710:             my @path;
 8711:             if (@cats > 0) {
 8712:                 if (ref($cats[0]) eq 'ARRAY') {
 8713:                     my $numtop = @{$cats[0]};
 8714:                     my $maxnum = $numtop;
 8715:                     my %default_names = (
 8716:                           instcode    => &mt('Official courses'),
 8717:                           communities => &mt('Communities'),
 8718:                     );
 8719: 
 8720:                     if ((!grep(/^instcode$/,@{$cats[0]})) || 
 8721:                         ($cathash->{'instcode::0'} eq '') ||
 8722:                         (!grep(/^communities$/,@{$cats[0]})) || 
 8723:                         ($cathash->{'communities::0'} eq '')) {
 8724:                         $maxnum ++;
 8725:                     }
 8726:                     my $lastidx;
 8727:                     for (my $i=0; $i<$numtop; $i++) {
 8728:                         my $parent = $cats[0][$i];
 8729:                         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8730:                         my $item = &escape($parent).'::0';
 8731:                         my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$item','$idx{$item}'".');"';
 8732:                         $lastidx = $idx{$item};
 8733:                         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 8734:                                       .'<select name="'.$item.'"'.$chgstr.'>';
 8735:                         for (my $k=0; $k<=$maxnum; $k++) {
 8736:                             my $vpos = $k+1;
 8737:                             my $selstr;
 8738:                             if ($k == $i) {
 8739:                                 $selstr = ' selected="selected" ';
 8740:                             }
 8741:                             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 8742:                         }
 8743:                         $datatable .= '</select></span></td><td>';
 8744:                         if ($parent eq 'instcode' || $parent eq 'communities') {
 8745:                             $datatable .=  '<span class="LC_nobreak">'
 8746:                                            .$default_names{$parent}.'</span>';
 8747:                             if ($parent eq 'instcode') {
 8748:                                 $datatable .= '<br /><span class="LC_nobreak">('
 8749:                                               .&mt('with institutional codes')
 8750:                                               .')</span></td><td'.$colattrib.'>';
 8751:                             } else {
 8752:                                 $datatable .= '<table><tr><td>';
 8753:                             }
 8754:                             $datatable .= '<span class="LC_nobreak">'
 8755:                                           .'<label><input type="radio" name="'
 8756:                                           .$parent.'" value="1" checked="checked" />'
 8757:                                           .&mt('Display').'</label>';
 8758:                             if ($parent eq 'instcode') {
 8759:                                 $datatable .= '&nbsp;';
 8760:                             } else {
 8761:                                 $datatable .= '</span></td></tr><tr><td>'
 8762:                                               .'<span class="LC_nobreak">';
 8763:                             }
 8764:                             $datatable .= '<label><input type="radio" name="'
 8765:                                           .$parent.'" value="0" />'
 8766:                                           .&mt('Do not display').'</label></span>';
 8767:                             if ($parent eq 'communities') {
 8768:                                 $datatable .= '</td></tr></table>';
 8769:                             }
 8770:                             $datatable .= '</td>';
 8771:                         } else {
 8772:                             $datatable .= $parent
 8773:                                           .'&nbsp;<span class="LC_nobreak"><label>'
 8774:                                           .'<input type="checkbox" name="deletecategory" '
 8775:                                           .'value="'.$item.'" />'.&mt('Delete').'</label></span></td>';
 8776:                         }
 8777:                         my $depth = 1;
 8778:                         push(@path,$parent);
 8779:                         $datatable .= &build_category_rows($itemcount,\@cats,$depth,$parent,\@path,\%idx);
 8780:                         pop(@path);
 8781:                         $datatable .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
 8782:                         $itemcount ++;
 8783:                     }
 8784:                     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8785:                     my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','$lastidx'".');"';
 8786:                     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="addcategory_pos"'.$chgstr.'>';
 8787:                     for (my $k=0; $k<=$maxnum; $k++) {
 8788:                         my $vpos = $k+1;
 8789:                         my $selstr;
 8790:                         if ($k == $numtop) {
 8791:                             $selstr = ' selected="selected" ';
 8792:                         }
 8793:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 8794:                     }
 8795:                     $datatable .= '</select></span></td><td colspan="2">'.&mt('Add category:').'&nbsp;'
 8796:                                   .'<input type="text" size="20" name="addcategory_name" value="" /></td>'
 8797:                                   .'</tr>'."\n";
 8798:                     $itemcount ++;
 8799:                     foreach my $default ('instcode','communities') {
 8800:                         if ((!grep(/^\Q$default\E$/,@{$cats[0]})) || ($cathash->{$default.'::0'} eq '')) {
 8801:                             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8802:                             my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','$lastidx'".');"';
 8803:                             $datatable .= '<tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr><tr '.$css_class.'><td>'.
 8804:                                           '<span class="LC_nobreak"><select name="'.$default.'_pos"'.$chgstr.'>';
 8805:                             for (my $k=0; $k<=$maxnum; $k++) {
 8806:                                 my $vpos = $k+1;
 8807:                                 my $selstr;
 8808:                                 if ($k == $maxnum) {
 8809:                                     $selstr = ' selected="selected" ';
 8810:                                 }
 8811:                                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 8812:                             }
 8813:                             $datatable .= '</select></span></td>'.
 8814:                                           '<td><span class="LC_nobreak">'.
 8815:                                           $default_names{$default}.'</span>';
 8816:                             if ($default eq 'instcode') {
 8817:                                 $datatable .= '<br /><span class="LC_nobreak">(' 
 8818:                                               .&mt('with institutional codes').')</span>';
 8819:                             }
 8820:                             $datatable .= '</td>'
 8821:                                           .'<td><span class="LC_nobreak"><label><input type="radio" name="'.$default.'" value="1" />'
 8822:                                           .&mt('Display').'</label>&nbsp;'
 8823:                                           .'<label><input type="radio" name="'.$default.'" value="0" checked="checked"/>'
 8824:                                           .&mt('Do not display').'</label></span></td></tr>';
 8825:                         }
 8826:                     }
 8827:                 }
 8828:             } else {
 8829:                 $datatable .= &initialize_categories($itemcount);
 8830:             }
 8831:         } else {
 8832:             $datatable .= '<tr><td class="LC_right_item">'.$hdritem->{'header'}->[1]->{'col2'}.'</td></tr>'
 8833:                           .&initialize_categories($itemcount);
 8834:         }
 8835:         $$rowtotal += $itemcount;
 8836:     }
 8837:     return $datatable;
 8838: }
 8839: 
 8840: sub print_serverstatuses {
 8841:     my ($dom,$settings,$rowtotal) = @_;
 8842:     my $datatable;
 8843:     my @pages = &serverstatus_pages();
 8844:     my (%namedaccess,%machineaccess);
 8845:     foreach my $type (@pages) {
 8846:         $namedaccess{$type} = '';
 8847:         $machineaccess{$type}= '';
 8848:     }
 8849:     if (ref($settings) eq 'HASH') {
 8850:         foreach my $type (@pages) {
 8851:             if (exists($settings->{$type})) {
 8852:                 if (ref($settings->{$type}) eq 'HASH') {
 8853:                     foreach my $key (keys(%{$settings->{$type}})) {
 8854:                         if ($key eq 'namedusers') {
 8855:                             $namedaccess{$type} = $settings->{$type}->{$key};
 8856:                         } elsif ($key eq 'machines') {
 8857:                             $machineaccess{$type} = $settings->{$type}->{$key};
 8858:                         }
 8859:                     }
 8860:                 }
 8861:             }
 8862:         }
 8863:     }
 8864:     my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
 8865:     my $rownum = 0;
 8866:     my $css_class;
 8867:     foreach my $type (@pages) {
 8868:         $rownum ++;
 8869:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 8870:         $datatable .= '<tr'.$css_class.'>'.
 8871:                       '<td><span class="LC_nobreak">'.
 8872:                       $titles->{$type}.'</span></td>'.
 8873:                       '<td class="LC_left_item">'.
 8874:                       '<input type="text" name="'.$type.'_namedusers" '.
 8875:                       'value="'.$namedaccess{$type}.'" size="30" /></td>'.
 8876:                       '<td class="LC_right_item">'.
 8877:                       '<span class="LC_nobreak">'.
 8878:                       '<input type="text" name="'.$type.'_machines" '.
 8879:                       'value="'.$machineaccess{$type}.'" size="10" />'.
 8880:                       '</span></td></tr>'."\n";
 8881:     }
 8882:     $$rowtotal += $rownum;
 8883:     return $datatable;
 8884: }
 8885: 
 8886: sub serverstatus_pages {
 8887:     return ('userstatus','lonstatus','loncron','server-status','codeversions',
 8888:             'checksums','clusterstatus','metadata_keywords','metadata_harvest',
 8889:             'takeoffline','takeonline','showenv','toggledebug','ping','domconf',
 8890:             'uniquecodes','diskusage','coursecatalog');
 8891: }
 8892: 
 8893: sub defaults_javascript {
 8894:     my ($settings) = @_;
 8895:     return unless (ref($settings) eq 'HASH');
 8896:     if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
 8897:         my $maxnum = scalar(@{$settings->{'inststatusorder'}});
 8898:         if ($maxnum eq '') {
 8899:             $maxnum = 0;
 8900:         }
 8901:         $maxnum ++;
 8902:         my $jstext = '    var inststatuses = Array('."'".join("','",@{$settings->{'inststatusorder'}})."'".');';  
 8903:         return <<"ENDSCRIPT";
 8904: <script type="text/javascript">
 8905: // <![CDATA[
 8906: function reorderTypes(form,caller) {
 8907:     var changedVal;
 8908: $jstext 
 8909:     var newpos = 'addinststatus_pos';
 8910:     var current = new Array;
 8911:     var maxh = $maxnum;
 8912:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 8913:     var oldVal;
 8914:     if (caller == newpos) {
 8915:         changedVal = newitemVal;
 8916:     } else {
 8917:         var curritem = 'inststatus_pos_'+caller;
 8918:         changedVal = form.elements[curritem].options[form.elements[curritem].selectedIndex].value;
 8919:         current[newitemVal] = newpos;
 8920:     }
 8921:     for (var i=0; i<inststatuses.length; i++) {
 8922:         if (inststatuses[i] != caller) {
 8923:             var elementName = 'inststatus_pos_'+inststatuses[i];
 8924:             if (form.elements[elementName]) {
 8925:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 8926:                 current[currVal] = elementName;
 8927:             }
 8928:         }
 8929:     }
 8930:     for (var j=0; j<maxh; j++) {
 8931:         if (current[j] == undefined) {
 8932:             oldVal = j;
 8933:         }
 8934:     }
 8935:     if (oldVal < changedVal) {
 8936:         for (var k=oldVal+1; k<=changedVal ; k++) {
 8937:            var elementName = current[k];
 8938:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 8939:         }
 8940:     } else {
 8941:         for (var k=changedVal; k<oldVal; k++) {
 8942:             var elementName = current[k];
 8943:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 8944:         }
 8945:     }
 8946:     return;
 8947: }
 8948: 
 8949: // ]]>
 8950: </script>
 8951: 
 8952: ENDSCRIPT
 8953:     }
 8954: }
 8955: 
 8956: sub passwords_javascript {
 8957:     my %intalert = &Apache::lonlocal::texthash (
 8958:         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.',
 8959:         authcost => 'Warning: bcrypt encryption cost for internal authentication must be an integer.',
 8960:         passmin => 'Warning: minimum password length must be a positive integer greater than 6.',
 8961:         passmax => 'Warning: maximum password length must be a positive integer (or blank).',
 8962:         passexp => 'Warning: days before password expiration must be a positive integer (or blank).',
 8963:         passnum => 'Warning: number of previous passwords to save must be a positive integer (or blank).',
 8964:     );
 8965:     &js_escape(\%intalert);
 8966:     my $defmin = $Apache::lonnet::passwdmin;
 8967:     my $intauthjs = <<"ENDSCRIPT";
 8968: 
 8969: function warnIntAuth(field) {
 8970:     if (field.name == 'intauth_check') {
 8971:         if (field.value == '2') {
 8972:             alert('$intalert{authcheck}');
 8973:         }
 8974:     }
 8975:     if (field.name == 'intauth_cost') {
 8976:         field.value.replace(/\s/g,'');
 8977:         if (field.value != '') {
 8978:             var regexdigit=/^\\d+\$/;
 8979:             if (!regexdigit.test(field.value)) {
 8980:                 alert('$intalert{authcost}');
 8981:             }
 8982:         }
 8983:     }
 8984:     return;
 8985: }
 8986: 
 8987: function warnIntPass(field) {
 8988:     field.value.replace(/^\s+/,'');
 8989:     field.value.replace(/\s+\$/,'');
 8990:     var regexdigit=/^\\d+\$/;
 8991:     if (field.name == 'passwords_min') {
 8992:         if (field.value == '') {
 8993:             alert('$intalert{passmin}');
 8994:             field.value = '$defmin';
 8995:         } else {
 8996:             if (!regexdigit.test(field.value)) {
 8997:                 alert('$intalert{passmin}');
 8998:                 field.value = '$defmin';
 8999:             }
 9000:             var minval = parseInt(field.value,10);
 9001:             if (minval < $defmin) {
 9002:                 alert('$intalert{passmin}');
 9003:                 field.value = '$defmin';
 9004:             }
 9005:         }
 9006:     } else {
 9007:         if (field.value == '0') {
 9008:             field.value = '';
 9009:         }
 9010:         if (field.value != '') {
 9011:             if (field.name == 'passwords_expire') {
 9012:                 var regexpposnum=/^\\d+(|\\.\\d*)\$/;
 9013:                 if (!regexpposnum.test(field.value)) {
 9014:                     alert('$intalert{passexp}');
 9015:                     field.value = '';
 9016:                 } else {
 9017:                     var expval = parseFloat(field.value);
 9018:                     if (expval == 0) {
 9019:                         alert('$intalert{passexp}');
 9020:                         field.value = '';
 9021:                     }
 9022:                 }
 9023:             } else {
 9024:                 if (!regexdigit.test(field.value)) {
 9025:                     if (field.name == 'passwords_max') {
 9026:                         alert('$intalert{passmax}');
 9027:                     } else {
 9028:                         if (field.name == 'passwords_numsaved') {
 9029:                             alert('$intalert{passnum}');
 9030:                         }
 9031:                     }
 9032:                     field.value = '';
 9033:                 }
 9034:             }
 9035:         }
 9036:     }
 9037:     return;
 9038: }
 9039: 
 9040: ENDSCRIPT
 9041:     return &Apache::lonhtmlcommon::scripttag($intauthjs);
 9042: }
 9043: 
 9044: sub coursecategories_javascript {
 9045:     my ($settings) = @_;
 9046:     my ($output,$jstext,$cathash);
 9047:     if (ref($settings) eq 'HASH') {
 9048:         $cathash = $settings->{'cats'};
 9049:     }
 9050:     if (ref($cathash) eq 'HASH') {
 9051:         my (@cats,@jsarray,%idx);
 9052:         &Apache::loncommon::gather_categories($cathash,\@cats,\%idx,\@jsarray);
 9053:         if (@jsarray > 0) {
 9054:             $jstext = '    var categories = Array('.scalar(@jsarray).');'."\n";
 9055:             for (my $i=0; $i<@jsarray; $i++) {
 9056:                 if (ref($jsarray[$i]) eq 'ARRAY') {
 9057:                     my $catstr = join('","',@{$jsarray[$i]});
 9058:                     $jstext .= '    categories['.$i.'] = Array("'.$catstr.'");'."\n";
 9059:                 }
 9060:             }
 9061:         }
 9062:     } else {
 9063:         $jstext  = '    var categories = Array(1);'."\n".
 9064:                    '    categories[0] = Array("instcode_pos");'."\n"; 
 9065:     }
 9066:     my $instcode_reserved = &mt('The name: [_1] is a reserved category.','"instcode"');
 9067:     my $communities_reserved = &mt('The name: [_1] is a reserved category.','"communities"');
 9068:     my $choose_again = "\n".&mt('Please use a different name for the new top level category.'); 
 9069:     &js_escape(\$instcode_reserved);
 9070:     &js_escape(\$communities_reserved);
 9071:     &js_escape(\$choose_again);
 9072:     $output = <<"ENDSCRIPT";
 9073: <script type="text/javascript">
 9074: // <![CDATA[
 9075: function reorderCats(form,parent,item,idx) {
 9076:     var changedVal;
 9077: $jstext
 9078:     var newpos = 'addcategory_pos';
 9079:     if (parent == '') {
 9080:         var has_instcode = 0;
 9081:         var maxtop = categories[idx].length;
 9082:         for (var j=0; j<maxtop; j++) {
 9083:             if (categories[idx][j] == 'instcode::0') {
 9084:                 has_instcode == 1;
 9085:             }
 9086:         }
 9087:         if (has_instcode == 0) {
 9088:             categories[idx][maxtop] = 'instcode_pos';
 9089:         }
 9090:     } else {
 9091:         newpos += '_'+parent;
 9092:     }
 9093:     var maxh = 1 + categories[idx].length;
 9094:     var current = new Array;
 9095:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 9096:     if (item == newpos) {
 9097:         changedVal = newitemVal;
 9098:     } else {
 9099:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 9100:         current[newitemVal] = newpos;
 9101:     }
 9102:     for (var i=0; i<categories[idx].length; i++) {
 9103:         var elementName = categories[idx][i];
 9104:         if (elementName != item) {
 9105:             if (form.elements[elementName]) {
 9106:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 9107:                 current[currVal] = elementName;
 9108:             }
 9109:         }
 9110:     }
 9111:     var oldVal;
 9112:     for (var j=0; j<maxh; j++) {
 9113:         if (current[j] == undefined) {
 9114:             oldVal = j;
 9115:         }
 9116:     }
 9117:     if (oldVal < changedVal) {
 9118:         for (var k=oldVal+1; k<=changedVal ; k++) {
 9119:            var elementName = current[k];
 9120:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 9121:         }
 9122:     } else {
 9123:         for (var k=changedVal; k<oldVal; k++) {
 9124:             var elementName = current[k];
 9125:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 9126:         }
 9127:     }
 9128:     return;
 9129: }
 9130: 
 9131: function categoryCheck(form) {
 9132:     if (form.elements['addcategory_name'].value == 'instcode') {
 9133:         alert('$instcode_reserved\\n$choose_again');
 9134:         return false;
 9135:     }
 9136:     if (form.elements['addcategory_name'].value == 'communities') {
 9137:         alert('$communities_reserved\\n$choose_again');
 9138:         return false;
 9139:     }
 9140:     return true;
 9141: }
 9142: 
 9143: // ]]>
 9144: </script>
 9145: 
 9146: ENDSCRIPT
 9147:     return $output;
 9148: }
 9149: 
 9150: sub initialize_categories {
 9151:     my ($itemcount) = @_;
 9152:     my ($datatable,$css_class,$chgstr);
 9153:     my %default_names = &Apache::lonlocal::texthash (
 9154:                       instcode    => 'Official courses (with institutional codes)',
 9155:                       communities => 'Communities',
 9156:                         );
 9157:     my $select0 = ' selected="selected"';
 9158:     my $select1 = '';
 9159:     foreach my $default ('instcode','communities') {
 9160:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9161:         $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','0'".');"';
 9162:         if ($default eq 'communities') {
 9163:             $select1 = $select0;
 9164:             $select0 = '';
 9165:         }
 9166:         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 9167:                      .'<select name="'.$default.'_pos">'
 9168:                      .'<option value="0"'.$select0.'>1</option>'
 9169:                      .'<option value="1"'.$select1.'>2</option>'
 9170:                      .'<option value="2">3</option></select>&nbsp;'
 9171:                      .$default_names{$default}
 9172:                      .'</span></td><td><span class="LC_nobreak">'
 9173:                      .'<label><input type="radio" name="'.$default.'" value="1" checked="checked" />'
 9174:                      .&mt('Display').'</label>&nbsp;<label>'
 9175:                      .'<input type="radio" name="'.$default.'" value="0" />'.&mt('Do not display')
 9176:                  .'</label></span></td></tr>';
 9177:         $itemcount ++;
 9178:     }
 9179:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9180:     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','0'".');"';
 9181:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 9182:                   .'<select name="addcategory_pos"'.$chgstr.'>'
 9183:                   .'<option value="0">1</option>'
 9184:                   .'<option value="1">2</option>'
 9185:                   .'<option value="2" selected="selected">3</option></select>&nbsp;'
 9186:                   .&mt('Add category').'</span></td><td><span class="LC_nobreak">'.&mt('Name:')
 9187:                   .'&nbsp;<input type="text" size="20" name="addcategory_name" value="" /></span>'
 9188:                   .'</td></tr>';
 9189:     return $datatable;
 9190: }
 9191: 
 9192: sub build_category_rows {
 9193:     my ($itemcount,$cats,$depth,$parent,$path,$idx) = @_;
 9194:     my ($text,$name,$item,$chgstr);
 9195:     if (ref($cats) eq 'ARRAY') {
 9196:         my $maxdepth = scalar(@{$cats});
 9197:         if (ref($cats->[$depth]) eq 'HASH') {
 9198:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
 9199:                 my $numchildren = @{$cats->[$depth]{$parent}};
 9200:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9201:                 $text .= '<td><table class="LC_data_table">';
 9202:                 my ($idxnum,$parent_name,$parent_item);
 9203:                 my $higher = $depth - 1;
 9204:                 if ($higher == 0) {
 9205:                     $parent_name = &escape($parent).'::'.$higher;
 9206:                 } else {
 9207:                     if (ref($path) eq 'ARRAY') {
 9208:                         $parent_name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
 9209:                     }
 9210:                 }
 9211:                 $parent_item = 'addcategory_pos_'.$parent_name;
 9212:                 for (my $j=0; $j<=$numchildren; $j++) {
 9213:                     if ($j < $numchildren) {
 9214:                         $name = $cats->[$depth]{$parent}[$j];
 9215:                         $item = &escape($name).':'.&escape($parent).':'.$depth;
 9216:                         $idxnum = $idx->{$item};
 9217:                     } else {
 9218:                         $name = $parent_name;
 9219:                         $item = $parent_item;
 9220:                     }
 9221:                     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'$parent_name','$item','$idxnum'".');"';
 9222:                     $text .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="'.$item.'"'.$chgstr.'>';
 9223:                     for (my $i=0; $i<=$numchildren; $i++) {
 9224:                         my $vpos = $i+1;
 9225:                         my $selstr;
 9226:                         if ($j == $i) {
 9227:                             $selstr = ' selected="selected" ';
 9228:                         }
 9229:                         $text .= '<option value="'.$i.'"'.$selstr.'>'.$vpos.'</option>';
 9230:                     }
 9231:                     $text .= '</select>&nbsp;';
 9232:                     if ($j < $numchildren) {
 9233:                         my $deeper = $depth+1;
 9234:                         $text .= $name.'&nbsp;'
 9235:                                  .'<label><input type="checkbox" name="deletecategory" value="'
 9236:                                  .$item.'" />'.&mt('Delete').'</label></span></td><td>';
 9237:                         if(ref($path) eq 'ARRAY') {
 9238:                             push(@{$path},$name);
 9239:                             $text .= &build_category_rows($itemcount,$cats,$deeper,$name,$path,$idx);
 9240:                             pop(@{$path});
 9241:                         }
 9242:                     } else {
 9243:                         $text .= &mt('Add subcategory:').'&nbsp;</span><input type="text" size="20" name="addcategory_name_';
 9244:                         if ($j == $numchildren) {
 9245:                             $text .= $name;
 9246:                         } else {
 9247:                             $text .= $item;
 9248:                         }
 9249:                         $text .= '" value="" />';
 9250:                     }
 9251:                     $text .= '</td></tr>';
 9252:                 }
 9253:                 $text .= '</table></td>';
 9254:             } else {
 9255:                 my $higher = $depth-1;
 9256:                 if ($higher == 0) {
 9257:                     $name = &escape($parent).'::'.$higher;
 9258:                 } else {
 9259:                     if (ref($path) eq 'ARRAY') {
 9260:                         $name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
 9261:                     }
 9262:                 }
 9263:                 my $colspan;
 9264:                 if ($parent ne 'instcode') {
 9265:                     $colspan = $maxdepth - $depth - 1;
 9266:                     $text .= '<td colspan="'.$colspan.'">'.&mt('Add subcategory:').'<input type="text" size="20" name="subcat_'.$name.'" value="" /></td>';
 9267:                 }
 9268:             }
 9269:         }
 9270:     }
 9271:     return $text;
 9272: }
 9273: 
 9274: sub modifiable_userdata_row {
 9275:     my ($context,$item,$settings,$numinrow,$rowcount,$usertypes,$fieldsref,$titlesref,
 9276:         $rowid,$customcss,$rowstyle) = @_;
 9277:     my ($role,$rolename,$statustype);
 9278:     $role = $item;
 9279:     if ($context eq 'cancreate') {
 9280:         if ($item =~ /^(emailusername)_(.+)$/) {
 9281:             $role = $1;
 9282:             $statustype = $2;
 9283:             if (ref($usertypes) eq 'HASH') {
 9284:                 if ($usertypes->{$statustype}) {
 9285:                     $rolename = &mt('Data provided by [_1]',$usertypes->{$statustype});
 9286:                 } else {
 9287:                     $rolename = &mt('Data provided by user');
 9288:                 }
 9289:             }
 9290:         }
 9291:     } elsif ($context eq 'selfcreate') {
 9292:         if (ref($usertypes) eq 'HASH') {
 9293:             $rolename = $usertypes->{$role};
 9294:         } else {
 9295:             $rolename = $role;
 9296:         }
 9297:     } else {
 9298:         if ($role eq 'cr') {
 9299:             $rolename = &mt('Custom role');
 9300:         } else {
 9301:             $rolename = &Apache::lonnet::plaintext($role);
 9302:         }
 9303:     }
 9304:     my (@fields,%fieldtitles);
 9305:     if (ref($fieldsref) eq 'ARRAY') {
 9306:         @fields = @{$fieldsref};
 9307:     } else {
 9308:         @fields = ('lastname','firstname','middlename','generation',
 9309:                    'permanentemail','id');
 9310:     }
 9311:     if ((ref($titlesref) eq 'HASH')) {
 9312:         %fieldtitles = %{$titlesref};
 9313:     } else {
 9314:         %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 9315:     }
 9316:     my $output;
 9317:     my $css_class;
 9318:     if ($rowcount%2) {
 9319:         $css_class = 'LC_odd_row';
 9320:     }
 9321:     if ($customcss) {
 9322:         $css_class .= " $customcss";
 9323:     }
 9324:     $css_class =~ s/^\s+//;
 9325:     if ($css_class) {
 9326:         $css_class = ' class="'.$css_class.'"';
 9327:     }
 9328:     if ($rowstyle) {
 9329:         $css_class .= ' style="'.$rowstyle.'"';
 9330:     }
 9331:     if ($rowid) {
 9332:         $rowid = ' id="'.$rowid.'"';
 9333:     }
 9334: 
 9335:     $output = '<tr '.$css_class.$rowid.'>'.
 9336:               '<td><span class="LC_nobreak">'.$rolename.'</span></td>'.
 9337:               '<td class="LC_left_item" colspan="2"><table>';
 9338:     my $rem;
 9339:     my %checks;
 9340:     if (ref($settings) eq 'HASH') {
 9341:         if (ref($settings->{$context}) eq 'HASH') {
 9342:             if (ref($settings->{$context}->{$role}) eq 'HASH') {
 9343:                 my $hashref = $settings->{$context}->{$role};
 9344:                 if ($role eq 'emailusername') {
 9345:                     if ($statustype) {
 9346:                         if (ref($settings->{$context}->{$role}->{$statustype}) eq 'HASH') {
 9347:                             $hashref = $settings->{$context}->{$role}->{$statustype};
 9348:                             if (ref($hashref) eq 'HASH') { 
 9349:                                 foreach my $field (@fields) {
 9350:                                     if ($hashref->{$field}) {
 9351:                                         $checks{$field} = $hashref->{$field};
 9352:                                     }
 9353:                                 }
 9354:                             }
 9355:                         }
 9356:                     }
 9357:                 } else {
 9358:                     if (ref($hashref) eq 'HASH') {
 9359:                         foreach my $field (@fields) {
 9360:                             if ($hashref->{$field}) {
 9361:                                 $checks{$field} = ' checked="checked" ';
 9362:                             }
 9363:                         }
 9364:                     }
 9365:                 }
 9366:             }
 9367:         }
 9368:     }
 9369: 
 9370:     my $total = scalar(@fields);
 9371:     for (my $i=0; $i<$total; $i++) {
 9372:         $rem = $i%($numinrow);
 9373:         if ($rem == 0) {
 9374:             if ($i > 0) {
 9375:                 $output .= '</tr>';
 9376:             }
 9377:             $output .= '<tr>';
 9378:         }
 9379:         my $check = ' ';
 9380:         unless ($role eq 'emailusername') {
 9381:             if (exists($checks{$fields[$i]})) {
 9382:                 $check = $checks{$fields[$i]};
 9383:             } else {
 9384:                 if ($role eq 'st') {
 9385:                     if (ref($settings) ne 'HASH') {
 9386:                         $check = ' checked="checked" '; 
 9387:                     }
 9388:                 }
 9389:             }
 9390:         }
 9391:         $output .= '<td class="LC_left_item">'.
 9392:                    '<span class="LC_nobreak">';
 9393:         if ($role eq 'emailusername') {
 9394:             unless ($checks{$fields[$i]} =~ /^(required|optional)$/) {
 9395:                 $checks{$fields[$i]} = 'omit';
 9396:             }
 9397:             foreach my $option ('required','optional','omit') {
 9398:                 my $checked='';
 9399:                 if ($checks{$fields[$i]} eq $option) {
 9400:                     $checked='checked="checked" ';
 9401:                 }
 9402:                 $output .= '<label>'.
 9403:                            '<input type="radio" name="canmodify_'.$item.'_'.$fields[$i].'" value="'.$option.'" '.$checked.'/>'.
 9404:                            &mt($option).'</label>'.('&nbsp;' x2);
 9405:             }
 9406:             $output .= '<i>'.$fieldtitles{$fields[$i]}.'</i>';
 9407:         } else {
 9408:             $output .= '<label>'.
 9409:                        '<input type="checkbox" name="canmodify_'.$role.'" '.
 9410:                        'value="'.$fields[$i].'"'.$check.'/>'.$fieldtitles{$fields[$i]}.
 9411:                        '</label>';
 9412:         }
 9413:         $output .= '</span></td>';
 9414:     }
 9415:     $rem = $total%$numinrow;
 9416:     my $colsleft;
 9417:     if ($rem) {
 9418:         $colsleft = $numinrow - $rem;
 9419:     }
 9420:     if ($colsleft > 1) {
 9421:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 9422:                    '&nbsp;</td>';
 9423:     } elsif ($colsleft == 1) {
 9424:         $output .= '<td class="LC_left_item">&nbsp;</td>';
 9425:     }
 9426:     $output .= '</tr></table></td></tr>';
 9427:     return $output;
 9428: }
 9429: 
 9430: sub insttypes_row {
 9431:     my ($settings,$types,$usertypes,$dom,$numinrow,$othertitle,$context,$rowtotal,$onclick,
 9432:         $customcss,$rowstyle) = @_;
 9433:     my %lt = &Apache::lonlocal::texthash (
 9434:                       cansearch => 'Users allowed to search',
 9435:                       statustocreate => 'Institutional affiliation(s) able to create own account (login/SSO)',
 9436:                       lockablenames => 'User preference to lock name',
 9437:                       selfassign    => 'Self-reportable affiliations',
 9438:                       overrides     => "Override domain's helpdesk settings based on requester's affiliation",
 9439:              );
 9440:     my $showdom;
 9441:     if ($context eq 'cansearch') {
 9442:         $showdom = ' ('.$dom.')';
 9443:     }
 9444:     my $class = 'LC_left_item';
 9445:     if ($context eq 'statustocreate') {
 9446:         $class = 'LC_right_item';
 9447:     }
 9448:     my $css_class;
 9449:     if ($$rowtotal%2) {
 9450:         $css_class = 'LC_odd_row';
 9451:     }
 9452:     if ($customcss) {
 9453:         $css_class .= ' '.$customcss;
 9454:     }
 9455:     $css_class =~ s/^\s+//;
 9456:     if ($css_class) {
 9457:         $css_class = ' class="'.$css_class.'"';
 9458:     }
 9459:     if ($rowstyle) {
 9460:         $css_class .= ' style="'.$rowstyle.'"';
 9461:     }
 9462:     if ($onclick) {
 9463:         $onclick = 'onclick="'.$onclick.'" ';
 9464:     }
 9465:     my $output = '<tr'.$css_class.'>'.
 9466:                  '<td>'.$lt{$context}.$showdom.
 9467:                  '</td><td class="'.$class.'" colspan="2"><table>';
 9468:     my $rem;
 9469:     if (ref($types) eq 'ARRAY') {
 9470:         for (my $i=0; $i<@{$types}; $i++) {
 9471:             if (defined($usertypes->{$types->[$i]})) {
 9472:                 my $rem = $i%($numinrow);
 9473:                 if ($rem == 0) {
 9474:                     if ($i > 0) {
 9475:                         $output .= '</tr>';
 9476:                     }
 9477:                     $output .= '<tr>';
 9478:                 }
 9479:                 my $check = ' ';
 9480:                 if (ref($settings) eq 'HASH') {
 9481:                     if (ref($settings->{$context}) eq 'ARRAY') {
 9482:                         if (grep(/^\Q$types->[$i]\E$/,@{$settings->{$context}})) {
 9483:                             $check = ' checked="checked" ';
 9484:                         }
 9485:                     } elsif (ref($settings->{$context}) eq 'HASH') {
 9486:                         if (ref($settings->{$context}->{$types->[$i]}) eq 'HASH') {
 9487:                             $check = ' checked="checked" ';
 9488:                         }
 9489:                     } elsif ($context eq 'statustocreate') {
 9490:                         $check = ' checked="checked" ';
 9491:                     }
 9492:                 }
 9493:                 $output .= '<td class="LC_left_item">'.
 9494:                            '<span class="LC_nobreak"><label>'.
 9495:                            '<input type="checkbox" name="'.$context.'" '.
 9496:                            'value="'.$types->[$i].'"'.$check.$onclick.'/>'.
 9497:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 9498:             }
 9499:         }
 9500:         $rem = @{$types}%($numinrow);
 9501:     }
 9502:     my $colsleft = $numinrow - $rem;
 9503:     if ($context eq 'overrides') {
 9504:         if ($colsleft > 1) {
 9505:             $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 9506:         } else {
 9507:             $output .= '<td class="LC_left_item">';
 9508:         }
 9509:         $output .= '&nbsp;';
 9510:     } else {
 9511:         if ($rem == 0) {
 9512:             $output .= '<tr>';
 9513:         }
 9514:         if ($colsleft > 1) {
 9515:             $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 9516:         } else {
 9517:             $output .= '<td class="LC_left_item">';
 9518:         }
 9519:         my $defcheck = ' ';
 9520:         if (ref($settings) eq 'HASH') {  
 9521:             if (ref($settings->{$context}) eq 'ARRAY') {
 9522:                 if (grep(/^default$/,@{$settings->{$context}})) {
 9523:                     $defcheck = ' checked="checked" ';
 9524:                 }
 9525:             } elsif ($context eq 'statustocreate') {
 9526:                 $defcheck = ' checked="checked" ';
 9527:             }
 9528:         }
 9529:         $output .= '<span class="LC_nobreak"><label>'.
 9530:                    '<input type="checkbox" name="'.$context.'" '.
 9531:                    'value="default"'.$defcheck.$onclick.' />'.
 9532:                    $othertitle.'</label></span>';
 9533:     }
 9534:     $output .= '</td></tr></table></td></tr>';
 9535:     return $output;
 9536: }
 9537: 
 9538: sub sorted_searchtitles {
 9539:     my %searchtitles = &Apache::lonlocal::texthash(
 9540:                          'uname' => 'username',
 9541:                          'lastname' => 'last name',
 9542:                          'lastfirst' => 'last name, first name',
 9543:                      );
 9544:     my @titleorder = ('uname','lastname','lastfirst');
 9545:     return (\%searchtitles,\@titleorder);
 9546: }
 9547: 
 9548: sub sorted_searchtypes {
 9549:     my %srchtypes_desc = (
 9550:                            exact    => 'is exact match',
 9551:                            contains => 'contains ..',
 9552:                            begins   => 'begins with ..',
 9553:                          );
 9554:     my @srchtypeorder = ('exact','begins','contains');
 9555:     return (\%srchtypes_desc,\@srchtypeorder);
 9556: }
 9557: 
 9558: sub usertype_update_row {
 9559:     my ($settings,$usertypes,$fieldtitles,$fields,$types,$rownums) = @_;
 9560:     my $datatable;
 9561:     my $numinrow = 4;
 9562:     foreach my $type (@{$types}) {
 9563:         if (defined($usertypes->{$type})) {
 9564:             $$rownums ++;
 9565:             my $css_class = $$rownums%2?' class="LC_odd_row"':'';
 9566:             $datatable .= '<tr'.$css_class.'><td>'.$usertypes->{$type}.
 9567:                           '</td><td class="LC_left_item"><table>';
 9568:             for (my $i=0; $i<@{$fields}; $i++) {
 9569:                 my $rem = $i%($numinrow);
 9570:                 if ($rem == 0) {
 9571:                     if ($i > 0) {
 9572:                         $datatable .= '</tr>';
 9573:                     }
 9574:                     $datatable .= '<tr>';
 9575:                 }
 9576:                 my $check = ' ';
 9577:                 if (ref($settings) eq 'HASH') {
 9578:                     if (ref($settings->{'fields'}) eq 'HASH') {
 9579:                         if (ref($settings->{'fields'}{$type}) eq 'ARRAY') {
 9580:                             if (grep(/^\Q$fields->[$i]\E$/,@{$settings->{'fields'}{$type}})) {
 9581:                                 $check = ' checked="checked" ';
 9582:                             }
 9583:                         }
 9584:                     }
 9585:                 }
 9586: 
 9587:                 if ($i == @{$fields}-1) {
 9588:                     my $colsleft = $numinrow - $rem;
 9589:                     if ($colsleft > 1) {
 9590:                         $datatable .= '<td colspan="'.$colsleft.'">';
 9591:                     } else {
 9592:                         $datatable .= '<td>';
 9593:                     }
 9594:                 } else {
 9595:                     $datatable .= '<td>';
 9596:                 }
 9597:                 $datatable .= '<span class="LC_nobreak"><label>'.
 9598:                               '<input type="checkbox" name="updateable_'.$type.
 9599:                               '_'.$fields->[$i].'" value="1"'.$check.'/>'.
 9600:                               $fieldtitles->{$fields->[$i]}.'</label></span></td>';
 9601:             }
 9602:             $datatable .= '</tr></table></td></tr>';
 9603:         }
 9604:     }
 9605:     return $datatable;
 9606: }
 9607: 
 9608: sub modify_login {
 9609:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
 9610:     my ($resulttext,$errors,$colchgtext,%changes,%colchanges,%newfile,%newurl,
 9611:         %curr_loginvia,%loginhash,@currlangs,@newlangs,$addedfile,%title,@offon,
 9612:         %currsaml,%saml,%samltext,%samlimg,%samlalt,%samlurl,%samltitle,%samlnotsso);
 9613:     %title = ( coursecatalog => 'Display course catalog',
 9614:                adminmail => 'Display administrator E-mail address',
 9615:                helpdesk  => 'Display "Contact Helpdesk" link',
 9616:                newuser => 'Link for visitors to create a user account',
 9617:                loginheader => 'Log-in box header',
 9618:                saml => 'Dual SSO and non-SSO login');
 9619:     @offon = ('off','on');
 9620:     if (ref($domconfig{login}) eq 'HASH') {
 9621:         if (ref($domconfig{login}{loginvia}) eq 'HASH') {
 9622:             foreach my $lonhost (keys(%{$domconfig{login}{loginvia}})) {
 9623:                 $curr_loginvia{$lonhost} = $domconfig{login}{loginvia}{$lonhost};
 9624:             }
 9625:         }
 9626:         if (ref($domconfig{login}{'saml'}) eq 'HASH') {
 9627:             foreach my $lonhost (keys(%{$domconfig{login}{'saml'}})) {
 9628:                 if (ref($domconfig{login}{'saml'}{$lonhost}) eq 'HASH') {
 9629:                     $currsaml{$lonhost} = $domconfig{login}{'saml'}{$lonhost};
 9630:                     $saml{$lonhost} = 1;
 9631:                     $samltext{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'text'};
 9632:                     $samlurl{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'url'};
 9633:                     $samlalt{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'alt'};
 9634:                     $samlimg{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'img'};
 9635:                     $samltitle{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'title'};
 9636:                     $samlnotsso{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'notsso'};
 9637:                 }
 9638:             }
 9639:         }
 9640:     }
 9641:     ($errors,%colchanges) = &modify_colors($r,$dom,$confname,['login'],
 9642:                                            \%domconfig,\%loginhash);
 9643:     my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
 9644:     foreach my $item (@toggles) {
 9645:         $loginhash{login}{$item} = $env{'form.'.$item};
 9646:     }
 9647:     $loginhash{login}{loginheader} = $env{'form.loginheader'};
 9648:     if (ref($colchanges{'login'}) eq 'HASH') {  
 9649:         $colchgtext = &display_colorchgs($dom,\%colchanges,['login'],
 9650:                                          \%loginhash);
 9651:     }
 9652: 
 9653:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 9654:     my %domservers = &Apache::lonnet::get_servers($dom);
 9655:     my @loginvia_attribs = ('serverpath','custompath','exempt');
 9656:     if (keys(%servers) > 1) {
 9657:         foreach my $lonhost (keys(%servers)) {
 9658:             next if ($env{'form.'.$lonhost.'_server'} eq $lonhost);
 9659:             if (ref($curr_loginvia{$lonhost}) eq 'HASH') {
 9660:                 if ($env{'form.'.$lonhost.'_server'} eq $curr_loginvia{$lonhost}{'server'}) {
 9661:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $curr_loginvia{$lonhost}{'server'};
 9662:                 } elsif ($curr_loginvia{$lonhost}{'server'} ne '') {
 9663:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
 9664:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
 9665:                         $changes{'loginvia'}{$lonhost} = 1;
 9666:                     } else {
 9667:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = '';
 9668:                         $changes{'loginvia'}{$lonhost} = 1;
 9669:                     }
 9670:                 } else {
 9671:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
 9672:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
 9673:                         $changes{'loginvia'}{$lonhost} = 1;
 9674:                     }
 9675:                 }
 9676:                 if ($loginhash{login}{loginvia}{$lonhost}{'server'} eq '') {
 9677:                     foreach my $item (@loginvia_attribs) {
 9678:                         $loginhash{login}{loginvia}{$lonhost}{$item} = '';
 9679:                     }
 9680:                 } else {
 9681:                     foreach my $item (@loginvia_attribs) {
 9682:                         my $new = $env{'form.'.$lonhost.'_'.$item};
 9683:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
 9684:                             $env{'form.'.$lonhost.'_custompath'} =~ s/\s+//g;
 9685:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
 9686:                                 $new = '/';
 9687:                             }
 9688:                         }
 9689:                         if (($item eq 'custompath') && 
 9690:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
 9691:                             $new = '';
 9692:                         }
 9693:                         if ($new ne $curr_loginvia{$lonhost}{$item}) {
 9694:                             $changes{'loginvia'}{$lonhost} = 1;
 9695:                         }
 9696:                         if ($item eq 'exempt') {
 9697:                             $new = &check_exempt_addresses($new);
 9698:                         }
 9699:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
 9700:                     }
 9701:                 }
 9702:             } else {
 9703:                 if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
 9704:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
 9705:                     $changes{'loginvia'}{$lonhost} = 1;
 9706:                     foreach my $item (@loginvia_attribs) {
 9707:                         my $new = $env{'form.'.$lonhost.'_'.$item};
 9708:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
 9709:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
 9710:                                 $new = '/';
 9711:                             }
 9712:                         }
 9713:                         if (($item eq 'custompath') && 
 9714:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
 9715:                             $new = '';
 9716:                         }
 9717:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
 9718:                     }
 9719:                 }
 9720:             }
 9721:         }
 9722:     }
 9723: 
 9724:     my $servadm = $r->dir_config('lonAdmEMail');
 9725:     my %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
 9726:     if (ref($domconfig{'login'}) eq 'HASH') {
 9727:         if (ref($domconfig{'login'}{'helpurl'}) eq 'HASH') {
 9728:             foreach my $lang (sort(keys(%{$domconfig{'login'}{'helpurl'}}))) {
 9729:                 if ($lang eq 'nolang') {
 9730:                     push(@currlangs,$lang);
 9731:                 } elsif (defined($langchoices{$lang})) {
 9732:                     push(@currlangs,$lang);
 9733:                 } else {
 9734:                     next;
 9735:                 }
 9736:             }
 9737:         }
 9738:     }
 9739:     my @delurls = &Apache::loncommon::get_env_multiple('form.loginhelpurl_del');
 9740:     if (@currlangs > 0) {
 9741:         foreach my $lang (@currlangs) {
 9742:             if (grep(/^\Q$lang\E$/,@delurls)) {
 9743:                 $changes{'helpurl'}{$lang} = 1;
 9744:             } elsif ($env{'form.loginhelpurl_'.$lang.'.filename'}) {
 9745:                 $changes{'helpurl'}{$lang} = 1;
 9746:                 $newfile{$lang} = $env{'form.loginhelpurl_'.$lang.'.filename'};
 9747:                 push(@newlangs,$lang);
 9748:             } else {
 9749:                 $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
 9750:             }
 9751:         }
 9752:     }
 9753:     unless (grep(/^nolang$/,@currlangs)) {
 9754:         if ($env{'form.loginhelpurl_nolang.filename'}) {
 9755:             $changes{'helpurl'}{'nolang'} = 1;
 9756:             $newfile{'nolang'} = $env{'form.loginhelpurl_nolang.filename'};
 9757:             push(@newlangs,'nolang');
 9758:         }
 9759:     }
 9760:     if ($env{'form.loginhelpurl_add_lang'}) {
 9761:         if ((defined($langchoices{$env{'form.loginhelpurl_add_lang'}})) &&
 9762:             ($env{'form.loginhelpurl_add_file.filename'})) {
 9763:             $newfile{$env{'form.loginhelpurl_add_lang'}} = $env{'form.loginhelpurl_add_file.filename'};
 9764:             $addedfile = $env{'form.loginhelpurl_add_lang'};
 9765:         }
 9766:     }
 9767:     if ((@newlangs > 0) || ($addedfile)) {
 9768:         my $error;
 9769:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
 9770:         if ($configuserok eq 'ok') {
 9771:             if ($switchserver) {
 9772:                 $error = &mt("Upload of custom help file is not permitted to this server: [_1]",$switchserver);
 9773:             } elsif ($author_ok eq 'ok') {
 9774:                 my @allnew = @newlangs;
 9775:                 if ($addedfile ne '') {
 9776:                     push(@allnew,$addedfile);
 9777:                 }
 9778:                 foreach my $lang (@allnew) {
 9779:                     my $formelem = 'loginhelpurl_'.$lang;
 9780:                     if ($lang eq $env{'form.loginhelpurl_add_lang'}) {
 9781:                         $formelem = 'loginhelpurl_add_file';
 9782:                     }
 9783:                     (my $result,$newurl{$lang}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
 9784:                                                                "help/$lang",'','',$newfile{$lang});
 9785:                     if ($result eq 'ok') {
 9786:                         $loginhash{'login'}{'helpurl'}{$lang} = $newurl{$lang};
 9787:                         $changes{'helpurl'}{$lang} = 1;
 9788:                     } else {
 9789:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$newfile{$lang},$result);
 9790:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
 9791:                         if ((grep(/^\Q$lang\E$/,@currlangs)) &&
 9792:                             (!grep(/^\Q$lang\E$/,@delurls))) {
 9793:                             $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
 9794:                         }
 9795:                     }
 9796:                 }
 9797:             } else {
 9798:                 $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);
 9799:             }
 9800:         } else {
 9801:             $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);
 9802:         }
 9803:         if ($error) {
 9804:             &Apache::lonnet::logthis($error);
 9805:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
 9806:         }
 9807:     }
 9808: 
 9809:     my (%currheadtagurls,%currexempt,@newhosts,%newheadtagurls,%possexempt);
 9810:     if (ref($domconfig{'login'}) eq 'HASH') {
 9811:         if (ref($domconfig{'login'}{'headtag'}) eq 'HASH') {
 9812:             foreach my $lonhost (keys(%{$domconfig{'login'}{'headtag'}})) {
 9813:                 if ($domservers{$lonhost}) {
 9814:                     if (ref($domconfig{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
 9815:                         $currheadtagurls{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'url'};
 9816:                         $currexempt{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'exempt'};
 9817:                     }
 9818:                 }
 9819:             }
 9820:         }
 9821:     }
 9822:     my @delheadtagurls = &Apache::loncommon::get_env_multiple('form.loginheadtag_del');
 9823:     foreach my $lonhost (sort(keys(%domservers))) {
 9824:         if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
 9825:             $changes{'headtag'}{$lonhost} = 1;
 9826:         } else {
 9827:             if ($env{'form.loginheadtagexempt_'.$lonhost}) {
 9828:                 $possexempt{$lonhost} = &check_exempt_addresses($env{'form.loginheadtagexempt_'.$lonhost});
 9829:             }
 9830:             if ($env{'form.loginheadtag_'.$lonhost.'.filename'}) {
 9831:                 push(@newhosts,$lonhost);
 9832:             } elsif ($currheadtagurls{$lonhost}) {
 9833:                 $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $currheadtagurls{$lonhost};
 9834:                 if ($currexempt{$lonhost}) {
 9835:                     if ((!exists($possexempt{$lonhost})) || ($possexempt{$lonhost} ne $currexempt{$lonhost})) {
 9836:                         $changes{'headtag'}{$lonhost} = 1;
 9837:                     }
 9838:                 } elsif ($possexempt{$lonhost}) {
 9839:                     $changes{'headtag'}{$lonhost} = 1;
 9840:                 }
 9841:                 if ($possexempt{$lonhost}) {
 9842:                     $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
 9843:                 }
 9844:             }
 9845:         }
 9846:     }
 9847:     if (@newhosts) {
 9848:         my $error;
 9849:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
 9850:         if ($configuserok eq 'ok') {
 9851:             if ($switchserver) {
 9852:                 $error = &mt("Upload of custom markup is not permitted to this server: [_1]",$switchserver);
 9853:             } elsif ($author_ok eq 'ok') {
 9854:                 foreach my $lonhost (@newhosts) {
 9855:                     my $formelem = 'loginheadtag_'.$lonhost;
 9856:                     (my $result,$newheadtagurls{$lonhost}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
 9857:                                                                           "login/headtag/$lonhost",'','',
 9858:                                                                           $env{'form.loginheadtag_'.$lonhost.'.filename'});
 9859:                     if ($result eq 'ok') {
 9860:                         $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $newheadtagurls{$lonhost};
 9861:                         $changes{'headtag'}{$lonhost} = 1;
 9862:                         if ($possexempt{$lonhost}) {
 9863:                             $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
 9864:                         }
 9865:                     } else {
 9866:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",
 9867:                                            $newheadtagurls{$lonhost},$result);
 9868:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
 9869:                         if ((grep(/^\Q$lonhost\E$/,keys(%currheadtagurls))) &&
 9870:                             (!grep(/^\Q$lonhost\E$/,@delheadtagurls))) {
 9871:                             $loginhash{'login'}{'headtag'}{$lonhost} = $currheadtagurls{$lonhost};
 9872:                         }
 9873:                     }
 9874:                 }
 9875:             } else {
 9876:                 $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);
 9877:             }
 9878:         } else {
 9879:             $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);
 9880:         }
 9881:         if ($error) {
 9882:             &Apache::lonnet::logthis($error);
 9883:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
 9884:         }
 9885:     }
 9886:     my @delsamlimg = &Apache::loncommon::get_env_multiple('form.saml_img_del');
 9887:     my @newsamlimgs;
 9888:     foreach my $lonhost (keys(%domservers)) {
 9889:         if ($env{'form.saml_'.$lonhost}) {
 9890:             if ($env{'form.saml_img_'.$lonhost.'.filename'}) {
 9891:                 push(@newsamlimgs,$lonhost);
 9892:             }
 9893:             foreach my $item ('text','alt','url','title','notsso') {
 9894:                 $env{'form.saml_'.$item.'_'.$lonhost} =~ s/^\s+|\s+$//g;
 9895:             }
 9896:             if ($saml{$lonhost}) {
 9897:                 if (grep(/^\Q$lonhost\E$/,@delsamlimg)) {
 9898: #FIXME Need to obsolete published image
 9899:                     delete($currsaml{$lonhost}{'img'});
 9900:                     $changes{'saml'}{$lonhost} = 1;
 9901:                 }
 9902:                 if ($env{'form.saml_alt_'.$lonhost} ne $samlalt{$lonhost}) {
 9903:                     $changes{'saml'}{$lonhost} = 1;
 9904:                 }
 9905:                 if ($env{'form.saml_text_'.$lonhost} ne $samltext{$lonhost}) {
 9906:                     $changes{'saml'}{$lonhost} = 1;
 9907:                 }
 9908:                 if ($env{'form.saml_url_'.$lonhost} ne $samlurl{$lonhost}) {
 9909:                     $changes{'saml'}{$lonhost} = 1;
 9910:                 }
 9911:                 if ($env{'form.saml_title_'.$lonhost} ne $samltitle{$lonhost}) {
 9912:                     $changes{'saml'}{$lonhost} = 1;
 9913:                 }
 9914:                 if ($env{'form.saml_notsso_'.$lonhost} ne $samlnotsso{$lonhost}) {
 9915:                     $changes{'saml'}{$lonhost} = 1;
 9916:                 }
 9917:             } else {
 9918:                 $changes{'saml'}{$lonhost} = 1;
 9919:             }
 9920:             foreach my $item ('text','alt','url','title','notsso') {
 9921:                 $currsaml{$lonhost}{$item} = $env{'form.saml_'.$item.'_'.$lonhost};
 9922:             }
 9923:         } else {
 9924:             if ($saml{$lonhost}) {
 9925:                 $changes{'saml'}{$lonhost} = 1;
 9926:                 delete($currsaml{$lonhost});
 9927:             }
 9928:         }
 9929:     }
 9930:     foreach my $posshost (keys(%currsaml)) {
 9931:         unless (exists($domservers{$posshost})) {
 9932:             delete($currsaml{$posshost});
 9933:         }
 9934:     }
 9935:     %{$loginhash{'login'}{'saml'}} = %currsaml;
 9936:     if (@newsamlimgs) {
 9937:         my $error;
 9938:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
 9939:         if ($configuserok eq 'ok') {
 9940:             if ($switchserver) {
 9941:                 $error = &mt("Upload of SSO Button Image is not permitted to this server: [_1].",$switchserver);
 9942:             } elsif ($author_ok eq 'ok') {
 9943:                 foreach my $lonhost (@newsamlimgs) {
 9944:                     my $formelem = 'saml_img_'.$lonhost;
 9945:                     my ($result,$imgurl) = &publishlogo($r,'upload',$formelem,$dom,$confname,
 9946:                                                         "login/saml/$lonhost",'','',
 9947:                                                         $env{'form.saml_img_'.$lonhost.'.filename'});
 9948:                     if ($result eq 'ok') {
 9949:                         $currsaml{$lonhost}{'img'} = $imgurl;
 9950:                         $loginhash{'login'}{'saml'}{$lonhost}{'img'} = $imgurl;
 9951:                         $changes{'saml'}{$lonhost} = 1;
 9952:                     } else {
 9953:                         my $puberror = &mt("Upload of SSO button image failed for [_1] because an error occurred publishing the file in RES space. Error was: [_2].",
 9954:                                            $lonhost,$result);
 9955:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
 9956:                     }
 9957:                 }
 9958:             } else {
 9959:                 $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);
 9960:             }
 9961:         } else {
 9962:             $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);
 9963:         }
 9964:         if ($error) {
 9965:             &Apache::lonnet::logthis($error);
 9966:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
 9967:         }
 9968:     }
 9969:     &process_captcha('login',\%changes,$loginhash{'login'},$domconfig{'login'});
 9970: 
 9971:     my $defaulthelpfile = '/adm/loginproblems.html';
 9972:     my $defaulttext = &mt('Default in use');
 9973: 
 9974:     my $putresult = &Apache::lonnet::put_dom('configuration',\%loginhash,
 9975:                                              $dom);
 9976:     if ($putresult eq 'ok') {
 9977:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
 9978:         my %defaultchecked = (
 9979:                     'coursecatalog' => 'on',
 9980:                     'helpdesk'      => 'on',
 9981:                     'adminmail'     => 'off',
 9982:                     'newuser'       => 'off',
 9983:         );
 9984:         if (ref($domconfig{'login'}) eq 'HASH') {
 9985:             foreach my $item (@toggles) {
 9986:                 if ($defaultchecked{$item} eq 'on') { 
 9987:                     if (($domconfig{'login'}{$item} eq '0') &&
 9988:                         ($env{'form.'.$item} eq '1')) {
 9989:                         $changes{$item} = 1;
 9990:                     } elsif (($domconfig{'login'}{$item} eq '' ||
 9991:                               $domconfig{'login'}{$item} eq '1') &&
 9992:                              ($env{'form.'.$item} eq '0')) {
 9993:                         $changes{$item} = 1;
 9994:                     }
 9995:                 } elsif ($defaultchecked{$item} eq 'off') {
 9996:                     if (($domconfig{'login'}{$item} eq '1') &&
 9997:                         ($env{'form.'.$item} eq '0')) {
 9998:                         $changes{$item} = 1;
 9999:                     } elsif (($domconfig{'login'}{$item} eq '' ||
10000:                               $domconfig{'login'}{$item} eq '0') &&
10001:                              ($env{'form.'.$item} eq '1')) {
10002:                         $changes{$item} = 1;
10003:                     }
10004:                 }
10005:             }
10006:         }
10007:         if (keys(%changes) > 0 || $colchgtext) {
10008:             &Apache::loncommon::devalidate_domconfig_cache($dom);
10009:             if (exists($changes{'saml'})) {
10010:                 my $hostid_in_use;
10011:                 my @hosts = &Apache::lonnet::current_machine_ids();
10012:                 if (@hosts > 1) {
10013:                     foreach my $hostid (@hosts) {
10014:                         if (&Apache::lonnet::host_domain($hostid) eq $dom) {
10015:                             $hostid_in_use = $hostid;
10016:                             last;
10017:                         }
10018:                     }
10019:                 } else {
10020:                     $hostid_in_use = $r->dir_config('lonHostID');
10021:                 }
10022:                 if (($hostid_in_use) &&
10023:                     (&Apache::lonnet::host_domain($hostid_in_use) eq $dom)) {
10024:                     &Apache::lonnet::devalidate_cache_new('samllanding',$hostid_in_use);
10025:                 }
10026:                 if (ref($lastactref) eq 'HASH') {
10027:                     if (ref($changes{'saml'}) eq 'HASH') {
10028:                         my %updates;
10029:                         map { $updates{$_} = 1; } keys(%{$changes{'saml'}});
10030:                         $lastactref->{'samllanding'} = \%updates;
10031:                     }
10032:                 }
10033:             }
10034:             if (ref($lastactref) eq 'HASH') {
10035:                 $lastactref->{'domainconfig'} = 1;
10036:             }
10037:             $resulttext = &mt('Changes made:').'<ul>';
10038:             foreach my $item (sort(keys(%changes))) {
10039:                 if ($item eq 'loginvia') {
10040:                     if (ref($changes{$item}) eq 'HASH') {
10041:                         $resulttext .= '<li>'.&mt('Log-in page availability:').'<ul>';
10042:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
10043:                             if (defined($servers{$loginhash{login}{loginvia}{$lonhost}{'server'}})) {
10044:                                 if (ref($loginhash{login}{loginvia}{$lonhost}) eq 'HASH') {
10045:                                     my $protocol = $Apache::lonnet::protocol{$env{'form.'.$lonhost.'_server'}};
10046:                                     $protocol = 'http' if ($protocol ne 'https');
10047:                                     my $target = $protocol.'://'.$servers{$env{'form.'.$lonhost.'_server'}};
10048: 
10049:                                     if ($loginhash{login}{loginvia}{$lonhost}{'serverpath'} eq 'custom') {
10050:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'custompath'};
10051:                                     } else {
10052:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'serverpath'}; 
10053:                                     }
10054:                                     $resulttext .= '<li>'.&mt('Server: [_1] log-in page redirects to [_2].',$servers{$lonhost},'<a href="'.$target.'">'.$target.'</a>');
10055:                                     if ($loginhash{login}{loginvia}{$lonhost}{'exempt'} ne '') {
10056:                                         $resulttext .= '&nbsp;'.&mt('No redirection for clients from following IPs:').'&nbsp;'.$loginhash{login}{loginvia}{$lonhost}{'exempt'};
10057:                                     }
10058:                                     $resulttext .= '</li>';
10059:                                 } else {
10060:                                     $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$lonhost).'</li>';
10061:                                 }
10062:                             } else {
10063:                                 $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$servers{$lonhost}).'</li>';
10064:                             }
10065:                         }
10066:                         $resulttext .= '</ul></li>';
10067:                     }
10068:                 } elsif ($item eq 'helpurl') {
10069:                     if (ref($changes{$item}) eq 'HASH') {
10070:                         foreach my $lang (sort(keys(%{$changes{$item}}))) {
10071:                             if (grep(/^\Q$lang\E$/,@delurls)) {
10072:                                 my ($chg,$link);
10073:                                 $link = &Apache::loncommon::modal_link($defaulthelpfile,$defaulttext,600,500);
10074:                                 if ($lang eq 'nolang') {
10075:                                     $chg = &mt('custom log-in help file removed for no preferred language; [_1]',$link);
10076:                                 } else {
10077:                                     $chg = &mt('custom log-in help file removed for specific language: [_1]; [_2]',$langchoices{$lang},$link);
10078:                                 }
10079:                                 $resulttext .= '<li>'.$chg.'</li>';
10080:                             } else {
10081:                                 my $chg;
10082:                                 if ($lang eq 'nolang') {
10083:                                     $chg = &mt('custom log-in help file for no preferred language');
10084:                                 } else {
10085:                                     $chg = &mt('custom log-in help file for specific language: [_1]',$langchoices{$lang});
10086:                                 }
10087:                                 $resulttext .= '<li>'.&Apache::loncommon::modal_link(
10088:                                                       $loginhash{'login'}{'helpurl'}{$lang}.
10089:                                                       '?inhibitmenu=yes',$chg,600,500).
10090:                                                '</li>';
10091:                             }
10092:                         }
10093:                     }
10094:                 } elsif ($item eq 'headtag') {
10095:                     if (ref($changes{$item}) eq 'HASH') {
10096:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
10097:                             if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
10098:                                 $resulttext .= '<li>'.&mt('custom markup file removed for [_1]',$domservers{$lonhost}).'</li>';
10099:                             } elsif (ref($loginhash{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
10100:                                 $resulttext .= '<li><a href="'.
10101:                                                "javascript:void(open('$loginhash{'login'}{'headtag'}{$lonhost}{'url'}?inhibitmenu=yes','Custom_HeadTag',
10102:                                                'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
10103:                                                '">'.&mt('custom markup').'</a> '.&mt('(for [_1])',$servers{$lonhost}).' ';
10104:                                 if ($possexempt{$lonhost}) {
10105:                                     $resulttext .= &mt('not included for client IP(s): [_1]',$possexempt{$lonhost});
10106:                                 } else {
10107:                                     $resulttext .= &mt('included for any client IP');
10108:                                 }
10109:                                 $resulttext .= '</li>';
10110:                             }
10111:                         }
10112:                     }
10113:                 } elsif ($item eq 'saml') {
10114:                     if (ref($changes{$item}) eq 'HASH') {
10115:                         my %notlt = (
10116:                                        text   => 'Text for log-in by SSO',
10117:                                        img    => 'SSO button image',
10118:                                        alt    => 'Alt text for button image',
10119:                                        url    => 'SSO URL',
10120:                                        title  => 'Tooltip for SSO link',
10121:                                        notsso => 'Text for non-SSO log-in',
10122:                                     );
10123:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
10124:                             if (ref($currsaml{$lonhost}) eq 'HASH') {
10125:                                 $resulttext .= '<li>'.&mt("$title{$item} in use for [_1]","<b>$lonhost</b>").
10126:                                                '<ul>';
10127:                                 foreach my $key ('text','img','alt','url','title','notsso') {
10128:                                     if ($currsaml{$lonhost}{$key} eq '') {
10129:                                         $resulttext .= '<li>'.&mt("$notlt{$key} not in use").'</li>';
10130:                                     } else {
10131:                                         my $value = "'$currsaml{$lonhost}{$key}'";
10132:                                         if ($key eq 'img') {
10133:                                             $value = '<img src="'.$currsaml{$lonhost}{$key}.'" />';
10134:                                         }
10135:                                         $resulttext .= '<li>'.&mt("$notlt{$key} set to: [_1]",
10136:                                                                   $value).'</li>';
10137:                                     }
10138:                                 }
10139:                                 $resulttext .= '</ul></li>';
10140:                             } else {
10141:                                 $resulttext .= '<li>'.&mt("$title{$item} not in use for [_1]",$lonhost).'</li>';
10142:                             }
10143:                         }
10144:                     }
10145:                 } elsif ($item eq 'captcha') {
10146:                     if (ref($loginhash{'login'}) eq 'HASH') {
10147:                         my $chgtxt;
10148:                         if ($loginhash{'login'}{$item} eq 'notused') {
10149:                             $chgtxt .= &mt('No CAPTCHA validation in use for helpdesk form.');
10150:                         } else {
10151:                             my %captchas = &captcha_phrases();
10152:                             if ($captchas{$loginhash{'login'}{$item}}) {
10153:                                 $chgtxt .= &mt("Validation for helpdesk form set to $captchas{$loginhash{'login'}{$item}}.");
10154:                             } else {
10155:                                 $chgtxt .= &mt('Validation for helpdesk form set to unknown type.');
10156:                             }
10157:                         }
10158:                         $resulttext .= '<li>'.$chgtxt.'</li>';
10159:                     }
10160:                 } elsif ($item eq 'recaptchakeys') {
10161:                     if (ref($loginhash{'login'}) eq 'HASH') {
10162:                         my ($privkey,$pubkey);
10163:                         if (ref($loginhash{'login'}{$item}) eq 'HASH') {
10164:                             $pubkey = $loginhash{'login'}{$item}{'public'};
10165:                             $privkey = $loginhash{'login'}{$item}{'private'};
10166:                         }
10167:                         my $chgtxt .= &mt('ReCAPTCHA keys changes').'<ul>';
10168:                         if (!$pubkey) {
10169:                             $chgtxt .= '<li>'.&mt('Public key deleted').'</li>';
10170:                         } else {
10171:                             $chgtxt .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
10172:                         }
10173:                         if (!$privkey) {
10174:                             $chgtxt .= '<li>'.&mt('Private key deleted').'</li>';
10175:                         } else {
10176:                             $chgtxt .= '<li>'.&mt('Private key set to [_1]',$privkey).'</li>';
10177:                         }
10178:                         $chgtxt .= '</ul>';
10179:                         $resulttext .= '<li>'.$chgtxt.'</li>';
10180:                     }
10181:                 } elsif ($item eq 'recaptchaversion') {
10182:                     if (ref($loginhash{'login'}) eq 'HASH') {
10183:                         if ($loginhash{'login'}{'captcha'} eq 'recaptcha') {
10184:                             $resulttext .= '<li>'.&mt('ReCAPTCHA for helpdesk form set to version [_1]',$loginhash{'login'}{'recaptchaversion'}).
10185:                                            '</li>';
10186:                         }
10187:                     }
10188:                 } else {
10189:                     $resulttext .= '<li>'.&mt("$title{$item} set to $offon[$env{'form.'.$item}]").'</li>';
10190:                 }
10191:             }
10192:             $resulttext .= $colchgtext.'</ul>';
10193:         } else {
10194:             $resulttext = &mt('No changes made to log-in page settings');
10195:         }
10196:     } else {
10197:         $resulttext = '<span class="LC_error">'.
10198: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
10199:     }
10200:     if ($errors) {
10201:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
10202:                        $errors.'</ul>';
10203:     }
10204:     return $resulttext;
10205: }
10206: 
10207: sub check_exempt_addresses {
10208:     my ($iplist) = @_;
10209:     $iplist =~ s/^\s+//;
10210:     $iplist =~ s/\s+$//;
10211:     my @poss_ips = split(/\s*[,:]\s*/,$iplist);
10212:     my (@okips,$new);
10213:     foreach my $ip (@poss_ips) {
10214:         if ($ip =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) {
10215:             if (($1 <= 255) && ($2 <= 255) && ($3 <= 255) && ($4 <= 255)) {
10216:                 push(@okips,$ip);
10217:             }
10218:         }
10219:     }
10220:     if (@okips > 0) {
10221:         $new = join(',',@okips);
10222:     } else {
10223:         $new = '';
10224:     }
10225:     return $new;
10226: }
10227: 
10228: sub color_font_choices {
10229:     my %choices =
10230:         &Apache::lonlocal::texthash (
10231:             img => "Header",
10232:             bgs => "Background colors",
10233:             links => "Link colors",
10234:             images => "Images",
10235:             font => "Font color",
10236:             fontmenu => "Font menu",
10237:             pgbg => "Page",
10238:             tabbg => "Header",
10239:             sidebg => "Border",
10240:             link => "Link",
10241:             alink => "Active link",
10242:             vlink => "Visited link",
10243:         );
10244:     return %choices;
10245: }
10246: 
10247: sub modify_ipaccess {
10248:     my ($dom,$lastactref,%domconfig) = @_;
10249:     my (@allpos,%changes,%confhash,$errors,$resulttext);
10250:     my (@items,%deletions,%itemids,@warnings);
10251:     my ($typeorder,$types) = &commblocktype_text();
10252:     if ($env{'form.ipaccess_add'}) {
10253:         my $name = $env{'form.ipaccess_name_add'};
10254:         my ($newid,$error) = &get_ipaccess_id($dom,$name);
10255:         if ($newid) {
10256:             $itemids{'add'} = $newid;
10257:             push(@items,'add');
10258:             $changes{$newid} = 1;
10259:         } else {
10260:             $error = &mt('Failed to acquire unique ID for new IP access control item');
10261:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
10262:         }
10263:     }
10264:     if (ref($domconfig{'ipaccess'}) eq 'HASH') {
10265:         my @todelete = &Apache::loncommon::get_env_multiple('form.ipaccess_del');
10266:         if (@todelete) {
10267:             map { $deletions{$_} = 1; } @todelete;
10268:         }
10269:         my $maxnum = $env{'form.ipaccess_maxnum'};
10270:         for (my $i=0; $i<$maxnum; $i++) {
10271:             my $itemid = $env{'form.ipaccess_id_'.$i};
10272:             $itemid =~ s/\D+//g;
10273:             if (ref($domconfig{'ipaccess'}{$itemid}) eq 'HASH') {
10274:                 if ($deletions{$itemid}) {
10275:                     $changes{$itemid} = $domconfig{'ipaccess'}{$itemid}{'name'};
10276:                 } else {
10277:                     push(@items,$i);
10278:                     $itemids{$i} = $itemid;
10279:                 }
10280:             }
10281:         }
10282:     }
10283:     foreach my $idx (@items) {
10284:         my $itemid = $itemids{$idx};
10285:         next unless ($itemid);
10286:         my %current;
10287:         unless ($idx eq 'add') {
10288:             if (ref($domconfig{'ipaccess'}{$itemid}) eq 'HASH') {
10289:                 %current = %{$domconfig{'ipaccess'}{$itemid}};
10290:             }
10291:         }
10292:         my $position = $env{'form.ipaccess_pos_'.$itemid};
10293:         $position =~ s/\D+//g;
10294:         if ($position ne '') {
10295:             $allpos[$position] = $itemid;
10296:         }
10297:         my $name = $env{'form.ipaccess_name_'.$idx};
10298:         $name =~ s/^\s+|\s+$//g;
10299:         $confhash{$itemid}{'name'} = $name;
10300:         my $possrange = $env{'form.ipaccess_range_'.$idx};
10301:         $possrange =~ s/^\s+|\s+$//g;
10302:         unless ($possrange eq '') {
10303:             $possrange =~ s/[\r\n]+/\s/g;
10304:             $possrange =~ s/\s*-\s*/-/g;
10305:             $possrange =~ s/\s+/,/g;
10306:             $possrange =~ s/,+/,/g;
10307:             if ($possrange ne '') {
10308:                 my (@ok,$count);
10309:                 $count = 0;
10310:                 foreach my $poss (split(/\,/,$possrange)) {
10311:                     $count ++;
10312:                     $poss = &validate_ip_pattern($poss);
10313:                     if ($poss ne '') {
10314:                         push(@ok,$poss);
10315:                     }
10316:                 }
10317:                 my $diff = $count - scalar(@ok);
10318:                 if ($diff) {
10319:                     $errors .= '<li><span class="LC_error">'.
10320:                                &mt('[quant,_1,IP] invalid and excluded from saved value for IP range(s) for [_2]',
10321:                                    $diff,$name).
10322:                                '</span></li>';
10323:                 }
10324:                 if (@ok) {
10325:                     my @cidr_list;
10326:                     foreach my $item (@ok) {
10327:                         @cidr_list = &Net::CIDR::cidradd($item,@cidr_list);
10328:                     }
10329:                     $confhash{$itemid}{'ip'} = join(',',@cidr_list);
10330:                 }
10331:             }
10332:         }
10333:         foreach my $field ('name','ip') {
10334:             unless (($idx eq 'add') || ($changes{$itemid})) {
10335:                 if ($current{$field} ne $confhash{$itemid}{$field}) {
10336:                     $changes{$itemid} = 1;
10337:                     last;
10338:                 }
10339:             }
10340:         }
10341:         $confhash{$itemid}{'commblocks'} = {};
10342: 
10343:         my %commblocks;
10344:         map { $commblocks{$_} = 1; } &Apache::loncommon::get_env_multiple('form.ipaccess_block_'.$idx);
10345:         foreach my $type (@{$typeorder}) {
10346:             if ($commblocks{$type}) {
10347:                 $confhash{$itemid}{'commblocks'}{$type} = 'on';
10348:             }
10349:             unless (($idx eq 'add') || ($changes{$itemid})) {
10350:                 if (ref($current{'commblocks'}) eq 'HASH') {
10351:                     if ($confhash{$itemid}{'commblocks'}{$type} ne $current{'commblocks'}{$type}) {
10352:                         $changes{$itemid} = 1;
10353:                     }
10354:                 } elsif ($confhash{$itemid}{'commblocks'}{$type}) {
10355:                     $changes{$itemid} = 1;
10356:                 }
10357:             }
10358:         }
10359:         $confhash{$itemid}{'courses'} = {};
10360:         my %crsdeletions;
10361:         my @delcrs = &Apache::loncommon::get_env_multiple('form.ipaccess_course_delete_'.$idx);
10362:         if (@delcrs) {
10363:             map { $crsdeletions{$_} = 1; } @delcrs;
10364:         }
10365:         if (ref($current{'courses'}) eq 'HASH') {
10366:             foreach my $cid (sort(keys(%{$current{'courses'}}))) {
10367:                 if ($crsdeletions{$cid}) {
10368:                     $changes{$itemid} = 1;
10369:                 } else {
10370:                     $confhash{$itemid}{'courses'}{$cid} = 1;
10371:                 }
10372:             }
10373:         }
10374:         $env{'form.ipaccess_cnum_'.$idx} =~ s/^\s+|\s+$//g;
10375:         $env{'form.ipaccess_cdom_'.$idx} =~ s/^\s+|\s+$//g;
10376:         if (($env{'form.ipaccess_cnum_'.$idx} =~ /^$match_courseid$/) &&
10377:             ($env{'form.ipaccess_cdom_'.$idx} =~ /^$match_domain$/)) {
10378:             if (&Apache::lonnet::homeserver($env{'form.ipaccess_cnum_'.$idx},
10379:                                             $env{'form.ipaccess_cdom_'.$idx}) eq 'no_host') {
10380:                 $errors .= '<li><span class="LC_error">'.
10381:                            &mt('Invalid courseID [_1] omitted from list of allowed courses',
10382:                                $env{'form.ipaccess_cdom_'.$idx}.'_'.$env{'form.ipaccess_cnum_'.$idx}).
10383:                            '</span></li>';
10384:             } else {
10385:                 $confhash{$itemid}{'courses'}{$env{'form.ipaccess_cdom_'.$idx}.'_'.$env{'form.ipaccess_cnum_'.$idx}} = 1;
10386:                 $changes{$itemid} = 1;
10387:             }
10388:         }
10389:     }
10390:     if (@allpos > 0) {
10391:         my $idx = 0;
10392:         foreach my $itemid (@allpos) {
10393:             if ($itemid ne '') {
10394:                 $confhash{$itemid}{'order'} = $idx;
10395:                 unless ($changes{$itemid}) {
10396:                     if (ref($domconfig{'ipaccess'}) eq 'HASH') {
10397:                         if (ref($domconfig{'ipaccess'}{$itemid}) eq 'HASH') {
10398:                             if ($domconfig{'ipaccess'}{$itemid}{'order'} ne $idx) {
10399:                                 $changes{$itemid} = 1;
10400:                             }
10401:                         }
10402:                     }
10403:                 }
10404:                 $idx ++;
10405:             }
10406:         }
10407:     }
10408:     if (keys(%changes)) {
10409:         my %defaultshash = (
10410:                               ipaccess => \%confhash,
10411:                            );
10412:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
10413:                                                  $dom);
10414:         if ($putresult eq 'ok') {
10415:             my $cachetime = 1800;
10416:             &Apache::lonnet::do_cache_new('ipaccess',$dom,\%confhash,$cachetime);
10417:             if (ref($lastactref) eq 'HASH') {
10418:                 $lastactref->{'ipaccess'} = 1;
10419:             }
10420:             $resulttext = &mt('Changes made:').'<ul>';
10421:             my %bynum;
10422:             foreach my $itemid (sort(keys(%changes))) {
10423:                 if (ref($confhash{$itemid}) eq 'HASH') {
10424:                     my $position = $confhash{$itemid}{'order'};
10425:                     if ($position =~ /^\d+$/) {
10426:                         $bynum{$position} = $itemid;
10427:                     }
10428:                 }
10429:             }
10430:             if (keys(%deletions)) {
10431:                 foreach my $itemid (sort { $a <=> $b } keys(%deletions)) {
10432:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
10433:                 }
10434:             }
10435:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
10436:                 my $itemid = $bynum{$pos};
10437:                 if (ref($confhash{$itemid}) eq 'HASH') {
10438:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'name'}.'</b><ul>';
10439:                     my $position = $pos + 1;
10440:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
10441:                     if ($confhash{$itemid}{'ip'} eq '') {
10442:                         $resulttext .= '<li>'.&mt('No IP Range(s) set').'</li>';
10443:                     } else {
10444:                         $resulttext .= '<li>'.&mt('IP Range(s): [_1]',$confhash{$itemid}{'ip'}).'</li>';
10445:                     }
10446:                     if (keys(%{$confhash{$itemid}{'commblocks'}})) {
10447:                         $resulttext .= '<li>'.&mt('Functionality Blocked: [_1]',
10448:                                                   join(', ', map { $types->{$_}; } sort(keys(%{$confhash{$itemid}{'commblocks'}})))).
10449:                                        '</li>';
10450:                     } else {
10451:                         $resulttext .= '<li>'.&mt('No functionality blocked').'</li>';
10452:                     }
10453:                     if (keys(%{$confhash{$itemid}{'courses'}})) {
10454:                         my @courses;
10455:                         foreach my $cid (sort(keys(%{$confhash{$itemid}{'courses'}}))) {
10456:                             my %courseinfo = &Apache::lonnet::coursedescription($cid,{'one_time' => 1});
10457:                             push(@courses,$courseinfo{'description'}.' ('.$cid.')');
10458:                         }
10459:                         $resulttext .= '<li>'.&mt('Courses/Communities allowed').':<ul><li>'.
10460:                                              join('</li><li>',@courses).'</li></ul>';
10461:                     } else {
10462:                         $resulttext .= '<li>'.&mt('No courses allowed').'</li>';
10463:                     }
10464:                     $resulttext .= '</ul></li>';
10465:                 }
10466:             }
10467:             $resulttext .= '</ul>';
10468:         } else {
10469:             $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
10470:         }
10471:     } else {
10472:         $resulttext = &mt('No changes made');
10473:     }
10474:     if ($errors) {
10475:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
10476:                        $errors.'</ul></p>';
10477:     }
10478:     return $resulttext;
10479: }
10480: 
10481: sub get_ipaccess_id {
10482:     my ($domain,$location) = @_;
10483:     # get lock on ipaccess db
10484:     my $lockhash = {
10485:                       lock => $env{'user.name'}.
10486:                               ':'.$env{'user.domain'},
10487:                    };
10488:     my $tries = 0;
10489:     my $gotlock = &Apache::lonnet::newput_dom('ipaccess',$lockhash,$domain);
10490:     my ($id,$error);
10491: 
10492:     while (($gotlock ne 'ok') && ($tries<10)) {
10493:         $tries ++;
10494:         sleep (0.1);
10495:         $gotlock = &Apache::lonnet::newput_dom('ipaccess',$lockhash,$domain);
10496:     }
10497:     if ($gotlock eq 'ok') {
10498:         my %currids = &Apache::lonnet::dump_dom('ipaccess',$domain);
10499:         if ($currids{'lock'}) {
10500:             delete($currids{'lock'});
10501:             if (keys(%currids)) {
10502:                 my @curr = sort { $a <=> $b } keys(%currids);
10503:                 if ($curr[-1] =~ /^\d+$/) {
10504:                     $id = 1 + $curr[-1];
10505:                 }
10506:             } else {
10507:                 $id = 1;
10508:             }
10509:             if ($id) {
10510:                 unless (&Apache::lonnet::newput_dom('ipaccess',{ $id => $location },$domain) eq 'ok') {
10511:                     $error = 'nostore';
10512:                 }
10513:             } else {
10514:                 $error = 'nonumber';
10515:             }
10516:         }
10517:         my $dellockoutcome = &Apache::lonnet::del_dom('ipaccess',['lock'],$domain);
10518:     } else {
10519:         $error = 'nolock';
10520:     }
10521:     return ($id,$error);
10522: }
10523: 
10524: sub modify_rolecolors {
10525:     my ($r,$dom,$confname,$roles,$lastactref,%domconfig) = @_;
10526:     my ($resulttext,%rolehash);
10527:     $rolehash{'rolecolors'} = {};
10528:     if (ref($domconfig{'rolecolors'}) ne 'HASH') {
10529:         if ($domconfig{'rolecolors'} eq '') {
10530:             $domconfig{'rolecolors'} = {};
10531:         }
10532:     }
10533:     my ($errors,%changes) = &modify_colors($r,$dom,$confname,$roles,
10534:                          $domconfig{'rolecolors'},$rolehash{'rolecolors'});
10535:     my $putresult = &Apache::lonnet::put_dom('configuration',\%rolehash,
10536:                                              $dom);
10537:     if ($putresult eq 'ok') {
10538:         if (keys(%changes) > 0) {
10539:             &Apache::loncommon::devalidate_domconfig_cache($dom);
10540:             if (ref($lastactref) eq 'HASH') {
10541:                 $lastactref->{'domainconfig'} = 1;
10542:             }
10543:             $resulttext = &display_colorchgs($dom,\%changes,$roles,
10544:                                              $rolehash{'rolecolors'});
10545:         } else {
10546:             $resulttext = &mt('No changes made to default color schemes');
10547:         }
10548:     } else {
10549:         $resulttext = '<span class="LC_error">'.
10550: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
10551:     }
10552:     if ($errors) {
10553:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
10554:                        $errors.'</ul>';
10555:     }
10556:     return $resulttext;
10557: }
10558: 
10559: sub modify_colors {
10560:     my ($r,$dom,$confname,$roles,$domconfig,$confhash) = @_;
10561:     my (%changes,%choices);
10562:     my @bgs;
10563:     my @links = ('link','alink','vlink');
10564:     my @logintext;
10565:     my @images;
10566:     my $servadm = $r->dir_config('lonAdmEMail');
10567:     my $errors;
10568:     my %defaults;
10569:     foreach my $role (@{$roles}) {
10570:         if ($role eq 'login') {
10571:             %choices = &login_choices();
10572:             @logintext = ('textcol','bgcol');
10573:         } else {
10574:             %choices = &color_font_choices();
10575:         }
10576:         if ($role eq 'login') {
10577:             @images = ('img','logo','domlogo','login');
10578:             @bgs = ('pgbg','mainbg','sidebg');
10579:         } else {
10580:             @images = ('img');
10581:             @bgs = ('pgbg','tabbg','sidebg');
10582:         }
10583:         my %defaults = &role_defaults($role,\@bgs,\@links,\@images,\@logintext);
10584:         unless ($env{'form.'.$role.'_font'} eq $defaults{'font'}) {
10585:             $confhash->{$role}{'font'} = $env{'form.'.$role.'_font'};
10586:         }
10587:         if ($role eq 'login') {
10588:             foreach my $item (@logintext) {
10589:                 $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
10590:                 if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
10591:                     $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
10592:                 }
10593:                 unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'logintext'}{$item})) {
10594:                     $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
10595:                 }
10596:             }
10597:         } else {
10598:             $env{'form.'.$role.'_fontmenu'} = lc($env{'form.'.$role.'_fontmenu'});
10599:             if ($env{'form.'.$role.'_fontmenu'} =~ /^\w+/) {
10600:                 $env{'form.'.$role.'_fontmenu'} = '#'.$env{'form.'.$role.'_fontmenu'};
10601:             }
10602:             unless($env{'form.'.$role.'_fontmenu'} eq lc($defaults{'fontmenu'})) {
10603:                 $confhash->{$role}{'fontmenu'} = $env{'form.'.$role.'_fontmenu'};
10604:             }
10605:         }
10606:         foreach my $item (@bgs) {
10607:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
10608:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
10609:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
10610:             }
10611:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'bgs'}{$item})) {
10612:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
10613:             }
10614:         }
10615:         foreach my $item (@links) {
10616:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
10617:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
10618:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
10619:             }
10620:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'links'}{$item})) {
10621:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
10622:             }
10623:         }
10624:         my ($configuserok,$author_ok,$switchserver) = 
10625:             &config_check($dom,$confname,$servadm);
10626:         my ($width,$height) = &thumb_dimensions();
10627:         if (ref($domconfig->{$role}) ne 'HASH') {
10628:             $domconfig->{$role} = {};
10629:         }
10630:         foreach my $img (@images) {
10631:             if (($role eq 'login') && (($img eq 'img') || ($img eq 'logo'))) {  
10632:                 if (defined($env{'form.login_showlogo_'.$img})) {
10633:                     $confhash->{$role}{'showlogo'}{$img} = 1;
10634:                 } else { 
10635:                     $confhash->{$role}{'showlogo'}{$img} = 0;
10636:                 }
10637:             } 
10638: 	    if ( ! $env{'form.'.$role.'_'.$img.'.filename'} 
10639: 		 && !defined($domconfig->{$role}{$img})
10640: 		 && !$env{'form.'.$role.'_del_'.$img}
10641: 		 && $env{'form.'.$role.'_import_'.$img}) {
10642: 		# import the old configured image from the .tab setting
10643: 		# if they haven't provided a new one 
10644: 		$domconfig->{$role}{$img} = 
10645: 		    $env{'form.'.$role.'_import_'.$img};
10646: 	    }
10647:             if ($env{'form.'.$role.'_'.$img.'.filename'} ne '') {
10648:                 my $error;
10649:                 if ($configuserok eq 'ok') {
10650:                     if ($switchserver) {
10651:                         $error = &mt("Upload of [_1] image for $role page(s) is not permitted to this server: [_2]",$choices{$img},$switchserver);
10652:                     } else {
10653:                         if ($author_ok eq 'ok') {
10654:                             my ($result,$logourl) = 
10655:                                 &publishlogo($r,'upload',$role.'_'.$img,
10656:                                            $dom,$confname,$img,$width,$height);
10657:                             if ($result eq 'ok') {
10658:                                 $confhash->{$role}{$img} = $logourl;
10659:                                 $changes{$role}{'images'}{$img} = 1;
10660:                             } else {
10661:                                 $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);
10662:                             }
10663:                         } else {
10664:                             $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);
10665:                         }
10666:                     }
10667:                 } else {
10668:                     $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);
10669:                 }
10670:                 if ($error) {
10671:                     &Apache::lonnet::logthis($error);
10672:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
10673:                 }
10674:             } elsif ($domconfig->{$role}{$img} ne '') {
10675:                 if ($domconfig->{$role}{$img} !~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
10676:                     my $error;
10677:                     if ($configuserok eq 'ok') {
10678: # is confname an author?
10679:                         if ($switchserver eq '') {
10680:                             if ($author_ok eq 'ok') {
10681:                                 my ($result,$logourl) = 
10682:                                &publishlogo($r,'copy',$domconfig->{$role}{$img},
10683:                                             $dom,$confname,$img,$width,$height);
10684:                                 if ($result eq 'ok') {
10685:                                     $confhash->{$role}{$img} = $logourl;
10686: 				    $changes{$role}{'images'}{$img} = 1;
10687:                                 }
10688:                             }
10689:                         }
10690:                     }
10691:                 }
10692:             }
10693:         }
10694:         if (ref($domconfig) eq 'HASH') {
10695:             if (ref($domconfig->{$role}) eq 'HASH') {
10696:                 foreach my $img (@images) {
10697:                     if ($domconfig->{$role}{$img} ne '') {
10698:                         if ($env{'form.'.$role.'_del_'.$img}) {
10699:                             $confhash->{$role}{$img} = '';
10700:                             $changes{$role}{'images'}{$img} = 1;
10701:                         } else {
10702:                             if ($confhash->{$role}{$img} eq '') {
10703:                                 $confhash->{$role}{$img} = $domconfig->{$role}{$img};
10704:                             }
10705:                         }
10706:                     } else {
10707:                         if ($env{'form.'.$role.'_del_'.$img}) {
10708:                             $confhash->{$role}{$img} = '';
10709:                             $changes{$role}{'images'}{$img} = 1;
10710:                         } 
10711:                     }
10712:                     if (($role eq 'login') && (($img eq 'logo') || ($img eq 'img'))) {
10713:                         if (ref($domconfig->{'login'}{'showlogo'}) eq 'HASH') {
10714:                             if ($confhash->{$role}{'showlogo'}{$img} ne 
10715:                                 $domconfig->{$role}{'showlogo'}{$img}) {
10716:                                 $changes{$role}{'showlogo'}{$img} = 1; 
10717:                             }
10718:                         } else {
10719:                             if ($confhash->{$role}{'showlogo'}{$img} == 0) {
10720:                                 $changes{$role}{'showlogo'}{$img} = 1;
10721:                             }
10722:                         }
10723:                     }
10724:                 }
10725:                 if ($domconfig->{$role}{'font'} ne '') {
10726:                     if ($confhash->{$role}{'font'} ne $domconfig->{$role}{'font'}) {
10727:                         $changes{$role}{'font'} = 1;
10728:                     }
10729:                 } else {
10730:                     if ($confhash->{$role}{'font'}) {
10731:                         $changes{$role}{'font'} = 1;
10732:                     }
10733:                 }
10734:                 if ($role ne 'login') {
10735:                     if ($domconfig->{$role}{'fontmenu'} ne '') {
10736:                         if ($confhash->{$role}{'fontmenu'} ne $domconfig->{$role}{'fontmenu'}) {
10737:                             $changes{$role}{'fontmenu'} = 1;
10738:                         }
10739:                     } else {
10740:                         if ($confhash->{$role}{'fontmenu'}) {
10741:                             $changes{$role}{'fontmenu'} = 1;
10742:                         }
10743:                     }
10744:                 }
10745:                 foreach my $item (@bgs) {
10746:                     if ($domconfig->{$role}{$item} ne '') {
10747:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
10748:                             $changes{$role}{'bgs'}{$item} = 1;
10749:                         } 
10750:                     } else {
10751:                         if ($confhash->{$role}{$item}) {
10752:                             $changes{$role}{'bgs'}{$item} = 1;
10753:                         }
10754:                     }
10755:                 }
10756:                 foreach my $item (@links) {
10757:                     if ($domconfig->{$role}{$item} ne '') {
10758:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
10759:                             $changes{$role}{'links'}{$item} = 1;
10760:                         }
10761:                     } else {
10762:                         if ($confhash->{$role}{$item}) {
10763:                             $changes{$role}{'links'}{$item} = 1;
10764:                         }
10765:                     }
10766:                 }
10767:                 foreach my $item (@logintext) {
10768:                     if ($domconfig->{$role}{$item} ne '') {
10769:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
10770:                             $changes{$role}{'logintext'}{$item} = 1;
10771:                         }
10772:                     } else {
10773:                         if ($confhash->{$role}{$item}) {
10774:                             $changes{$role}{'logintext'}{$item} = 1;
10775:                         }
10776:                     }
10777:                 }
10778:             } else {
10779:                 &default_change_checker($role,\@images,\@links,\@bgs,
10780:                                         \@logintext,$confhash,\%changes); 
10781:             }
10782:         } else {
10783:             &default_change_checker($role,\@images,\@links,\@bgs,
10784:                                     \@logintext,$confhash,\%changes); 
10785:         }
10786:     }
10787:     return ($errors,%changes);
10788: }
10789: 
10790: sub config_check {
10791:     my ($dom,$confname,$servadm) = @_;
10792:     my ($configuserok,$author_ok,$switchserver,%currroles);
10793:     my $uhome = &Apache::lonnet::homeserver($confname,$dom,1);
10794:     ($configuserok,%currroles) = &check_configuser($uhome,$dom,
10795:                                                    $confname,$servadm);
10796:     if ($configuserok eq 'ok') {
10797:         $switchserver = &check_switchserver($dom,$confname);
10798:         if ($switchserver eq '') {
10799:             $author_ok = &check_authorstatus($dom,$confname,%currroles);
10800:         }
10801:     }
10802:     return ($configuserok,$author_ok,$switchserver);
10803: }
10804: 
10805: sub default_change_checker {
10806:     my ($role,$images,$links,$bgs,$logintext,$confhash,$changes) = @_;
10807:     foreach my $item (@{$links}) {
10808:         if ($confhash->{$role}{$item}) {
10809:             $changes->{$role}{'links'}{$item} = 1;
10810:         }
10811:     }
10812:     foreach my $item (@{$bgs}) {
10813:         if ($confhash->{$role}{$item}) {
10814:             $changes->{$role}{'bgs'}{$item} = 1;
10815:         }
10816:     }
10817:     foreach my $item (@{$logintext}) {
10818:         if ($confhash->{$role}{$item}) {
10819:             $changes->{$role}{'logintext'}{$item} = 1;
10820:         }
10821:     }
10822:     foreach my $img (@{$images}) {
10823:         if ($env{'form.'.$role.'_del_'.$img}) {
10824:             $confhash->{$role}{$img} = '';
10825:             $changes->{$role}{'images'}{$img} = 1;
10826:         }
10827:         if ($role eq 'login') {
10828:             if ($confhash->{$role}{'showlogo'}{$img} == 0) {
10829:                 $changes->{$role}{'showlogo'}{$img} = 1;
10830:             }
10831:         }
10832:     }
10833:     if ($confhash->{$role}{'font'}) {
10834:         $changes->{$role}{'font'} = 1;
10835:     }
10836: }
10837: 
10838: sub display_colorchgs {
10839:     my ($dom,$changes,$roles,$confhash) = @_;
10840:     my (%choices,$resulttext);
10841:     if (!grep(/^login$/,@{$roles})) {
10842:         $resulttext = &mt('Changes made:').'<br />';
10843:     }
10844:     foreach my $role (@{$roles}) {
10845:         if ($role eq 'login') {
10846:             %choices = &login_choices();
10847:         } else {
10848:             %choices = &color_font_choices();
10849:         }
10850:         if (ref($changes->{$role}) eq 'HASH') {
10851:             if ($role ne 'login') {
10852:                 $resulttext .= '<h4>'.&mt($role).'</h4>';
10853:             }
10854:             foreach my $key (sort(keys(%{$changes->{$role}}))) {
10855:                 if ($role ne 'login') {
10856:                     $resulttext .= '<ul>';
10857:                 }
10858:                 if (ref($changes->{$role}{$key}) eq 'HASH') {
10859:                     if ($role ne 'login') {
10860:                         $resulttext .= '<li>'.&mt($choices{$key}).':<ul>';
10861:                     }
10862:                     foreach my $item (sort(keys(%{$changes->{$role}{$key}}))) {
10863:                         if (($role eq 'login') && ($key eq 'showlogo')) {
10864:                             if ($confhash->{$role}{$key}{$item}) {
10865:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to be displayed").'</li>';
10866:                             } else {
10867:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to not be displayed").'</li>';
10868:                             }
10869:                         } elsif ($confhash->{$role}{$item} eq '') {
10870:                             $resulttext .= '<li>'.&mt("$choices{$item} set to default").'</li>';
10871:                         } else {
10872:                             my $newitem = $confhash->{$role}{$item};
10873:                             if ($key eq 'images') {
10874:                                 $newitem = '<img src="'.$confhash->{$role}{$item}.'" alt="'.$choices{$item}.'" valign="bottom" />';
10875:                             }
10876:                             $resulttext .= '<li>'.&mt("$choices{$item} set to [_1]",$newitem).'</li>';
10877:                         }
10878:                     }
10879:                     if ($role ne 'login') {
10880:                         $resulttext .= '</ul></li>';
10881:                     }
10882:                 } else {
10883:                     if ($confhash->{$role}{$key} eq '') {
10884:                         $resulttext .= '<li>'.&mt("$choices{$key} set to default").'</li>';
10885:                     } else {
10886:                         $resulttext .= '<li>'.&mt("$choices{$key} set to [_1]",$confhash->{$role}{$key}).'</li>';
10887:                     }
10888:                 }
10889:                 if ($role ne 'login') {
10890:                     $resulttext .= '</ul>';
10891:                 }
10892:             }
10893:         }
10894:     }
10895:     return $resulttext;
10896: }
10897: 
10898: sub thumb_dimensions {
10899:     return ('200','50');
10900: }
10901: 
10902: sub check_dimensions {
10903:     my ($inputfile) = @_;
10904:     my ($fullwidth,$fullheight);
10905:     if ($inputfile =~ m|^[/\w.\-]+$|) {
10906:         if (open(PIPE,"identify $inputfile 2>&1 |")) {
10907:             my $imageinfo = <PIPE>;
10908:             if (!close(PIPE)) {
10909:                 &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
10910:             }
10911:             chomp($imageinfo);
10912:             my ($fullsize) = 
10913:                 ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
10914:             if ($fullsize) {
10915:                 ($fullwidth,$fullheight) = split(/x/,$fullsize);
10916:             }
10917:         }
10918:     }
10919:     return ($fullwidth,$fullheight);
10920: }
10921: 
10922: sub check_configuser {
10923:     my ($uhome,$dom,$confname,$servadm) = @_;
10924:     my ($configuserok,%currroles);
10925:     if ($uhome eq 'no_host') {
10926:         srand( time() ^ ($$ + ($$ << 15))  ); # Seed rand.
10927:         my $configpass = &LONCAPA::Enrollment::create_password($dom);
10928:         $configuserok = 
10929:             &Apache::lonnet::modifyuser($dom,$confname,'','internal',
10930:                              $configpass,'','','','','',undef,$servadm);
10931:     } else {
10932:         $configuserok = 'ok';
10933:         %currroles = 
10934:             &Apache::lonnet::get_my_roles($confname,$dom,'userroles');
10935:     }
10936:     return ($configuserok,%currroles);
10937: }
10938: 
10939: sub check_authorstatus {
10940:     my ($dom,$confname,%currroles) = @_;
10941:     my $author_ok;
10942:     if (!$currroles{':'.$dom.':au'}) {
10943:         my $start = time;
10944:         my $end = 0;
10945:         $author_ok = 
10946:             &Apache::lonnet::assignrole($dom,$confname,'/'.$dom.'/',
10947:                                         'au',$end,$start,'','','domconfig');
10948:     } else {
10949:         $author_ok = 'ok';
10950:     }
10951:     return $author_ok;
10952: }
10953: 
10954: sub publishlogo {
10955:     my ($r,$action,$formname,$dom,$confname,$subdir,$thumbwidth,$thumbheight,$savefileas) = @_;
10956:     my ($output,$fname,$logourl);
10957:     if ($action eq 'upload') {
10958:         $fname=$env{'form.'.$formname.'.filename'};
10959:         chop($env{'form.'.$formname});
10960:     } else {
10961:         ($fname) = ($formname =~ /([^\/]+)$/);
10962:     }
10963:     if ($savefileas ne '') {
10964:         $fname = $savefileas;
10965:     }
10966:     $fname=&Apache::lonnet::clean_filename($fname);
10967: # See if there is anything left
10968:     unless ($fname) { return ('error: no uploaded file'); }
10969:     $fname="$subdir/$fname";
10970:     my $docroot=$r->dir_config('lonDocRoot');
10971:     my $filepath="$docroot/priv";
10972:     my $relpath = "$dom/$confname";
10973:     my ($fnamepath,$file,$fetchthumb);
10974:     $file=$fname;
10975:     if ($fname=~m|/|) {
10976:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
10977:     }
10978:     my @parts=split(/\//,"$filepath/$relpath/$fnamepath");
10979:     my $count;
10980:     for ($count=5;$count<=$#parts;$count++) {
10981:         $filepath.="/$parts[$count]";
10982:         if ((-e $filepath)!=1) {
10983:             mkdir($filepath,02770);
10984:         }
10985:     }
10986:     # Check for bad extension and disallow upload
10987:     if ($file=~/\.(\w+)$/ &&
10988:         (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
10989:         $output = 
10990:             &mt('Invalid file extension ([_1]) - reserved for internal use.',$1); 
10991:     } elsif ($file=~/\.(\w+)$/ &&
10992:         !defined(&Apache::loncommon::fileembstyle($1))) {
10993:         $output = &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
10994:     } elsif ($file=~/\.(\d+)\.(\w+)$/) {
10995:         $output = &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
10996:     } elsif (-d "$filepath/$file") {
10997:         $output = &mt('Filename is a directory name - rename the file and re-upload');
10998:     } else {
10999:         my $source = $filepath.'/'.$file;
11000:         my $logfile;
11001:         if (!open($logfile,">>",$source.'.log')) {
11002:             return (&mt('No write permission to Authoring Space'));
11003:         }
11004:         print $logfile
11005: "\n================= Publish ".localtime()." ================\n".
11006: $env{'user.name'}.':'.$env{'user.domain'}."\n";
11007: # Save the file
11008:         if (!open(FH,">",$source)) {
11009:             &Apache::lonnet::logthis('Failed to create '.$source);
11010:             return (&mt('Failed to create file'));
11011:         }
11012:         if ($action eq 'upload') {
11013:             if (!print FH ($env{'form.'.$formname})) {
11014:                 &Apache::lonnet::logthis('Failed to write to '.$source);
11015:                 return (&mt('Failed to write file'));
11016:             }
11017:         } else {
11018:             my $original = &Apache::lonnet::filelocation('',$formname);
11019:             if(!copy($original,$source)) {
11020:                 &Apache::lonnet::logthis('Failed to copy '.$original.' to '.$source);
11021:                 return (&mt('Failed to write file'));
11022:             }
11023:         }
11024:         close(FH);
11025:         chmod(0660, $source); # Permissions to rw-rw---.
11026: 
11027:         my $targetdir=$docroot.'/res/'.$dom.'/'.$confname .'/'.$fnamepath;
11028:         my $copyfile=$targetdir.'/'.$file;
11029: 
11030:         my @parts=split(/\//,$targetdir);
11031:         my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
11032:         for (my $count=5;$count<=$#parts;$count++) {
11033:             $path.="/$parts[$count]";
11034:             if (!-e $path) {
11035:                 print $logfile "\nCreating directory ".$path;
11036:                 mkdir($path,02770);
11037:             }
11038:         }
11039:         my $versionresult;
11040:         if (-e $copyfile) {
11041:             $versionresult = &logo_versioning($targetdir,$file,$logfile);
11042:         } else {
11043:             $versionresult = 'ok';
11044:         }
11045:         if ($versionresult eq 'ok') {
11046:             if (copy($source,$copyfile)) {
11047:                 print $logfile "\nCopied original source to ".$copyfile."\n";
11048:                 $output = 'ok';
11049:                 $logourl = '/res/'.$dom.'/'.$confname.'/'.$fname;
11050:                 push(@{$modified_urls},[$copyfile,$source]);
11051:                 my $metaoutput = 
11052:                     &write_metadata($dom,$confname,$formname,$targetdir,$file,$logfile);
11053:                 unless ($registered_cleanup) {
11054:                     my $handlers = $r->get_handlers('PerlCleanupHandler');
11055:                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
11056:                     $registered_cleanup=1;
11057:                 }
11058:             } else {
11059:                 print $logfile "\nUnable to write ".$copyfile.':'.$!."\n";
11060:                 $output = &mt('Failed to copy file to RES space').", $!";
11061:             }
11062:             if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
11063:                 my $inputfile = $filepath.'/'.$file;
11064:                 my $outfile = $filepath.'/'.'tn-'.$file;
11065:                 my ($fullwidth,$fullheight) = &check_dimensions($inputfile);
11066:                 if ($fullwidth ne '' && $fullheight ne '') { 
11067:                     if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
11068:                         my $thumbsize = $thumbwidth.'x'.$thumbheight;
11069:                         my @args = ('convert','-sample',$thumbsize,$inputfile,$outfile);
11070:                         system({$args[0]} @args);
11071:                         chmod(0660, $filepath.'/tn-'.$file);
11072:                         if (-e $outfile) {
11073:                             my $copyfile=$targetdir.'/tn-'.$file;
11074:                             if (copy($outfile,$copyfile)) {
11075:                                 print $logfile "\nCopied source to ".$copyfile."\n";
11076:                                 my $thumb_metaoutput = 
11077:                                     &write_metadata($dom,$confname,$formname,
11078:                                                     $targetdir,'tn-'.$file,$logfile);
11079:                                 push(@{$modified_urls},[$copyfile,$outfile]);
11080:                                 unless ($registered_cleanup) {
11081:                                     my $handlers = $r->get_handlers('PerlCleanupHandler');
11082:                                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
11083:                                     $registered_cleanup=1;
11084:                                 }
11085:                             } else {
11086:                                 print $logfile "\nUnable to write ".$copyfile.
11087:                                                ':'.$!."\n";
11088:                             }
11089:                         }
11090:                     }
11091:                 }
11092:             }
11093:         } else {
11094:             $output = $versionresult;
11095:         }
11096:     }
11097:     return ($output,$logourl);
11098: }
11099: 
11100: sub logo_versioning {
11101:     my ($targetdir,$file,$logfile) = @_;
11102:     my $target = $targetdir.'/'.$file;
11103:     my ($maxversion,$fn,$extn,$output);
11104:     $maxversion = 0;
11105:     if ($file =~ /^(.+)\.(\w+)$/) {
11106:         $fn=$1;
11107:         $extn=$2;
11108:     }
11109:     opendir(DIR,$targetdir);
11110:     while (my $filename=readdir(DIR)) {
11111:         if ($filename=~/\Q$fn\E\.(\d+)\.\Q$extn\E$/) {
11112:             $maxversion=($1>$maxversion)?$1:$maxversion;
11113:         }
11114:     }
11115:     $maxversion++;
11116:     print $logfile "\nCreating old version ".$maxversion."\n";
11117:     my $copyfile=$targetdir.'/'.$fn.'.'.$maxversion.'.'.$extn;
11118:     if (copy($target,$copyfile)) {
11119:         print $logfile "Copied old target to ".$copyfile."\n";
11120:         $copyfile=$copyfile.'.meta';
11121:         if (copy($target.'.meta',$copyfile)) {
11122:             print $logfile "Copied old target metadata to ".$copyfile."\n";
11123:             $output = 'ok';
11124:         } else {
11125:             print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
11126:             $output = &mt('Failed to copy old meta').", $!, ";
11127:         }
11128:     } else {
11129:         print $logfile "Unable to write ".$copyfile.':'.$!."\n";
11130:         $output = &mt('Failed to copy old target').", $!, ";
11131:     }
11132:     return $output;
11133: }
11134: 
11135: sub write_metadata {
11136:     my ($dom,$confname,$formname,$targetdir,$file,$logfile) = @_;
11137:     my (%metadatafields,%metadatakeys,$output);
11138:     $metadatafields{'title'}=$formname;
11139:     $metadatafields{'creationdate'}=time;
11140:     $metadatafields{'lastrevisiondate'}=time;
11141:     $metadatafields{'copyright'}='public';
11142:     $metadatafields{'modifyinguser'}=$env{'user.name'}.':'.
11143:                                          $env{'user.domain'};
11144:     $metadatafields{'authorspace'}=$confname.':'.$dom;
11145:     $metadatafields{'domain'}=$dom;
11146:     {
11147:         print $logfile "\nWrite metadata file for ".$targetdir.'/'.$file;
11148:         my $mfh;
11149:         if (open($mfh,">",$targetdir.'/'.$file.'.meta')) {
11150:             foreach (sort(keys(%metadatafields))) {
11151:                 unless ($_=~/\./) {
11152:                     my $unikey=$_;
11153:                     $unikey=~/^([A-Za-z]+)/;
11154:                     my $tag=$1;
11155:                     $tag=~tr/A-Z/a-z/;
11156:                     print $mfh "\n\<$tag";
11157:                     foreach (split(/\,/,$metadatakeys{$unikey})) {
11158:                         my $value=$metadatafields{$unikey.'.'.$_};
11159:                         $value=~s/\"/\'\'/g;
11160:                         print $mfh ' '.$_.'="'.$value.'"';
11161:                     }
11162:                     print $mfh '>'.
11163:                         &HTML::Entities::encode($metadatafields{$unikey},'<>&"')
11164:                             .'</'.$tag.'>';
11165:                 }
11166:             }
11167:             $output = 'ok';
11168:             print $logfile "\nWrote metadata";
11169:             close($mfh);
11170:         } else {
11171:             print $logfile "\nFailed to open metadata file";
11172:             $output = &mt('Could not write metadata');
11173:         }
11174:     }
11175:     return $output;
11176: }
11177: 
11178: sub notifysubscribed {
11179:     foreach my $targetsource (@{$modified_urls}){
11180:         next unless (ref($targetsource) eq 'ARRAY');
11181:         my ($target,$source)=@{$targetsource};
11182:         if ($source ne '') {
11183:             if (open(my $logfh,">>",$source.'.log')) {
11184:                 print $logfh "\nCleanup phase: Notifications\n";
11185:                 my @subscribed=&subscribed_hosts($target);
11186:                 foreach my $subhost (@subscribed) {
11187:                     print $logfh "\nNotifying host ".$subhost.':';
11188:                     my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
11189:                     print $logfh $reply;
11190:                 }
11191:                 my @subscribedmeta=&subscribed_hosts("$target.meta");
11192:                 foreach my $subhost (@subscribedmeta) {
11193:                     print $logfh "\nNotifying host for metadata only ".$subhost.':';
11194:                     my $reply=&Apache::lonnet::critical('update:'.$target.'.meta',
11195:                                                         $subhost);
11196:                     print $logfh $reply;
11197:                 }
11198:                 print $logfh "\n============ Done ============\n";
11199:                 close($logfh);
11200:             }
11201:         }
11202:     }
11203:     return OK;
11204: }
11205: 
11206: sub subscribed_hosts {
11207:     my ($target) = @_;
11208:     my @subscribed;
11209:     if (open(my $fh,"<","$target.subscription")) {
11210:         while (my $subline=<$fh>) {
11211:             if ($subline =~ /^($match_lonid):/) {
11212:                 my $host = $1;
11213:                 if ($host ne $Apache::lonnet::perlvar{'lonHostID'}) {
11214:                     unless (grep(/^\Q$host\E$/,@subscribed)) {
11215:                         push(@subscribed,$host);
11216:                     }
11217:                 }
11218:             }
11219:         }
11220:     }
11221:     return @subscribed;
11222: }
11223: 
11224: sub check_switchserver {
11225:     my ($dom,$confname) = @_;
11226:     my ($allowed,$switchserver);
11227:     my $home = &Apache::lonnet::homeserver($confname,$dom);
11228:     if ($home eq 'no_host') {
11229:         $home = &Apache::lonnet::domain($dom,'primary');
11230:     }
11231:     my @ids=&Apache::lonnet::current_machine_ids();
11232:     foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
11233:     if (!$allowed) {
11234: 	$switchserver='<a href="/adm/switchserver?otherserver='.$home.'&amp;role=dc./'.$dom.'/&amp;destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
11235:     }
11236:     return $switchserver;
11237: }
11238: 
11239: sub modify_quotas {
11240:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
11241:     my ($context,@usertools,@options,%validations,%titles,%confhash,%toolshash,
11242:         %limithash,$toolregexp,%conditions,$resulttext,%changes,$confname,$configuserok,
11243:         $author_ok,$switchserver,$errors,$validationitemsref,$validationnamesref,
11244:         $validationfieldsref);
11245:     if ($action eq 'quotas') {
11246:         $context = 'tools'; 
11247:     } else {
11248:         $context = $action;
11249:     }
11250:     if ($context eq 'requestcourses') {
11251:         @usertools = ('official','unofficial','community','textbook');
11252:         @options =('norequest','approval','validate','autolimit');
11253:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
11254:         %titles = &courserequest_titles();
11255:         $toolregexp = join('|',@usertools);
11256:         %conditions = &courserequest_conditions();
11257:         $confname = $dom.'-domainconfig';
11258:         my $servadm = $r->dir_config('lonAdmEMail');
11259:         ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
11260:         ($validationitemsref,$validationnamesref,$validationfieldsref) = 
11261:             &Apache::loncoursequeueadmin::requestcourses_validation_types();
11262:     } elsif ($context eq 'requestauthor') {
11263:         @usertools = ('author');
11264:         %titles = &authorrequest_titles();
11265:     } else {
11266:         @usertools = ('aboutme','blog','webdav','portfolio');
11267:         %titles = &tool_titles();
11268:     }
11269:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
11270:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
11271:     foreach my $key (keys(%env)) {
11272:         if ($context eq 'requestcourses') {
11273:             if ($key =~ /^form\.crsreq_($toolregexp)_(.+)$/) {
11274:                 my $item = $1;
11275:                 my $type = $2;
11276:                 if ($type =~ /^limit_(.+)/) {
11277:                     $limithash{$item}{$1} = $env{$key};
11278:                 } else {
11279:                     $confhash{$item}{$type} = $env{$key};
11280:                 }
11281:             }
11282:         } elsif ($context eq 'requestauthor') {
11283:             if ($key =~ /^\Qform.authorreq_\E(.+)$/) {
11284:                 $confhash{$1} = $env{$key};
11285:             }
11286:         } else {
11287:             if ($key =~ /^form\.quota_(.+)$/) {
11288:                 $confhash{'defaultquota'}{$1} = $env{$key};
11289:             } elsif ($key =~ /^form\.authorquota_(.+)$/) {
11290:                 $confhash{'authorquota'}{$1} = $env{$key};
11291:             } elsif ($key =~ /^form\.\Q$context\E_(.+)$/) {
11292:                 @{$toolshash{$1}} = &Apache::loncommon::get_env_multiple($key);
11293:             }
11294:         }
11295:     }
11296:     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
11297:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.'.$context.'notifyapproval');
11298:         @approvalnotify = sort(@approvalnotify);
11299:         $confhash{'notify'}{'approval'} = join(',',@approvalnotify);
11300:         my @crstypes = ('official','unofficial','community','textbook');
11301:         my @hasuniquecode = &Apache::loncommon::get_env_multiple('form.uniquecode');
11302:         foreach my $type (@hasuniquecode) {
11303:             if (grep(/^\Q$type\E$/,@crstypes)) {
11304:                 $confhash{'uniquecode'}{$type} = 1;
11305:             }
11306:         }
11307:         my (%newbook,%allpos);
11308:         if ($context eq 'requestcourses') {
11309:             foreach my $type ('textbooks','templates') {
11310:                 @{$allpos{$type}} = (); 
11311:                 my $invalid;
11312:                 if ($type eq 'textbooks') {
11313:                     $invalid = &mt('Invalid LON-CAPA course for textbook');
11314:                 } else {
11315:                     $invalid = &mt('Invalid LON-CAPA course for template');
11316:                 }
11317:                 if ($env{'form.'.$type.'_addbook'}) {
11318:                     if (($env{'form.'.$type.'_addbook_cnum'} =~ /^$match_courseid$/) &&
11319:                         ($env{'form.'.$type.'_addbook_cdom'} =~ /^$match_domain$/)) {
11320:                         if (&Apache::lonnet::homeserver($env{'form.'.$type.'_addbook_cnum'},
11321:                                                         $env{'form.'.$type.'_addbook_cdom'}) eq 'no_host') {
11322:                             $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
11323:                         } else {
11324:                             $newbook{$type} = $env{'form.'.$type.'_addbook_cdom'}.'_'.$env{'form.'.$type.'_addbook_cnum'};
11325:                             my $position = $env{'form.'.$type.'_addbook_pos'};
11326:                             $position =~ s/\D+//g;
11327:                             if ($position ne '') {
11328:                                 $allpos{$type}[$position] = $newbook{$type};
11329:                             }
11330:                         }
11331:                     } else {
11332:                         $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
11333:                     }
11334:                 }
11335:             } 
11336:         }
11337:         if (ref($domconfig{$action}) eq 'HASH') {
11338:             if (ref($domconfig{$action}{'notify'}) eq 'HASH') {
11339:                 if ($domconfig{$action}{'notify'}{'approval'} ne $confhash{'notify'}{'approval'}) {
11340:                     $changes{'notify'}{'approval'} = 1;
11341:                 }
11342:             } else {
11343:                 if ($confhash{'notify'}{'approval'}) {
11344:                     $changes{'notify'}{'approval'} = 1;
11345:                 }
11346:             }
11347:             if (ref($domconfig{$action}{'uniquecode'}) eq 'HASH') {
11348:                 if (ref($confhash{'uniquecode'}) eq 'HASH') {
11349:                     foreach my $crstype (keys(%{$domconfig{$action}{'uniquecode'}})) {
11350:                         unless ($confhash{'uniquecode'}{$crstype}) {
11351:                             $changes{'uniquecode'} = 1;
11352:                         }
11353:                     }
11354:                     unless ($changes{'uniquecode'}) {
11355:                         foreach my $crstype (keys(%{$confhash{'uniquecode'}})) {
11356:                             unless ($domconfig{$action}{'uniquecode'}{$crstype}) {
11357:                                 $changes{'uniquecode'} = 1;
11358:                             }
11359:                         }
11360:                     }
11361:                } else {
11362:                    $changes{'uniquecode'} = 1;
11363:                }
11364:             } elsif (ref($confhash{'uniquecode'}) eq 'HASH') {
11365:                 $changes{'uniquecode'} = 1;
11366:             }
11367:             if ($context eq 'requestcourses') {
11368:                 foreach my $type ('textbooks','templates') {
11369:                     if (ref($domconfig{$action}{$type}) eq 'HASH') {
11370:                         my %deletions;
11371:                         my @todelete = &Apache::loncommon::get_env_multiple('form.'.$type.'_del');
11372:                         if (@todelete) {
11373:                             map { $deletions{$_} = 1; } @todelete;
11374:                         }
11375:                         my %imgdeletions;
11376:                         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.'.$type.'_image_del');
11377:                         if (@todeleteimages) {
11378:                             map { $imgdeletions{$_} = 1; } @todeleteimages;
11379:                         }
11380:                         my $maxnum = $env{'form.'.$type.'_maxnum'};
11381:                         for (my $i=0; $i<=$maxnum; $i++) {
11382:                             my $itemid = $env{'form.'.$type.'_id_'.$i};
11383:                             my ($key) = ($itemid =~ /^\Q$type\E_(\w+)$/); 
11384:                             if (ref($domconfig{$action}{$type}{$key}) eq 'HASH') {
11385:                                 if ($deletions{$key}) {
11386:                                     if ($domconfig{$action}{$type}{$key}{'image'}) {
11387:                                         #FIXME need to obsolete item in RES space
11388:                                     }
11389:                                     next;
11390:                                 } else {
11391:                                     my $newpos = $env{'form.'.$itemid};
11392:                                     $newpos =~ s/\D+//g;
11393:                                     foreach my $item ('subject','title','publisher','author') {
11394:                                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
11395:                                                  ($type eq 'templates'));
11396:                                         $confhash{$type}{$key}{$item} = $env{'form.'.$type.'_'.$item.'_'.$i};
11397:                                         if ($domconfig{$action}{$type}{$key}{$item} ne $confhash{$type}{$key}{$item}) {
11398:                                             $changes{$type}{$key} = 1;
11399:                                         }
11400:                                     }
11401:                                     $allpos{$type}[$newpos] = $key;
11402:                                 }
11403:                                 if ($imgdeletions{$key}) {
11404:                                     $changes{$type}{$key} = 1;
11405:                                     #FIXME need to obsolete item in RES space
11406:                                 } elsif ($env{'form.'.$type.'_image_'.$i.'.filename'}) {
11407:                                     my ($cdom,$cnum) = split(/_/,$key);
11408:                                     if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
11409:                                         $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
11410:                                     } else {
11411:                                         my ($imgurl,$error) = &process_textbook_image($r,$dom,$confname,$type.'_image_'.$i,
11412:                                                                                       $cdom,$cnum,$type,$configuserok,
11413:                                                                                       $switchserver,$author_ok);
11414:                                         if ($imgurl) {
11415:                                             $confhash{$type}{$key}{'image'} = $imgurl;
11416:                                             $changes{$type}{$key} = 1; 
11417:                                         }
11418:                                         if ($error) {
11419:                                             &Apache::lonnet::logthis($error);
11420:                                             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
11421:                                         }
11422:                                     } 
11423:                                 } elsif ($domconfig{$action}{$type}{$key}{'image'}) {
11424:                                     $confhash{$type}{$key}{'image'} = 
11425:                                         $domconfig{$action}{$type}{$key}{'image'};
11426:                                 }
11427:                             }
11428:                         }
11429:                     }
11430:                 }
11431:             }
11432:         } else {
11433:             if ($confhash{'notify'}{'approval'}) {
11434:                 $changes{'notify'}{'approval'} = 1;
11435:             }
11436:             if (ref($confhash{'uniquecode'} eq 'HASH')) {
11437:                 $changes{'uniquecode'} = 1;
11438:             }
11439:         }
11440:         if ($context eq 'requestcourses') {
11441:             foreach my $type ('textbooks','templates') {
11442:                 if ($newbook{$type}) {
11443:                     $changes{$type}{$newbook{$type}} = 1;
11444:                     foreach my $item ('subject','title','publisher','author') {
11445:                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
11446:                                  ($type eq 'template'));
11447:                         $env{'form.'.$type.'_addbook_'.$item} =~ s/(`)/'/g;
11448:                         if ($env{'form.'.$type.'_addbook_'.$item}) {
11449:                             $confhash{$type}{$newbook{$type}}{$item} = $env{'form.'.$type.'_addbook_'.$item};
11450:                         }
11451:                     }
11452:                     if ($type eq 'textbooks') {
11453:                         if ($env{'form.'.$type.'_addbook_image.filename'} ne '') {
11454:                             my ($cdom,$cnum) = split(/_/,$newbook{$type});
11455:                             if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
11456:                                 $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
11457:                             } else {
11458:                                 my ($imageurl,$error) =
11459:                                     &process_textbook_image($r,$dom,$confname,$type.'_addbook_image',$cdom,$cnum,$type,
11460:                                                             $configuserok,$switchserver,$author_ok);
11461:                                 if ($imageurl) {
11462:                                     $confhash{$type}{$newbook{$type}}{'image'} = $imageurl;
11463:                                 }
11464:                                 if ($error) {
11465:                                     &Apache::lonnet::logthis($error);
11466:                                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
11467:                                 }
11468:                             }
11469:                         }
11470:                     }
11471:                 }
11472:                 if (@{$allpos{$type}} > 0) {
11473:                     my $idx = 0;
11474:                     foreach my $item (@{$allpos{$type}}) {
11475:                         if ($item ne '') {
11476:                             $confhash{$type}{$item}{'order'} = $idx;
11477:                             if (ref($domconfig{$action}) eq 'HASH') {
11478:                                 if (ref($domconfig{$action}{$type}) eq 'HASH') {
11479:                                     if (ref($domconfig{$action}{$type}{$item}) eq 'HASH') {
11480:                                         if ($domconfig{$action}{$type}{$item}{'order'} ne $idx) {
11481:                                             $changes{$type}{$item} = 1;
11482:                                         }
11483:                                     }
11484:                                 }
11485:                             }
11486:                             $idx ++;
11487:                         }
11488:                     }
11489:                 }
11490:             }
11491:             if (ref($validationitemsref) eq 'ARRAY') {
11492:                 foreach my $item (@{$validationitemsref}) {
11493:                     if ($item eq 'fields') {
11494:                         my @changed;
11495:                         @{$confhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.requestcourses_validation_'.$item);
11496:                         if (@{$confhash{'validation'}{$item}} > 0) {
11497:                             @{$confhash{'validation'}{$item}} = sort(@{$confhash{'validation'}{$item}});
11498:                         }
11499:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
11500:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
11501:                                 if (ref($domconfig{'requestcourses'}{'validation'}{$item}) eq 'ARRAY') {
11502:                                     @changed = &Apache::loncommon::compare_arrays($confhash{'validation'}{$item},
11503:                                                                                   $domconfig{'requestcourses'}{'validation'}{$item});
11504:                                 } else {
11505:                                     @changed = @{$confhash{'validation'}{$item}};
11506:                                 }
11507:                             } else {
11508:                                 @changed = @{$confhash{'validation'}{$item}};
11509:                             }
11510:                         } else {
11511:                             @changed = @{$confhash{'validation'}{$item}};
11512:                         }
11513:                         if (@changed) {
11514:                             if ($confhash{'validation'}{$item}) {
11515:                                 $changes{'validation'}{$item} = join(', ',@{$confhash{'validation'}{$item}});
11516:                             } else {
11517:                                 $changes{'validation'}{$item} = &mt('None');
11518:                             }
11519:                         }
11520:                     } else {
11521:                         $confhash{'validation'}{$item} = $env{'form.requestcourses_validation_'.$item};
11522:                         if ($item eq 'markup') {
11523:                             if ($env{'form.requestcourses_validation_'.$item}) {
11524:                                 $env{'form.requestcourses_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
11525:                             }
11526:                         }
11527:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
11528:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
11529:                                 if ($domconfig{'requestcourses'}{'validation'}{$item} ne $confhash{'validation'}{$item}) {
11530:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
11531:                                 }
11532:                             } else {
11533:                                 if ($confhash{'validation'}{$item} ne '') {
11534:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
11535:                                 }
11536:                             }
11537:                         } else {
11538:                             if ($confhash{'validation'}{$item} ne '') {
11539:                                 $changes{'validation'}{$item} = $confhash{'validation'}{$item};
11540:                             }
11541:                         }
11542:                     }
11543:                 }
11544:             }
11545:             if ($env{'form.validationdc'}) {
11546:                 my $newval = $env{'form.validationdc'};
11547:                 my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
11548:                 if (exists($domcoords{$newval})) {
11549:                     $confhash{'validation'}{'dc'} = $newval;
11550:                 }
11551:             }
11552:             if (ref($confhash{'validation'}) eq 'HASH') {
11553:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
11554:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
11555:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
11556:                             unless ($confhash{'validation'}{'dc'} eq $domconfig{'requestcourses'}{'validation'}{'dc'}) {
11557:                                 if ($confhash{'validation'}{'dc'} eq '') {
11558:                                     $changes{'validation'}{'dc'} = &mt('None');
11559:                                 } else {
11560:                                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
11561:                                 }
11562:                             }
11563:                         } elsif ($confhash{'validation'}{'dc'} ne '') {
11564:                             $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
11565:                         }
11566:                     } elsif ($confhash{'validation'}{'dc'} ne '') {
11567:                         $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
11568:                     }
11569:                 } elsif ($confhash{'validation'}{'dc'} ne '') {
11570:                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
11571:                 }
11572:             } else {
11573:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
11574:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
11575:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
11576:                             $changes{'validation'}{'dc'} = &mt('None');
11577:                         }
11578:                     }
11579:                 }
11580:             }
11581:         }
11582:     } else {
11583:         $confhash{'defaultquota'}{'default'} = $env{'form.defaultquota'};
11584:         $confhash{'authorquota'}{'default'} = $env{'form.authorquota'};
11585:     }
11586:     foreach my $item (@usertools) {
11587:         foreach my $type (@{$types},'default','_LC_adv') {
11588:             my $unset; 
11589:             if ($context eq 'requestcourses') {
11590:                 $unset = '0';
11591:                 if ($type eq '_LC_adv') {
11592:                     $unset = '';
11593:                 }
11594:                 if ($confhash{$item}{$type} eq 'autolimit') {
11595:                     $confhash{$item}{$type} .= '=';
11596:                     unless ($limithash{$item}{$type} =~ /\D/) {
11597:                         $confhash{$item}{$type} .= $limithash{$item}{$type};
11598:                     }
11599:                 }
11600:             } elsif ($context eq 'requestauthor') {
11601:                 $unset = '0';
11602:                 if ($type eq '_LC_adv') {
11603:                     $unset = '';
11604:                 }
11605:             } else {
11606:                 if (grep(/^\Q$type\E$/,@{$toolshash{$item}})) {
11607:                     $confhash{$item}{$type} = 1;
11608:                 } else {
11609:                     $confhash{$item}{$type} = 0;
11610:                 }
11611:             }
11612:             if (ref($domconfig{$action}) eq 'HASH') {
11613:                 if ($action eq 'requestauthor') {
11614:                     if ($domconfig{$action}{$type} ne $confhash{$type}) {
11615:                         $changes{$type} = 1;
11616:                     }
11617:                 } elsif (ref($domconfig{$action}{$item}) eq 'HASH') {
11618:                     if ($domconfig{$action}{$item}{$type} ne $confhash{$item}{$type}) {
11619:                         $changes{$item}{$type} = 1;
11620:                     }
11621:                 } else {
11622:                     if ($context eq 'requestcourses') {
11623:                         if ($confhash{$item}{$type} ne $unset) {
11624:                             $changes{$item}{$type} = 1;
11625:                         }
11626:                     } else {
11627:                         if (!$confhash{$item}{$type}) {
11628:                             $changes{$item}{$type} = 1;
11629:                         }
11630:                     }
11631:                 }
11632:             } else {
11633:                 if ($context eq 'requestcourses') {
11634:                     if ($confhash{$item}{$type} ne $unset) {
11635:                         $changes{$item}{$type} = 1;
11636:                     }
11637:                 } elsif ($context eq 'requestauthor') {
11638:                     if ($confhash{$type} ne $unset) {
11639:                         $changes{$type} = 1;
11640:                     }
11641:                 } else {
11642:                     if (!$confhash{$item}{$type}) {
11643:                         $changes{$item}{$type} = 1;
11644:                     }
11645:                 }
11646:             }
11647:         }
11648:     }
11649:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
11650:         if (ref($domconfig{'quotas'}) eq 'HASH') {
11651:             if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
11652:                 foreach my $key (keys(%{$domconfig{'quotas'}{'defaultquota'}})) {
11653:                     if (exists($confhash{'defaultquota'}{$key})) {
11654:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{'defaultquota'}{$key}) {
11655:                             $changes{'defaultquota'}{$key} = 1;
11656:                         }
11657:                     } else {
11658:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{'defaultquota'}{$key};
11659:                     }
11660:                 }
11661:             } else {
11662:                 foreach my $key (keys(%{$domconfig{'quotas'}})) {
11663:                     if (exists($confhash{'defaultquota'}{$key})) {
11664:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{$key}) {
11665:                             $changes{'defaultquota'}{$key} = 1;
11666:                         }
11667:                     } else {
11668:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{$key};
11669:                     }
11670:                 }
11671:             }
11672:             if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
11673:                 foreach my $key (keys(%{$domconfig{'quotas'}{'authorquota'}})) {
11674:                     if (exists($confhash{'authorquota'}{$key})) {
11675:                         if ($confhash{'authorquota'}{$key} ne $domconfig{'quotas'}{'authorquota'}{$key}) {
11676:                             $changes{'authorquota'}{$key} = 1;
11677:                         }
11678:                     } else {
11679:                         $confhash{'authorquota'}{$key} = $domconfig{'quotas'}{'authorquota'}{$key};
11680:                     }
11681:                 }
11682:             }
11683:         }
11684:         if (ref($confhash{'defaultquota'}) eq 'HASH') {
11685:             foreach my $key (keys(%{$confhash{'defaultquota'}})) {
11686:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
11687:                     if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
11688:                         if (!exists($domconfig{'quotas'}{'defaultquota'}{$key})) {
11689:                             $changes{'defaultquota'}{$key} = 1;
11690:                         }
11691:                     } else {
11692:                         if (!exists($domconfig{'quotas'}{$key})) {
11693:                             $changes{'defaultquota'}{$key} = 1;
11694:                         }
11695:                     }
11696:                 } else {
11697:                     $changes{'defaultquota'}{$key} = 1;
11698:                 }
11699:             }
11700:         }
11701:         if (ref($confhash{'authorquota'}) eq 'HASH') {
11702:             foreach my $key (keys(%{$confhash{'authorquota'}})) {
11703:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
11704:                     if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
11705:                         if (!exists($domconfig{'quotas'}{'authorquota'}{$key})) {
11706:                             $changes{'authorquota'}{$key} = 1;
11707:                         }
11708:                     } else {
11709:                         $changes{'authorquota'}{$key} = 1;
11710:                     }
11711:                 } else {
11712:                     $changes{'authorquota'}{$key} = 1;
11713:                 }
11714:             }
11715:         }
11716:     }
11717: 
11718:     if ($context eq 'requestauthor') {
11719:         $domdefaults{'requestauthor'} = \%confhash;
11720:     } else {
11721:         foreach my $key (keys(%confhash)) {
11722:             unless (($context eq 'requestcourses') && (($key eq 'textbooks') || ($key eq 'templates'))) {
11723:                 $domdefaults{$key} = $confhash{$key};
11724:             }
11725:         }
11726:     }
11727: 
11728:     my %quotahash = (
11729:                       $action => { %confhash }
11730:                     );
11731:     my $putresult = &Apache::lonnet::put_dom('configuration',\%quotahash,
11732:                                              $dom);
11733:     if ($putresult eq 'ok') {
11734:         if (keys(%changes) > 0) {
11735:             my $cachetime = 24*60*60;
11736:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
11737:             if (ref($lastactref) eq 'HASH') {
11738:                 $lastactref->{'domdefaults'} = 1;
11739:             }
11740:             $resulttext = &mt('Changes made:').'<ul>';
11741:             unless (($context eq 'requestcourses') ||
11742:                     ($context eq 'requestauthor')) {
11743:                 if (ref($changes{'defaultquota'}) eq 'HASH') {
11744:                     $resulttext .= '<li>'.&mt('Portfolio default quotas').'<ul>';
11745:                     foreach my $type (@{$types},'default') {
11746:                         if (defined($changes{'defaultquota'}{$type})) {
11747:                             my $typetitle = $usertypes->{$type};
11748:                             if ($type eq 'default') {
11749:                                 $typetitle = $othertitle;
11750:                             }
11751:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'defaultquota'}{$type}).'</li>';
11752:                         }
11753:                     }
11754:                     $resulttext .= '</ul></li>';
11755:                 }
11756:                 if (ref($changes{'authorquota'}) eq 'HASH') {
11757:                     $resulttext .= '<li>'.&mt('Authoring Space default quotas').'<ul>';
11758:                     foreach my $type (@{$types},'default') {
11759:                         if (defined($changes{'authorquota'}{$type})) {
11760:                             my $typetitle = $usertypes->{$type};
11761:                             if ($type eq 'default') {
11762:                                 $typetitle = $othertitle;
11763:                             }
11764:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'authorquota'}{$type}).'</li>';
11765:                         }
11766:                     }
11767:                     $resulttext .= '</ul></li>';
11768:                 }
11769:             }
11770:             my %newenv;
11771:             foreach my $item (@usertools) {
11772:                 my (%haschgs,%inconf);
11773:                 if ($context eq 'requestauthor') {
11774:                     %haschgs = %changes;
11775:                     %inconf = %confhash;
11776:                 } else {
11777:                     if (ref($changes{$item}) eq 'HASH') {
11778:                         %haschgs = %{$changes{$item}};
11779:                     }
11780:                     if (ref($confhash{$item}) eq 'HASH') {
11781:                         %inconf = %{$confhash{$item}};
11782:                     }
11783:                 }
11784:                 if (keys(%haschgs) > 0) {
11785:                     my $newacc = 
11786:                         &Apache::lonnet::usertools_access($env{'user.name'},
11787:                                                           $env{'user.domain'},
11788:                                                           $item,'reload',$context);
11789:                     if (($context eq 'requestcourses') ||
11790:                         ($context eq 'requestauthor')) {
11791:                         if ($env{'environment.canrequest.'.$item} ne $newacc) {
11792:                             $newenv{'environment.canrequest.'.$item} = $newacc;
11793:                         }
11794:                     } else {
11795:                         if ($env{'environment.availabletools.'.$item} ne $newacc) { 
11796:                             $newenv{'environment.availabletools.'.$item} = $newacc;
11797:                         }
11798:                     }
11799:                     unless ($context eq 'requestauthor') {
11800:                         $resulttext .= '<li>'.$titles{$item}.'<ul>';
11801:                     }
11802:                     foreach my $type (@{$types},'default','_LC_adv') {
11803:                         if ($haschgs{$type}) {
11804:                             my $typetitle = $usertypes->{$type};
11805:                             if ($type eq 'default') {
11806:                                 $typetitle = $othertitle;
11807:                             } elsif ($type eq '_LC_adv') {
11808:                                 $typetitle = 'LON-CAPA Advanced Users'; 
11809:                             }
11810:                             if ($inconf{$type}) {
11811:                                 if ($context eq 'requestcourses') {
11812:                                     my $cond;
11813:                                     if ($inconf{$type} =~ /^autolimit=(\d*)$/) {
11814:                                         if ($1 eq '') {
11815:                                             $cond = &mt('(Automatic processing of any request).');
11816:                                         } else {
11817:                                             $cond = &mt('(Automatic processing of requests up to limit of [quant,_1,request] per user).',$1);
11818:                                         }
11819:                                     } else { 
11820:                                         $cond = $conditions{$inconf{$type}};
11821:                                     }
11822:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1].',$typetitle).' '.$cond.'</li>';
11823:                                 } elsif ($context eq 'requestauthor') {
11824:                                     $resulttext .= '<li>'.&mt('Set to "[_1]" for "[_2]".',
11825:                                                              $titles{$inconf{$type}},$typetitle);
11826: 
11827:                                 } else {
11828:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1]',$typetitle).'</li>';
11829:                                 }
11830:                             } else {
11831:                                 if ($type eq '_LC_adv') {
11832:                                     if ($inconf{$type} eq '0') {
11833:                                         $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
11834:                                     } else { 
11835:                                         $resulttext .= '<li>'.&mt('No override set for [_1]',$typetitle).'</li>';
11836:                                     }
11837:                                 } else {
11838:                                     $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
11839:                                 }
11840:                             }
11841:                         }
11842:                     }
11843:                     unless ($context eq 'requestauthor') {
11844:                         $resulttext .= '</ul></li>';
11845:                     }
11846:                 }
11847:             }
11848:             if (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
11849:                 if (ref($changes{'notify'}) eq 'HASH') {
11850:                     if ($changes{'notify'}{'approval'}) {
11851:                         if (ref($confhash{'notify'}) eq 'HASH') {
11852:                             if ($confhash{'notify'}{'approval'}) {
11853:                                 $resulttext .= '<li>'.&mt('Notification of requests requiring approval will be sent to: ').$confhash{'notify'}{'approval'}.'</li>';
11854:                             } else {
11855:                                 $resulttext .= '<li>'.&mt('No Domain Coordinators will receive notification of requests requiring approval.').'</li>';
11856:                             }
11857:                         }
11858:                     }
11859:                 }
11860:             }
11861:             if ($action eq 'requestcourses') {
11862:                 my @offon = ('off','on');
11863:                 if ($changes{'uniquecode'}) {
11864:                     if (ref($confhash{'uniquecode'}) eq 'HASH') {
11865:                         my $codestr = join(' ',map{ &mt($_); } sort(keys(%{$confhash{'uniquecode'}})));
11866:                         $resulttext .= '<li>'.
11867:                                        &mt('Generation of six character code as course identifier for distribution to students set to on for: [_1].','<b>'.$codestr.'</b>').
11868:                                        '</li>';
11869:                     } else {
11870:                         $resulttext .= '<li>'.&mt('Generation of six character code as course identifier for distribution to students set to off.').
11871:                                        '</li>';
11872:                     }
11873:                 }
11874:                 foreach my $type ('textbooks','templates') {
11875:                     if (ref($changes{$type}) eq 'HASH') {
11876:                         $resulttext .= '<li>'.&mt("Available $type updated").'<ul>';
11877:                         foreach my $key (sort(keys(%{$changes{$type}}))) {
11878:                             my %coursehash = &Apache::lonnet::coursedescription($key);
11879:                             my $coursetitle = $coursehash{'description'};
11880:                             my $position = $confhash{$type}{$key}{'order'} + 1;
11881:                             $resulttext .= '<li>';
11882:                             foreach my $item ('subject','title','publisher','author') {
11883:                                 next if ((($item eq 'author') || ($item eq 'publisher')) &&
11884:                                          ($type eq 'templates'));
11885:                                 my $name = $item.':';
11886:                                 $name =~ s/^(\w)/\U$1/;
11887:                                 $resulttext .= &mt($name).' '.$confhash{$type}{$key}{$item}.'<br />';
11888:                             }
11889:                             $resulttext .= ' '.&mt('Order: [_1]',$position).'<br />';
11890:                             if ($type eq 'textbooks') {
11891:                                 if ($confhash{$type}{$key}{'image'}) {
11892:                                     $resulttext .= ' '.&mt('Image: [_1]',
11893:                                                    '<img src="'.$confhash{$type}{$key}{'image'}.'"'.
11894:                                                    ' alt="Textbook cover" />').'<br />';
11895:                                 }
11896:                             }
11897:                             $resulttext .= ' '.&mt('LON-CAPA Course: [_1]',$coursetitle).'</li>';
11898:                         }
11899:                         $resulttext .= '</ul></li>';
11900:                     }
11901:                 }
11902:                 if (ref($changes{'validation'}) eq 'HASH') {
11903:                     if ((ref($validationitemsref) eq 'ARRAY') && (ref($validationnamesref) eq 'HASH')) {
11904:                         $resulttext .= '<li>'.&mt('Validation of courses/communities updated').'<ul>';
11905:                         foreach my $item (@{$validationitemsref}) {
11906:                             if (exists($changes{'validation'}{$item})) {
11907:                                 if ($item eq 'markup') {
11908:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
11909:                                                               '<br /><pre>'.$changes{'validation'}{$item}.'</pre>').'</li>';
11910:                                 } else {
11911:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
11912:                                                               '<b>'.$changes{'validation'}{$item}.'</b>').'</li>';
11913:                                 }
11914:                             }
11915:                         }
11916:                         if (exists($changes{'validation'}{'dc'})) {
11917:                             $resulttext .= '<li>'.&mt('Validated course requests identified as processed by: [_1]',
11918:                                                      '<b>'.$changes{'validation'}{'dc'}.'</b>').'</li>';
11919:                         }
11920:                     }
11921:                 }
11922:             }
11923:             $resulttext .= '</ul>';
11924:             if (keys(%newenv)) {
11925:                 &Apache::lonnet::appenv(\%newenv);
11926:             }
11927:         } else {
11928:             if ($context eq 'requestcourses') {
11929:                 $resulttext = &mt('No changes made to rights to request creation of courses.');
11930:             } elsif ($context eq 'requestauthor') {
11931:                 $resulttext = &mt('No changes made to rights to request author space.');
11932:             } else {
11933:                 $resulttext = &mt('No changes made to availability of personal information pages, blogs, portfolios or default quotas');
11934:             }
11935:         }
11936:     } else {
11937:         $resulttext = '<span class="LC_error">'.
11938: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
11939:     }
11940:     if ($errors) {
11941:         $resulttext .= '<p>'.&mt('The following errors occurred when modifying Textbook settings.').
11942:                        '<ul>'.$errors.'</ul></p>';
11943:     }
11944:     return $resulttext;
11945: }
11946: 
11947: sub process_textbook_image {
11948:     my ($r,$dom,$confname,$caller,$cdom,$cnum,$type,$configuserok,$switchserver,$author_ok) = @_;
11949:     my $filename = $env{'form.'.$caller.'.filename'};
11950:     my ($error,$url);
11951:     my ($width,$height) = (50,50);
11952:     if ($configuserok eq 'ok') {
11953:         if ($switchserver) {
11954:             $error = &mt('Upload of textbook image is not permitted to this server: [_1]',
11955:                          $switchserver);
11956:         } elsif ($author_ok eq 'ok') {
11957:             my ($result,$imageurl) =
11958:                 &publishlogo($r,'upload',$caller,$dom,$confname,
11959:                              "$type/$cdom/$cnum/cover",$width,$height);
11960:             if ($result eq 'ok') {
11961:                 $url = $imageurl;
11962:             } else {
11963:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
11964:             }
11965:         } else {
11966:             $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);
11967:         }
11968:     } else {
11969:         $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);
11970:     }
11971:     return ($url,$error);
11972: }
11973: 
11974: sub modify_ltitools {
11975:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
11976:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
11977:     my ($newid,@allpos,%changes,%confhash,%encconfig,$errors,$resulttext);
11978:     my $confname = $dom.'-domainconfig';
11979:     my $servadm = $r->dir_config('lonAdmEMail');
11980:     my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
11981:     my (%posslti,%possfield);
11982:     my @courseroles = ('cc','in','ta','ep','st');
11983:     my @ltiroles = qw(Instructor ContentDeveloper TeachingAssistant Learner);
11984:     map { $posslti{$_} = 1; } @ltiroles;
11985:     my @allfields = ('fullname','firstname','lastname','email','user','roles');
11986:     map { $possfield{$_} = 1; } @allfields;
11987:     my %lt = &ltitools_names();
11988:     if ($env{'form.ltitools_add'}) {
11989:         my $title = $env{'form.ltitools_add_title'};
11990:         $title =~ s/(`)/'/g;
11991:         ($newid,my $error) = &get_ltitools_id($dom,$title);
11992:         if ($newid) {
11993:             my $position = $env{'form.ltitools_add_pos'};
11994:             $position =~ s/\D+//g;
11995:             if ($position ne '') {
11996:                 $allpos[$position] = $newid;
11997:             }
11998:             $changes{$newid} = 1;
11999:             foreach my $item ('title','url','key','secret','lifetime') {
12000:                 $env{'form.ltitools_add_'.$item} =~ s/(`)/'/g;
12001:                 if ($item eq 'lifetime') {
12002:                     $env{'form.ltitools_add_'.$item} =~ s/[^\d.]//g;
12003:                 }
12004:                 if ($env{'form.ltitools_add_'.$item}) {
12005:                     if (($item eq 'key') || ($item eq 'secret')) {
12006:                         $encconfig{$newid}{$item} = $env{'form.ltitools_add_'.$item};
12007:                     } else {
12008:                         $confhash{$newid}{$item} = $env{'form.ltitools_add_'.$item};
12009:                     }
12010:                 }
12011:             }
12012:             if ($env{'form.ltitools_add_version'} eq 'LTI-1p0') {
12013:                 $confhash{$newid}{'version'} = $env{'form.ltitools_add_version'};
12014:             }
12015:             if ($env{'form.ltitools_add_msgtype'} eq 'basic-lti-launch-request') {
12016:                 $confhash{$newid}{'msgtype'} = $env{'form.ltitools_add_msgtype'};
12017:             }
12018:             if ($env{'form.ltitools_add_sigmethod'} eq 'HMAC-SHA256') {
12019:                 $confhash{$newid}{'sigmethod'} = $env{'form.ltitools_add_sigmethod'};
12020:             } else {
12021:                 $confhash{$newid}{'sigmethod'} = 'HMAC-SHA1';
12022:             }
12023:             foreach my $item ('width','height','linktext','explanation') {
12024:                 $env{'form.ltitools_add_'.$item} =~ s/^\s+//;
12025:                 $env{'form.ltitools_add_'.$item} =~ s/\s+$//;
12026:                 if (($item eq 'width') || ($item eq 'height')) {
12027:                     if ($env{'form.ltitools_add_'.$item} =~ /^\d+$/) {
12028:                         $confhash{$newid}{'display'}{$item} = $env{'form.ltitools_add_'.$item};
12029:                     }
12030:                 } else {
12031:                     if ($env{'form.ltitools_add_'.$item} ne '') {
12032:                         $confhash{$newid}{'display'}{$item} = $env{'form.ltitools_add_'.$item};
12033:                     }
12034:                 }
12035:             }
12036:             if ($env{'form.ltitools_add_target'} eq 'window') {
12037:                 $confhash{$newid}{'display'}{'target'} = $env{'form.ltitools_add_target'};
12038:             } elsif ($env{'form.ltitools_add_target'} eq 'tab') {
12039:                 $confhash{$newid}{'display'}{'target'} = $env{'form.ltitools_add_target'};
12040:             } else {
12041:                 $confhash{$newid}{'display'}{'target'} = 'iframe';
12042:             }
12043:             if ($env{'form.ltitools_add_image.filename'} ne '') {
12044:                 my ($imageurl,$error) =
12045:                     &process_ltitools_image($r,$dom,$confname,'ltitools_add_image',$newid,
12046:                                             $configuserok,$switchserver,$author_ok);
12047:                 if ($imageurl) {
12048:                     $confhash{$newid}{'image'} = $imageurl;
12049:                 }
12050:                 if ($error) {
12051:                     &Apache::lonnet::logthis($error);
12052:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12053:                 }
12054:             }
12055:             my @fields = &Apache::loncommon::get_env_multiple('form.ltitools_add_fields');
12056:             foreach my $field (@fields) {
12057:                 if ($possfield{$field}) {
12058:                     if ($field eq 'roles') {
12059:                         foreach my $role (@courseroles) {
12060:                             my $choice = $env{'form.ltitools_add_roles_'.$role};
12061:                             if (($choice ne '') && ($posslti{$choice})) {
12062:                                 $confhash{$newid}{'roles'}{$role} = $choice;
12063:                                 if ($role eq 'cc') {
12064:                                     $confhash{$newid}{'roles'}{'co'} = $choice;
12065:                                 }
12066:                             }
12067:                         }
12068:                     } else {
12069:                         $confhash{$newid}{'fields'}{$field} = 1;
12070:                     }
12071:                 }
12072:             }
12073:             if (ref($confhash{$newid}{'fields'}) eq 'HASH') {
12074:                 if ($confhash{$newid}{'fields'}{'user'}) {
12075:                     if ($env{'form.ltitools_userincdom_add'}) {
12076:                         $confhash{$newid}{'incdom'} = 1;
12077:                     }
12078:                 }
12079:             }
12080:             my @courseconfig = &Apache::loncommon::get_env_multiple('form.ltitools_courseconfig');
12081:             foreach my $item (@courseconfig) {
12082:                 $confhash{$newid}{'crsconf'}{$item} = 1;
12083:             }
12084:             if ($env{'form.ltitools_add_custom'}) {
12085:                 my $name = $env{'form.ltitools_add_custom_name'};
12086:                 my $value = $env{'form.ltitools_add_custom_value'};
12087:                 $value =~ s/(`)/'/g;
12088:                 $name =~ s/(`)/'/g;
12089:                 $confhash{$newid}{'custom'}{$name} = $value;
12090:             }
12091:         } else {
12092:             my $error = &mt('Failed to acquire unique ID for new external tool');
12093:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12094:         }
12095:     }
12096:     if (ref($domconfig{$action}) eq 'HASH') {
12097:         my %deletions;
12098:         my @todelete = &Apache::loncommon::get_env_multiple('form.ltitools_del');
12099:         if (@todelete) {
12100:             map { $deletions{$_} = 1; } @todelete;
12101:         }
12102:         my %customadds;
12103:         my @newcustom = &Apache::loncommon::get_env_multiple('form.ltitools_customadd');
12104:         if (@newcustom) {
12105:             map { $customadds{$_} = 1; } @newcustom;
12106:         }
12107:         my %imgdeletions;
12108:         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.ltitools_image_del');
12109:         if (@todeleteimages) {
12110:             map { $imgdeletions{$_} = 1; } @todeleteimages;
12111:         }
12112:         my $maxnum = $env{'form.ltitools_maxnum'};
12113:         for (my $i=0; $i<=$maxnum; $i++) {
12114:             my $itemid = $env{'form.ltitools_id_'.$i};
12115:             $itemid =~ s/\D+//g;
12116:             if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
12117:                 if ($deletions{$itemid}) {
12118:                     if ($domconfig{$action}{$itemid}{'image'}) {
12119:                         #FIXME need to obsolete item in RES space
12120:                     }
12121:                     $changes{$itemid} = $domconfig{$action}{$itemid}{'title'};
12122:                     next;
12123:                 } else {
12124:                     my $newpos = $env{'form.ltitools_'.$itemid};
12125:                     $newpos =~ s/\D+//g;
12126:                     foreach my $item ('title','url','lifetime') {
12127:                         $confhash{$itemid}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
12128:                         if ($domconfig{$action}{$itemid}{$item} ne $confhash{$itemid}{$item}) {
12129:                             $changes{$itemid} = 1;
12130:                         }
12131:                     }
12132:                     foreach my $item ('key','secret') {
12133:                         $encconfig{$itemid}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
12134:                         if ($domconfig{$action}{$itemid}{$item} ne $encconfig{$itemid}{$item}) {
12135:                             $changes{$itemid} = 1;
12136:                         }
12137:                     }
12138:                     if ($env{'form.ltitools_version_'.$i} eq 'LTI-1p0') {
12139:                         $confhash{$itemid}{'version'} = $env{'form.ltitools_version_'.$i};
12140:                     }
12141:                     if ($env{'form.ltitools_msgtype_'.$i} eq 'basic-lti-launch-request') {
12142:                         $confhash{$itemid}{'msgtype'} = $env{'form.ltitools_msgtype_'.$i};
12143:                     }
12144:                     if ($env{'form.ltitools_sigmethod_'.$i} eq 'HMAC-SHA256') {
12145:                         $confhash{$itemid}{'sigmethod'} = $env{'form.ltitools_sigmethod_'.$i};
12146:                     } else {
12147:                         $confhash{$itemid}{'sigmethod'} = 'HMAC-SHA1';
12148:                     }
12149:                     if ($domconfig{$action}{$itemid}{'sigmethod'} eq '') {
12150:                         if ($confhash{$itemid}{'sigmethod'} ne 'HMAC-SHA1') {
12151:                             $changes{$itemid} = 1;
12152:                         }
12153:                     } elsif ($domconfig{$action}{$itemid}{'sigmethod'} ne $confhash{$itemid}{'sigmethod'}) {
12154:                         $changes{$itemid} = 1;
12155:                     }
12156:                     foreach my $size ('width','height') {
12157:                         $env{'form.ltitools_'.$size.'_'.$i} =~ s/^\s+//;
12158:                         $env{'form.ltitools_'.$size.'_'.$i} =~ s/\s+$//;
12159:                         if ($env{'form.ltitools_'.$size.'_'.$i} =~ /^\d+$/) {
12160:                             $confhash{$itemid}{'display'}{$size} = $env{'form.ltitools_'.$size.'_'.$i};
12161:                             if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
12162:                                 if ($domconfig{$action}{$itemid}{'display'}{$size} ne $confhash{$itemid}{'display'}{$size}) {
12163:                                     $changes{$itemid} = 1;
12164:                                 }
12165:                             } else {
12166:                                 $changes{$itemid} = 1;
12167:                             }
12168:                         } elsif (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
12169:                             if ($domconfig{$action}{$itemid}{'display'}{$size} ne '') {
12170:                                 $changes{$itemid} = 1;
12171:                             }
12172:                         }
12173:                     }
12174:                     foreach my $item ('linktext','explanation') {
12175:                         $env{'form.ltitools_'.$item.'_'.$i} =~ s/^\s+//;
12176:                         $env{'form.ltitools_'.$item.'_'.$i} =~ s/\s+$//;
12177:                         if ($env{'form.ltitools_'.$item.'_'.$i} ne '') {
12178:                             $confhash{$itemid}{'display'}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
12179:                             if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
12180:                                 if ($domconfig{$action}{$itemid}{'display'}{$item} ne $confhash{$itemid}{'display'}{$item}) {
12181:                                     $changes{$itemid} = 1;
12182:                                 }
12183:                             } else {
12184:                                 $changes{$itemid} = 1;
12185:                             }
12186:                         } elsif (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
12187:                             if ($domconfig{$action}{$itemid}{'display'}{$item} ne '') {
12188:                                 $changes{$itemid} = 1;
12189:                             }
12190:                         }
12191:                     }
12192:                     if ($env{'form.ltitools_target_'.$i} eq 'window') {
12193:                         $confhash{$itemid}{'display'}{'target'} = $env{'form.ltitools_target_'.$i};
12194:                     } elsif ($env{'form.ltitools_target_'.$i} eq 'tab') {
12195:                         $confhash{$itemid}{'display'}{'target'} = $env{'form.ltitools_target_'.$i};
12196:                     } else {
12197:                         $confhash{$itemid}{'display'}{'target'} = 'iframe';
12198:                     }
12199:                     if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
12200:                         if ($domconfig{$action}{$itemid}{'display'}{'target'} ne $confhash{$itemid}{'display'}{'target'}) {
12201:                             $changes{$itemid} = 1;
12202:                         }
12203:                     } else {
12204:                         $changes{$itemid} = 1;
12205:                     }
12206:                     my @courseconfig = &Apache::loncommon::get_env_multiple('form.ltitools_courseconfig_'.$i);
12207:                     foreach my $item ('label','title','target','linktext','explanation','append') {
12208:                         if (grep(/^\Q$item\E$/,@courseconfig)) {
12209:                             $confhash{$itemid}{'crsconf'}{$item} = 1;
12210:                             if (ref($domconfig{$action}{$itemid}{'crsconf'}) eq 'HASH') {
12211:                                 if ($domconfig{$action}{$itemid}{'crsconf'}{$item} ne $confhash{$itemid}{'crsconf'}{$item}) {
12212:                                     $changes{$itemid} = 1;
12213:                                 }
12214:                             } else {
12215:                                 $changes{$itemid} = 1;
12216:                             }
12217:                         }
12218:                     }
12219:                     my @fields = &Apache::loncommon::get_env_multiple('form.ltitools_fields_'.$i);
12220:                     foreach my $field (@fields) {
12221:                         if ($possfield{$field}) {
12222:                             if ($field eq 'roles') {
12223:                                 foreach my $role (@courseroles) {
12224:                                     my $choice = $env{'form.ltitools_roles_'.$role.'_'.$i};
12225:                                     if (($choice ne '') && ($posslti{$choice})) {
12226:                                         $confhash{$itemid}{'roles'}{$role} = $choice;
12227:                                         if ($role eq 'cc') {
12228:                                             $confhash{$itemid}{'roles'}{'co'} = $choice;
12229:                                         }
12230:                                     }
12231:                                     if (ref($domconfig{$action}{$itemid}{'roles'}) eq 'HASH') {
12232:                                         if ($domconfig{$action}{$itemid}{'roles'}{$role} ne $confhash{$itemid}{'roles'}{$role}) {
12233:                                             $changes{$itemid} = 1;
12234:                                         }
12235:                                     } elsif ($confhash{$itemid}{'roles'}{$role}) {
12236:                                         $changes{$itemid} = 1;
12237:                                     }
12238:                                 }
12239:                             } else {
12240:                                 $confhash{$itemid}{'fields'}{$field} = 1;
12241:                                 if (ref($domconfig{$action}{$itemid}{'fields'}) eq 'HASH') {
12242:                                     if ($domconfig{$action}{$itemid}{'fields'}{$field} ne $confhash{$itemid}{'fields'}{$field}) {
12243:                                         $changes{$itemid} = 1;
12244:                                     }
12245:                                 } else {
12246:                                     $changes{$itemid} = 1;
12247:                                 }
12248:                             }
12249:                         }
12250:                     }
12251:                     if (ref($confhash{$itemid}{'fields'}) eq 'HASH') {
12252:                         if ($confhash{$itemid}{'fields'}{'user'}) {
12253:                             if ($env{'form.ltitools_userincdom_'.$i}) {
12254:                                 $confhash{$itemid}{'incdom'} = 1;
12255:                             }
12256:                             if ($domconfig{$action}{$itemid}{'incdom'} ne $confhash{$itemid}{'incdom'}) {
12257:                                 $changes{$itemid} = 1;
12258:                             }
12259:                         }
12260:                     }
12261:                     $allpos[$newpos] = $itemid;
12262:                 }
12263:                 if ($imgdeletions{$itemid}) {
12264:                     $changes{$itemid} = 1;
12265:                     #FIXME need to obsolete item in RES space
12266:                 } elsif ($env{'form.ltitools_image_'.$i.'.filename'}) {
12267:                     my ($imgurl,$error) = &process_ltitools_image($r,$dom,$confname,'ltitools_image_'.$i,
12268:                                                                  $itemid,$configuserok,$switchserver,
12269:                                                                  $author_ok);
12270:                     if ($imgurl) {
12271:                         $confhash{$itemid}{'image'} = $imgurl;
12272:                         $changes{$itemid} = 1;
12273:                     }
12274:                     if ($error) {
12275:                         &Apache::lonnet::logthis($error);
12276:                         $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12277:                     }
12278:                 } elsif ($domconfig{$action}{$itemid}{'image'}) {
12279:                     $confhash{$itemid}{'image'} =
12280:                        $domconfig{$action}{$itemid}{'image'};
12281:                 }
12282:                 if ($customadds{$i}) {
12283:                     my $name = $env{'form.ltitools_custom_name_'.$i};
12284:                     $name =~ s/(`)/'/g;
12285:                     $name =~ s/^\s+//;
12286:                     $name =~ s/\s+$//;
12287:                     my $value = $env{'form.ltitools_custom_value_'.$i};
12288:                     $value =~ s/(`)/'/g;
12289:                     $value =~ s/^\s+//;
12290:                     $value =~ s/\s+$//;
12291:                     if ($name ne '') {
12292:                         $confhash{$itemid}{'custom'}{$name} = $value;
12293:                         $changes{$itemid} = 1;
12294:                     }
12295:                 }
12296:                 my %customdels;
12297:                 my @customdeletions = &Apache::loncommon::get_env_multiple('form.ltitools_customdel_'.$i);
12298:                 if (@customdeletions) {
12299:                     $changes{$itemid} = 1;
12300:                 }
12301:                 map { $customdels{$_} = 1; } @customdeletions;
12302:                 if (ref($domconfig{$action}{$itemid}{'custom'}) eq 'HASH') {
12303:                     foreach my $key (keys(%{$domconfig{$action}{$itemid}{'custom'}})) {
12304:                         unless ($customdels{$key}) {
12305:                             if ($env{'form.ltitools_customval_'.$key.'_'.$i} ne '') {
12306:                                 $confhash{$itemid}{'custom'}{$key} = $env{'form.ltitools_customval_'.$key.'_'.$i};
12307:                             }
12308:                             if ($domconfig{$action}{$itemid}{'custom'}{$key} ne $env{'form.ltitools_customval_'.$key.'_'.$i}) {
12309:                                 $changes{$itemid} = 1;
12310:                             }
12311:                         }
12312:                     }
12313:                 }
12314:                 unless ($changes{$itemid}) {
12315:                     foreach my $key (keys(%{$domconfig{$action}{$itemid}})) {
12316:                         if (ref($domconfig{$action}{$itemid}{$key}) eq 'HASH') {
12317:                             if (ref($confhash{$itemid}{$key}) eq 'HASH') {
12318:                                 foreach my $innerkey (keys(%{$domconfig{$action}{$itemid}{$key}})) {
12319:                                     unless (exists($confhash{$itemid}{$key}{$innerkey})) {
12320:                                         $changes{$itemid} = 1;
12321:                                         last;
12322:                                     }
12323:                                 }
12324:                             } elsif (keys(%{$domconfig{$action}{$itemid}{$key}}) > 0) {
12325:                                 $changes{$itemid} = 1;
12326:                             }
12327:                         }
12328:                         last if ($changes{$itemid});
12329:                     }
12330:                 }
12331:             }
12332:         }
12333:     }
12334:     if (@allpos > 0) {
12335:         my $idx = 0;
12336:         foreach my $itemid (@allpos) {
12337:             if ($itemid ne '') {
12338:                 $confhash{$itemid}{'order'} = $idx;
12339:                 if (ref($domconfig{$action}) eq 'HASH') {
12340:                     if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
12341:                         if ($domconfig{$action}{$itemid}{'order'} ne $idx) {
12342:                             $changes{$itemid} = 1;
12343:                         }
12344:                     }
12345:                 }
12346:                 $idx ++;
12347:             }
12348:         }
12349:     }
12350:     my %ltitoolshash = (
12351:                           $action => { %confhash }
12352:                        );
12353:     my $putresult = &Apache::lonnet::put_dom('configuration',\%ltitoolshash,
12354:                                              $dom);
12355:     if ($putresult eq 'ok') {
12356:         my %ltienchash = (
12357:                              $action => { %encconfig }
12358:                          );
12359:         &Apache::lonnet::put_dom('encconfig',\%ltienchash,$dom,undef,1);
12360:         if (keys(%changes) > 0) {
12361:             my $cachetime = 24*60*60;
12362:             my %ltiall = %confhash;
12363:             foreach my $id (keys(%ltiall)) {
12364:                 if (ref($encconfig{$id}) eq 'HASH') {
12365:                     foreach my $item ('key','secret') {
12366:                         $ltiall{$id}{$item} = $encconfig{$id}{$item};
12367:                     }
12368:                 }
12369:             }
12370:             &Apache::lonnet::do_cache_new('ltitools',$dom,\%ltiall,$cachetime);
12371:             if (ref($lastactref) eq 'HASH') {
12372:                 $lastactref->{'ltitools'} = 1;
12373:             }
12374:             $resulttext = &mt('Changes made:').'<ul>';
12375:             my %bynum;
12376:             foreach my $itemid (sort(keys(%changes))) {
12377:                 my $position = $confhash{$itemid}{'order'};
12378:                 $bynum{$position} = $itemid;
12379:             }
12380:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
12381:                 my $itemid = $bynum{$pos};
12382:                 if (ref($confhash{$itemid}) ne 'HASH') {
12383:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
12384:                 } else {
12385:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'title'}.'</b>';
12386:                     if ($confhash{$itemid}{'image'}) {
12387:                         $resulttext .= '&nbsp;'.
12388:                                        '<img src="'.$confhash{$itemid}{'image'}.'"'.
12389:                                        ' alt="'.&mt('Tool Provider icon').'" />';
12390:                     }
12391:                     $resulttext .= '</li><ul>';
12392:                     my $position = $pos + 1;
12393:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
12394:                     foreach my $item ('version','msgtype','sigmethod','url','lifetime') {
12395:                         if ($confhash{$itemid}{$item} ne '') {
12396:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{$item}.'</li>';
12397:                         }
12398:                     }
12399:                     if ($encconfig{$itemid}{'key'} ne '') {
12400:                         $resulttext .= '<li>'.$lt{'key'}.':&nbsp;'.$encconfig{$itemid}{'key'}.'</li>';
12401:                     }
12402:                     if ($encconfig{$itemid}{'secret'} ne '') {
12403:                         $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;';
12404:                         my $num = length($encconfig{$itemid}{'secret'});
12405:                         $resulttext .= ('*'x$num).'</li>';
12406:                     }
12407:                     $resulttext .= '<li>'.&mt('Configurable in course:');
12408:                     my @possconfig = ('label','title','target','linktext','explanation','append');
12409:                     my $numconfig = 0;
12410:                     if (ref($confhash{$itemid}{'crsconf'}) eq 'HASH') {
12411:                         foreach my $item (@possconfig) {
12412:                             if ($confhash{$itemid}{'crsconf'}{$item}) {
12413:                                 $numconfig ++;
12414:                                 $resulttext .= ' "'.$lt{'crs'.$item}.'"';
12415:                             }
12416:                         }
12417:                     }
12418:                     if (!$numconfig) {
12419:                         $resulttext .= &mt('None');
12420:                     }
12421:                     $resulttext .= '</li>';
12422:                     if (ref($confhash{$itemid}{'display'}) eq 'HASH') {
12423:                         my $displaylist;
12424:                         if ($confhash{$itemid}{'display'}{'target'}) {
12425:                             $displaylist = &mt('Display target').':&nbsp;'.
12426:                                            $confhash{$itemid}{'display'}{'target'}.',';
12427:                         }
12428:                         foreach my $size ('width','height') {
12429:                             if ($confhash{$itemid}{'display'}{$size}) {
12430:                                 $displaylist .= ('&nbsp;'x2).$lt{$size}.':&nbsp;'.
12431:                                                 $confhash{$itemid}{'display'}{$size}.',';
12432:                             }
12433:                         }
12434:                         if ($displaylist) {
12435:                             $displaylist =~ s/,$//;
12436:                             $resulttext .= '<li>'.$displaylist.'</li>';
12437:                         }
12438:                         foreach my $item ('linktext','explanation') {
12439:                             if ($confhash{$itemid}{'display'}{$item}) {
12440:                                 $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{'display'}{$item}.'</li>';
12441:                             }
12442:                         }
12443:                     }
12444:                     if (ref($confhash{$itemid}{'fields'}) eq 'HASH') {
12445:                         my $fieldlist;
12446:                         foreach my $field (@allfields) {
12447:                             if ($confhash{$itemid}{'fields'}{$field}) {
12448:                                 $fieldlist .= ('&nbsp;'x2).$lt{$field}.',';
12449:                             }
12450:                         }
12451:                         if ($fieldlist) {
12452:                             $fieldlist =~ s/,$//;
12453:                             if ($confhash{$itemid}{'fields'}{'user'}) {
12454:                                 if ($confhash{$itemid}{'incdom'}) {
12455:                                     $fieldlist .= ' ('.&mt('username:domain').')';
12456:                                 } else {
12457:                                     $fieldlist .= ' ('.&mt('username').')';
12458:                                 }
12459:                             }
12460:                             $resulttext .= '<li>'.&mt('Data sent').':'.$fieldlist.'</li>';
12461:                         }
12462:                     }
12463:                     if (ref($confhash{$itemid}{'roles'}) eq 'HASH') {
12464:                         my $rolemaps;
12465:                         foreach my $role (@courseroles) {
12466:                             if ($confhash{$itemid}{'roles'}{$role}) {
12467:                                 $rolemaps .= ('&nbsp;'x2).&Apache::lonnet::plaintext($role,'Course').'='.
12468:                                              $confhash{$itemid}{'roles'}{$role}.',';
12469:                             }
12470:                         }
12471:                         if ($rolemaps) {
12472:                             $rolemaps =~ s/,$//;
12473:                             $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
12474:                         }
12475:                     }
12476:                     if (ref($confhash{$itemid}{'custom'}) eq 'HASH') {
12477:                         my $customlist;
12478:                         if (keys(%{$confhash{$itemid}{'custom'}})) {
12479:                             foreach my $key (sort(keys(%{$confhash{$itemid}{'custom'}}))) {
12480:                                 $customlist .= $key.':'.$confhash{$itemid}{'custom'}{$key}.('&nbsp;'x2);
12481:                             }
12482:                         }
12483:                         if ($customlist) {
12484:                             $resulttext .= '<li>'.&mt('Custom items').': '.$customlist.'</li>';
12485:                         }
12486:                     }
12487:                     $resulttext .= '</ul></li>';
12488:                 }
12489:             }
12490:             $resulttext .= '</ul>';
12491:         } else {
12492:             $resulttext = &mt('No changes made.');
12493:         }
12494:     } else {
12495:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
12496:     }
12497:     if ($errors) {
12498:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
12499:                        $errors.'</ul>';
12500:     }
12501:     return $resulttext;
12502: }
12503: 
12504: sub process_ltitools_image {
12505:     my ($r,$dom,$confname,$caller,$itemid,$configuserok,$switchserver,$author_ok) = @_;
12506:     my $filename = $env{'form.'.$caller.'.filename'};
12507:     my ($error,$url);
12508:     my ($width,$height) = (21,21);
12509:     if ($configuserok eq 'ok') {
12510:         if ($switchserver) {
12511:             $error = &mt('Upload of Tool Provider (LTI) icon is not permitted to this server: [_1]',
12512:                          $switchserver);
12513:         } elsif ($author_ok eq 'ok') {
12514:             my ($result,$imageurl,$madethumb) =
12515:                 &publishlogo($r,'upload',$caller,$dom,$confname,
12516:                              "ltitools/$itemid/icon",$width,$height);
12517:             if ($result eq 'ok') {
12518:                 if ($madethumb) {
12519:                     my ($path,$imagefile) = ($imageurl =~ m{^(.+)/([^/]+)$});
12520:                     my $imagethumb = "$path/tn-".$imagefile;
12521:                     $url = $imagethumb;
12522:                 } else {
12523:                     $url = $imageurl;
12524:                 }
12525:             } else {
12526:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
12527:             }
12528:         } else {
12529:             $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);
12530:         }
12531:     } else {
12532:         $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);
12533:     }
12534:     return ($url,$error);
12535: }
12536: 
12537: sub get_ltitools_id {
12538:     my ($cdom,$title) = @_;
12539:     # get lock on ltitools db
12540:     my $lockhash = {
12541:                       lock => $env{'user.name'}.
12542:                               ':'.$env{'user.domain'},
12543:                    };
12544:     my $tries = 0;
12545:     my $gotlock = &Apache::lonnet::newput_dom('ltitools',$lockhash,$cdom);
12546:     my ($id,$error);
12547: 
12548:     while (($gotlock ne 'ok') && ($tries<10)) {
12549:         $tries ++;
12550:         sleep (0.1);
12551:         $gotlock = &Apache::lonnet::newput_dom('ltitools',$lockhash,$cdom);
12552:     }
12553:     if ($gotlock eq 'ok') {
12554:         my %currids = &Apache::lonnet::dump_dom('ltitools',$cdom);
12555:         if ($currids{'lock'}) {
12556:             delete($currids{'lock'});
12557:             if (keys(%currids)) {
12558:                 my @curr = sort { $a <=> $b } keys(%currids);
12559:                 if ($curr[-1] =~ /^\d+$/) {
12560:                     $id = 1 + $curr[-1];
12561:                 }
12562:             } else {
12563:                 $id = 1;
12564:             }
12565:             if ($id) {
12566:                 unless (&Apache::lonnet::newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
12567:                     $error = 'nostore';
12568:                 }
12569:             } else {
12570:                 $error = 'nonumber';
12571:             }
12572:         }
12573:         my $dellockoutcome = &Apache::lonnet::del_dom('ltitools',['lock'],$cdom);
12574:     } else {
12575:         $error = 'nolock';
12576:     }
12577:     return ($id,$error);
12578: }
12579: 
12580: sub modify_autoenroll {
12581:     my ($dom,$lastactref,%domconfig) = @_;
12582:     my ($resulttext,%changes);
12583:     my %currautoenroll;
12584:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
12585:         foreach my $key (keys(%{$domconfig{'autoenroll'}})) {
12586:             $currautoenroll{$key} = $domconfig{'autoenroll'}{$key};
12587:         }
12588:     }
12589:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
12590:     my %title = ( run => 'Auto-enrollment active',
12591:                   sender => 'Sender for notification messages',
12592:                   coowners => 'Automatic assignment of co-ownership to instructors of record (institutional data)',
12593:                   autofailsafe => 'Failsafe for no drops if institutional data missing for a section');
12594:     my @offon = ('off','on');
12595:     my $sender_uname = $env{'form.sender_uname'};
12596:     my $sender_domain = $env{'form.sender_domain'};
12597:     if ($sender_domain eq '') {
12598:         $sender_uname = '';
12599:     } elsif ($sender_uname eq '') {
12600:         $sender_domain = '';
12601:     }
12602:     my $coowners = $env{'form.autoassign_coowners'};
12603:     my $autofailsafe = $env{'form.autoenroll_autofailsafe'};
12604:     $autofailsafe =~ s{^\s+|\s+$}{}g;
12605:     if ($autofailsafe =~ /\D/) {
12606:         undef($autofailsafe);
12607:     }
12608:     my $failsafe = $env{'form.autoenroll_failsafe'};
12609:     unless (($failsafe eq 'zero') || ($failsafe eq 'any')) {
12610:         $failsafe = 'off';
12611:         undef($autofailsafe);
12612:     }
12613:     my %autoenrollhash =  (
12614:                        autoenroll => { 'run' => $env{'form.autoenroll_run'},
12615:                                        'sender_uname' => $sender_uname,
12616:                                        'sender_domain' => $sender_domain,
12617:                                        'co-owners' => $coowners,
12618:                                        'autofailsafe' => $autofailsafe,
12619:                                        'failsafe' => $failsafe,
12620:                                 }
12621:                      );
12622:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autoenrollhash,
12623:                                              $dom);
12624:     if ($putresult eq 'ok') {
12625:         if (exists($currautoenroll{'run'})) {
12626:              if ($currautoenroll{'run'} ne $env{'form.autoenroll_run'}) {
12627:                  $changes{'run'} = 1;
12628:              }
12629:         } elsif ($autorun) {
12630:             if ($env{'form.autoenroll_run'} ne '1') {
12631:                  $changes{'run'} = 1;
12632:             }
12633:         }
12634:         if ($currautoenroll{'sender_uname'} ne $sender_uname) {
12635:             $changes{'sender'} = 1;
12636:         }
12637:         if ($currautoenroll{'sender_domain'} ne $sender_domain) {
12638:             $changes{'sender'} = 1;
12639:         }
12640:         if ($currautoenroll{'co-owners'} ne '') {
12641:             if ($currautoenroll{'co-owners'} ne $coowners) {
12642:                 $changes{'coowners'} = 1;
12643:             }
12644:         } elsif ($coowners) {
12645:             $changes{'coowners'} = 1;
12646:         }
12647:         if ($currautoenroll{'autofailsafe'} ne $autofailsafe) {
12648:             $changes{'autofailsafe'} = 1;
12649:         }
12650:         if ($currautoenroll{'failsafe'} ne $failsafe) {
12651:             $changes{'failsafe'} = 1;
12652:         }
12653:         if (keys(%changes) > 0) {
12654:             $resulttext = &mt('Changes made:').'<ul>';
12655:             if ($changes{'run'}) {
12656:                 $resulttext .= '<li>'.&mt("$title{'run'} set to $offon[$env{'form.autoenroll_run'}]").'</li>';
12657:             }
12658:             if ($changes{'sender'}) {
12659:                 if ($sender_uname eq '' || $sender_domain eq '') {
12660:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to default (course owner).").'</li>';
12661:                 } else {
12662:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to [_1]",$sender_uname.':'.$sender_domain).'</li>';
12663:                 }
12664:             }
12665:             if ($changes{'coowners'}) {
12666:                 $resulttext .= '<li>'.&mt("$title{'coowners'} set to $offon[$env{'form.autoassign_coowners'}]").'</li>';
12667:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
12668:                 if (ref($lastactref) eq 'HASH') {
12669:                     $lastactref->{'domainconfig'} = 1;
12670:                 }
12671:             }
12672:             if ($changes{'autofailsafe'}) {
12673:                 if ($autofailsafe ne '') {
12674:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section set to: [_1]',$autofailsafe).'</li>';
12675:                 } else {
12676:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section not in use').'</li>';
12677:                 }
12678:             }
12679:             if ($changes{'failsafe'}) {
12680:                 if ($failsafe eq 'off') {
12681:                     unless ($changes{'autofailsafe'}) {
12682:                         $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section not in use').'</li>';
12683:                     }
12684:                 } elsif ($failsafe eq 'zero') {
12685:                     $resulttext .= '<li>'.&mt('Failsafe applies if retrieved section enrollment is zero').'</li>';
12686:                 } else {
12687:                     $resulttext .= '<li>'.&mt('Failsafe applies if retrieved section enrollment is zero or greater').'</li>';
12688:                 }
12689:             }
12690:             if (($changes{'autofailsafe'}) || ($changes{'failsafe'})) {
12691:                 &Apache::lonnet::get_domain_defaults($dom,1);
12692:                 if (ref($lastactref) eq 'HASH') {
12693:                     $lastactref->{'domdefaults'} = 1;
12694:                 }
12695:             }
12696:             $resulttext .= '</ul>';
12697:         } else {
12698:             $resulttext = &mt('No changes made to auto-enrollment settings');
12699:         }
12700:     } else {
12701:         $resulttext = '<span class="LC_error">'.
12702: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
12703:     }
12704:     return $resulttext;
12705: }
12706: 
12707: sub modify_autoupdate {
12708:     my ($dom,%domconfig) = @_;
12709:     my ($resulttext,%currautoupdate,%fields,%changes);
12710:     if (ref($domconfig{'autoupdate'}) eq 'HASH') {
12711:         foreach my $key (keys(%{$domconfig{'autoupdate'}})) {
12712:             $currautoupdate{$key} = $domconfig{'autoupdate'}{$key};
12713:         }
12714:     }
12715:     my @offon = ('off','on');
12716:     my %title = &Apache::lonlocal::texthash (
12717:                     run        => 'Auto-update:',
12718:                     classlists => 'Updates to user information in classlists?',
12719:                     unexpired  => 'Skip updates for users without active or future roles?',
12720:                     lastactive => 'Skip updates for inactive users?',
12721:                 );
12722:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
12723:     my %fieldtitles = &Apache::lonlocal::texthash (
12724:                         id => 'Student/Employee ID',
12725:                         permanentemail => 'E-mail address',
12726:                         lastname => 'Last Name',
12727:                         firstname => 'First Name',
12728:                         middlename => 'Middle Name',
12729:                         generation => 'Generation',
12730:                       );
12731:     $othertitle = &mt('All users');
12732:     if (keys(%{$usertypes}) >  0) {
12733:         $othertitle = &mt('Other users');
12734:     }
12735:     foreach my $key (keys(%env)) {
12736:         if ($key =~ /^form\.updateable_(.+)_([^_]+)$/) {
12737:             my ($usertype,$item) = ($1,$2);
12738:             if (grep(/^\Q$item\E$/,keys(%fieldtitles))) {
12739:                 if ($usertype eq 'default') {   
12740:                     push(@{$fields{$1}},$2);
12741:                 } elsif (ref($types) eq 'ARRAY') {
12742:                     if (grep(/^\Q$usertype\E$/,@{$types})) {
12743:                         push(@{$fields{$1}},$2);
12744:                     }
12745:                 }
12746:             }
12747:         }
12748:     }
12749:     my @lockablenames = &Apache::loncommon::get_env_multiple('form.lockablenames');
12750:     @lockablenames = sort(@lockablenames);
12751:     if (ref($currautoupdate{'lockablenames'}) eq 'ARRAY') {
12752:         my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
12753:         if (@changed) {
12754:             $changes{'lockablenames'} = 1;
12755:         }
12756:     } else {
12757:         if (@lockablenames) {
12758:             $changes{'lockablenames'} = 1;
12759:         }
12760:     }
12761:     my %updatehash = (
12762:                       autoupdate => { run => $env{'form.autoupdate_run'},
12763:                                       classlists => $env{'form.classlists'},
12764:                                       unexpired  => $env{'form.unexpired'},
12765:                                       fields => {%fields},
12766:                                       lockablenames => \@lockablenames,
12767:                                     }
12768:                      );
12769:     my $lastactivedays;
12770:     if ($env{'form.lastactive'}) {
12771:         $lastactivedays = $env{'form.lastactivedays'};
12772:         $lastactivedays =~ s/^\s+|\s+$//g;
12773:         unless ($lastactivedays =~ /^\d+$/) {
12774:             undef($lastactivedays);
12775:             $env{'form.lastactive'} = 0;
12776:         }
12777:     }
12778:     $updatehash{'autoupdate'}{'lastactive'} = $lastactivedays;
12779:     foreach my $key (keys(%currautoupdate)) {
12780:         if (($key eq 'run') || ($key eq 'classlists') || ($key eq 'unexpired') || ($key eq 'lastactive')) {
12781:             if (exists($updatehash{autoupdate}{$key})) {
12782:                 if ($currautoupdate{$key} ne $updatehash{autoupdate}{$key}) {
12783:                     $changes{$key} = 1;
12784:                 }
12785:             }
12786:         } elsif ($key eq 'fields') {
12787:             if (ref($currautoupdate{$key}) eq 'HASH') {
12788:                 foreach my $item (@{$types},'default') {
12789:                     if (ref($currautoupdate{$key}{$item}) eq 'ARRAY') {
12790:                         my $change = 0;
12791:                         foreach my $type (@{$currautoupdate{$key}{$item}}) {
12792:                             if (!exists($fields{$item})) {
12793:                                 $change = 1;
12794:                                 last;
12795:                             } elsif (ref($fields{$item}) eq 'ARRAY') {
12796:                                 if (!grep(/^\Q$type\E$/,@{$fields{$item}})) {
12797:                                     $change = 1;
12798:                                     last;
12799:                                 }
12800:                             }
12801:                         }
12802:                         if ($change) {
12803:                             push(@{$changes{$key}},$item);
12804:                         }
12805:                     } 
12806:                 }
12807:             }
12808:         } elsif ($key eq 'lockablenames') {
12809:             if (ref($currautoupdate{$key}) eq 'ARRAY') {
12810:                 my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
12811:                 if (@changed) {
12812:                     $changes{'lockablenames'} = 1;
12813:                 }
12814:             } else {
12815:                 if (@lockablenames) {
12816:                     $changes{'lockablenames'} = 1;
12817:                 }
12818:             }
12819:         }
12820:     }
12821:     unless (grep(/^\Qlockablenames\E$/,keys(%currautoupdate))) {
12822:         if (@lockablenames) {
12823:             $changes{'lockablenames'} = 1;
12824:         }
12825:     }
12826:     unless (grep(/^unexpired$/,keys(%currautoupdate))) {
12827:         if ($updatehash{'autoupdate'}{'unexpired'}) {
12828:             $changes{'unexpired'} = 1;
12829:         }
12830:     }
12831:     unless (grep(/^lastactive$/,keys(%currautoupdate))) {
12832:         if ($updatehash{'autoupdate'}{'lastactive'} ne '') {
12833:             $changes{'lastactive'} = 1;
12834:         }
12835:     }
12836:     foreach my $item (@{$types},'default') {
12837:         if (defined($fields{$item})) {
12838:             if (ref($currautoupdate{'fields'}) eq 'HASH') {
12839:                 if (ref($currautoupdate{'fields'}{$item}) eq 'ARRAY') {
12840:                     my $change = 0;
12841:                     if (ref($fields{$item}) eq 'ARRAY') {
12842:                         foreach my $type (@{$fields{$item}}) {
12843:                             if (!grep(/^\Q$type\E$/,@{$currautoupdate{'fields'}{$item}})) {
12844:                                 $change = 1;
12845:                                 last;
12846:                             }
12847:                         }
12848:                     }
12849:                     if ($change) {
12850:                         push(@{$changes{'fields'}},$item);
12851:                     }
12852:                 } else {
12853:                     push(@{$changes{'fields'}},$item);
12854:                 }
12855:             } else {
12856:                 push(@{$changes{'fields'}},$item);
12857:             }
12858:         }
12859:     }
12860:     my $putresult = &Apache::lonnet::put_dom('configuration',\%updatehash,
12861:                                              $dom);
12862:     if ($putresult eq 'ok') {
12863:         if (keys(%changes) > 0) {
12864:             $resulttext = &mt('Changes made:').'<ul>';
12865:             foreach my $key (sort(keys(%changes))) {
12866:                 if ($key eq 'lockablenames') {
12867:                     $resulttext .= '<li>';
12868:                     if (@lockablenames) {
12869:                         $usertypes->{'default'} = $othertitle;
12870:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update), available for the following affiliations:").' '.
12871:                                    join(', ', map { $usertypes->{$_}; } @lockablenames).'</li>';
12872:                     } else {
12873:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update) is unavailable.");
12874:                     }
12875:                     $resulttext .= '</li>';
12876:                 } elsif (ref($changes{$key}) eq 'ARRAY') {
12877:                     foreach my $item (@{$changes{$key}}) {
12878:                         my @newvalues;
12879:                         foreach my $type (@{$fields{$item}}) {
12880:                             push(@newvalues,$fieldtitles{$type});
12881:                         }
12882:                         my $newvaluestr;
12883:                         if (@newvalues > 0) {
12884:                             $newvaluestr = join(', ',@newvalues);
12885:                         } else {
12886:                             $newvaluestr = &mt('none');
12887:                         }
12888:                         if ($item eq 'default') {
12889:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$othertitle,$newvaluestr).'</li>';
12890:                         } else {
12891:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$usertypes->{$item},$newvaluestr).'</li>';
12892:                         }
12893:                     }
12894:                 } else {
12895:                     my $newvalue;
12896:                     if ($key eq 'run') {
12897:                         $newvalue = $offon[$env{'form.autoupdate_run'}];
12898:                     } elsif ($key eq 'lastactive') {
12899:                         $newvalue = $offon[$env{'form.lastactive'}];
12900:                         unless ($lastactivedays eq '') {
12901:                             $newvalue .= '; '.&mt('inactive = no activity in last [quant,_1,day]',$lastactivedays);
12902:                         }
12903:                     } else {
12904:                         $newvalue = $offon[$env{'form.'.$key}];
12905:                     }
12906:                     $resulttext .= '<li>'.&mt("[_1] set to $newvalue",$title{$key}).'</li>';
12907:                 }
12908:             }
12909:             $resulttext .= '</ul>';
12910:         } else {
12911:             $resulttext = &mt('No changes made to autoupdates');
12912:         }
12913:     } else {
12914:         $resulttext = '<span class="LC_error">'.
12915: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
12916:     }
12917:     return $resulttext;
12918: }
12919: 
12920: sub modify_autocreate {
12921:     my ($dom,%domconfig) = @_;
12922:     my ($resulttext,%changes,%currautocreate,%newvals,%autocreatehash);
12923:     if (ref($domconfig{'autocreate'}) eq 'HASH') {
12924:         foreach my $key (keys(%{$domconfig{'autocreate'}})) {
12925:             $currautocreate{$key} = $domconfig{'autocreate'}{$key};
12926:         }
12927:     }
12928:     my %title= ( xml => 'Auto-creation of courses in XML course description files',
12929:                  req => 'Auto-creation of validated requests for official courses',
12930:                  xmldc => 'Identity of course creator of courses from XML files',
12931:                );
12932:     my @types = ('xml','req');
12933:     foreach my $item (@types) {
12934:         $newvals{$item} = $env{'form.autocreate_'.$item};
12935:         $newvals{$item} =~ s/\D//g;
12936:         $newvals{$item} = 0 if ($newvals{$item} eq '');
12937:     }
12938:     $newvals{'xmldc'} = $env{'form.autocreate_xmldc'};
12939:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
12940:     unless (exists($domcoords{$newvals{'xmldc'}})) {
12941:         $newvals{'xmldc'} = '';
12942:     } 
12943:     %autocreatehash =  (
12944:                         autocreate => { xml => $newvals{'xml'},
12945:                                         req => $newvals{'req'},
12946:                                       }
12947:                        );
12948:     if ($newvals{'xmldc'} ne '') {
12949:         $autocreatehash{'autocreate'}{'xmldc'} = $newvals{'xmldc'};
12950:     }
12951:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autocreatehash,
12952:                                              $dom);
12953:     if ($putresult eq 'ok') {
12954:         my @items = @types;
12955:         if ($newvals{'xml'}) {
12956:             push(@items,'xmldc');
12957:         }
12958:         foreach my $item (@items) {
12959:             if (exists($currautocreate{$item})) {
12960:                 if ($currautocreate{$item} ne $newvals{$item}) {
12961:                     $changes{$item} = 1;
12962:                 }
12963:             } elsif ($newvals{$item}) {
12964:                 $changes{$item} = 1;
12965:             }
12966:         }
12967:         if (keys(%changes) > 0) {
12968:             my @offon = ('off','on'); 
12969:             $resulttext = &mt('Changes made:').'<ul>';
12970:             foreach my $item (@types) {
12971:                 if ($changes{$item}) {
12972:                     my $newtxt = $offon[$newvals{$item}];
12973:                     $resulttext .= '<li>'.
12974:                                    &mt("$title{$item} set to [_1]$newtxt [_2]",
12975:                                        '<b>','</b>').
12976:                                    '</li>';
12977:                 }
12978:             }
12979:             if ($changes{'xmldc'}) {
12980:                 my ($dcname,$dcdom) = split(':',$newvals{'xmldc'});
12981:                 my $newtxt = &Apache::loncommon::plainname($dcname,$dcdom);
12982:                 $resulttext .= '<li>'.&mt("$title{'xmldc'} set to [_1]",'<b>'.$newtxt.'</b>').'</li>'; 
12983:             }
12984:             $resulttext .= '</ul>';
12985:         } else {
12986:             $resulttext = &mt('No changes made to auto-creation settings');
12987:         }
12988:     } else {
12989:         $resulttext = '<span class="LC_error">'.
12990:             &mt('An error occurred: [_1]',$putresult).'</span>';
12991:     }
12992:     return $resulttext;
12993: }
12994: 
12995: sub modify_directorysrch {
12996:     my ($dom,$lastactref,%domconfig) = @_;
12997:     my ($resulttext,%changes);
12998:     my %currdirsrch;
12999:     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
13000:         foreach my $key (keys(%{$domconfig{'directorysrch'}})) {
13001:             $currdirsrch{$key} = $domconfig{'directorysrch'}{$key};
13002:         }
13003:     }
13004:     my %title = ( available => 'Institutional directory search available',
13005:                   localonly => 'Other domains can search institution',
13006:                   lcavailable => 'LON-CAPA directory search available',
13007:                   lclocalonly => 'Other domains can search LON-CAPA domain',
13008:                   searchby => 'Search types',
13009:                   searchtypes => 'Search latitude');
13010:     my @offon = ('off','on');
13011:     my @otherdoms = ('Yes','No');
13012: 
13013:     my @searchtypes = &Apache::loncommon::get_env_multiple('form.searchtypes');  
13014:     my @cansearch = &Apache::loncommon::get_env_multiple('form.cansearch');
13015:     my @searchby = &Apache::loncommon::get_env_multiple('form.searchby');
13016: 
13017:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
13018:     if (keys(%{$usertypes}) == 0) {
13019:         @cansearch = ('default');
13020:     } else {
13021:         if (ref($currdirsrch{'cansearch'}) eq 'ARRAY') {
13022:             foreach my $type (@{$currdirsrch{'cansearch'}}) {
13023:                 if (!grep(/^\Q$type\E$/,@cansearch)) {
13024:                     push(@{$changes{'cansearch'}},$type);
13025:                 }
13026:             }
13027:             foreach my $type (@cansearch) {
13028:                 if (!grep(/^\Q$type\E$/,@{$currdirsrch{'cansearch'}})) {
13029:                     push(@{$changes{'cansearch'}},$type);
13030:                 }
13031:             }
13032:         } else {
13033:             push(@{$changes{'cansearch'}},@cansearch);
13034:         }
13035:     }
13036: 
13037:     if (ref($currdirsrch{'searchby'}) eq 'ARRAY') {
13038:         foreach my $by (@{$currdirsrch{'searchby'}}) {
13039:             if (!grep(/^\Q$by\E$/,@searchby)) {
13040:                 push(@{$changes{'searchby'}},$by);
13041:             }
13042:         }
13043:         foreach my $by (@searchby) {
13044:             if (!grep(/^\Q$by\E$/,@{$currdirsrch{'searchby'}})) {
13045:                 push(@{$changes{'searchby'}},$by);
13046:             }
13047:         }
13048:     } else {
13049:         push(@{$changes{'searchby'}},@searchby);
13050:     }
13051: 
13052:     if (ref($currdirsrch{'searchtypes'}) eq 'ARRAY') {
13053:         foreach my $type (@{$currdirsrch{'searchtypes'}}) {
13054:             if (!grep(/^\Q$type\E$/,@searchtypes)) {
13055:                 push(@{$changes{'searchtypes'}},$type);
13056:             }
13057:         }
13058:         foreach my $type (@searchtypes) {
13059:             if (!grep(/^\Q$type\E$/,@{$currdirsrch{'searchtypes'}})) {
13060:                 push(@{$changes{'searchtypes'}},$type);
13061:             }
13062:         }
13063:     } else {
13064:         if (exists($currdirsrch{'searchtypes'})) {
13065:             foreach my $type (@searchtypes) {  
13066:                 if ($type ne $currdirsrch{'searchtypes'}) { 
13067:                     push(@{$changes{'searchtypes'}},$type);
13068:                 }
13069:             }
13070:             if (!grep(/^\Q$currdirsrch{'searchtypes'}\E/,@searchtypes)) {
13071:                 push(@{$changes{'searchtypes'}},$currdirsrch{'searchtypes'});
13072:             }   
13073:         } else {
13074:             push(@{$changes{'searchtypes'}},@searchtypes); 
13075:         }
13076:     }
13077: 
13078:     my %dirsrch_hash =  (
13079:             directorysrch => { available => $env{'form.dirsrch_available'},
13080:                                cansearch => \@cansearch,
13081:                                localonly => $env{'form.dirsrch_instlocalonly'},
13082:                                lclocalonly => $env{'form.dirsrch_domlocalonly'},
13083:                                lcavailable => $env{'form.dirsrch_domavailable'},
13084:                                searchby => \@searchby,
13085:                                searchtypes => \@searchtypes,
13086:                              }
13087:             );
13088:     my $putresult = &Apache::lonnet::put_dom('configuration',\%dirsrch_hash,
13089:                                              $dom);
13090:     if ($putresult eq 'ok') {
13091:         if (exists($currdirsrch{'available'})) {
13092:              if ($currdirsrch{'available'} ne $env{'form.dirsrch_available'}) {
13093:                  $changes{'available'} = 1;
13094:              }
13095:         } else {
13096:             if ($env{'form.dirsrch_available'} eq '1') {
13097:                 $changes{'available'} = 1;
13098:             }
13099:         }
13100:         if (exists($currdirsrch{'lcavailable'})) {
13101:             if ($currdirsrch{'lcavailable'} ne $env{'form.dirsrch_domavailable'}) {
13102:                 $changes{'lcavailable'} = 1;
13103:             }
13104:         } else {
13105:             if ($env{'form.dirsrch_lcavailable'} eq '1') {
13106:                 $changes{'lcavailable'} = 1;
13107:             }
13108:         }
13109:         if (exists($currdirsrch{'localonly'})) {
13110:             if ($currdirsrch{'localonly'} ne $env{'form.dirsrch_instlocalonly'}) {
13111:                 $changes{'localonly'} = 1;
13112:             }
13113:         } else {
13114:             if ($env{'form.dirsrch_instlocalonly'} eq '1') {
13115:                 $changes{'localonly'} = 1;
13116:             }
13117:         }
13118:         if (exists($currdirsrch{'lclocalonly'})) {
13119:             if ($currdirsrch{'lclocalonly'} ne $env{'form.dirsrch_domlocalonly'}) {
13120:                 $changes{'lclocalonly'} = 1;
13121:             }
13122:         } else {
13123:             if ($env{'form.dirsrch_domlocalonly'} eq '1') {
13124:                 $changes{'lclocalonly'} = 1;
13125:             }
13126:         }
13127:         if (keys(%changes) > 0) {
13128:             $resulttext = &mt('Changes made:').'<ul>';
13129:             if ($changes{'available'}) {
13130:                 $resulttext .= '<li>'.&mt("$title{'available'} set to: $offon[$env{'form.dirsrch_available'}]").'</li>';
13131:             }
13132:             if ($changes{'lcavailable'}) {
13133:                 $resulttext .= '<li>'.&mt("$title{'lcavailable'} set to: $offon[$env{'form.dirsrch_domavailable'}]").'</li>';
13134:             }
13135:             if ($changes{'localonly'}) {
13136:                 $resulttext .= '<li>'.&mt("$title{'localonly'} set to: $otherdoms[$env{'form.dirsrch_instlocalonly'}]").'</li>';
13137:             }
13138:             if ($changes{'lclocalonly'}) {
13139:                 $resulttext .= '<li>'.&mt("$title{'lclocalonly'} set to: $otherdoms[$env{'form.dirsrch_domlocalonly'}]").'</li>';
13140:             }
13141:             if (ref($changes{'cansearch'}) eq 'ARRAY') {
13142:                 my $chgtext;
13143:                 if (ref($usertypes) eq 'HASH') {
13144:                     if (keys(%{$usertypes}) > 0) {
13145:                         foreach my $type (@{$types}) {
13146:                             if (grep(/^\Q$type\E$/,@cansearch)) {
13147:                                 $chgtext .= $usertypes->{$type}.'; ';
13148:                             }
13149:                         }
13150:                         if (grep(/^default$/,@cansearch)) {
13151:                             $chgtext .= $othertitle;
13152:                         } else {
13153:                             $chgtext =~ s/\; $//;
13154:                         }
13155:                         $resulttext .=
13156:                             '<li>'.
13157:                             &mt("Users from domain '[_1]' permitted to search the institutional directory set to: [_2]",
13158:                                 '<span class="LC_cusr_emph">'.$dom.'</span>',$chgtext).
13159:                             '</li>';
13160:                     }
13161:                 }
13162:             }
13163:             if (ref($changes{'searchby'}) eq 'ARRAY') {
13164:                 my ($searchtitles,$titleorder) = &sorted_searchtitles();
13165:                 my $chgtext;
13166:                 foreach my $type (@{$titleorder}) {
13167:                     if (grep(/^\Q$type\E$/,@searchby)) {
13168:                         if (defined($searchtitles->{$type})) {
13169:                             $chgtext .= $searchtitles->{$type}.'; ';
13170:                         }
13171:                     }
13172:                 }
13173:                 $chgtext =~ s/\; $//;
13174:                 $resulttext .= '<li>'.&mt("$title{'searchby'} set to: [_1]",$chgtext).'</li>';
13175:             }
13176:             if (ref($changes{'searchtypes'}) eq 'ARRAY') {
13177:                 my ($srchtypes_desc,$srchtypeorder) = &sorted_searchtypes(); 
13178:                 my $chgtext;
13179:                 foreach my $type (@{$srchtypeorder}) {
13180:                     if (grep(/^\Q$type\E$/,@searchtypes)) {
13181:                         if (defined($srchtypes_desc->{$type})) {
13182:                             $chgtext .= $srchtypes_desc->{$type}.'; ';
13183:                         }
13184:                     }
13185:                 }
13186:                 $chgtext =~ s/\; $//;
13187:                 $resulttext .= '<li>'.&mt($title{'searchtypes'}.' set to: "[_1]"',$chgtext).'</li>';
13188:             }
13189:             $resulttext .= '</ul>';
13190:             &Apache::lonnet::do_cache_new('directorysrch',$dom,$dirsrch_hash{'directorysrch'},3600);
13191:             if (ref($lastactref) eq 'HASH') {
13192:                 $lastactref->{'directorysrch'} = 1;
13193:             }
13194:         } else {
13195:             $resulttext = &mt('No changes made to directory search settings');
13196:         }
13197:     } else {
13198:         $resulttext = '<span class="LC_error">'.
13199:                       &mt('An error occurred: [_1]',$putresult).'</span>';
13200:     }
13201:     return $resulttext;
13202: }
13203: 
13204: sub modify_contacts {
13205:     my ($dom,$lastactref,%domconfig) = @_;
13206:     my ($resulttext,%currsetting,%newsetting,%changes,%contacts_hash);
13207:     if (ref($domconfig{'contacts'}) eq 'HASH') {
13208:         foreach my $key (keys(%{$domconfig{'contacts'}})) {
13209:             $currsetting{$key} = $domconfig{'contacts'}{$key};
13210:         }
13211:     }
13212:     my (%others,%to,%bcc,%includestr,%includeloc);
13213:     my @contacts = ('supportemail','adminemail');
13214:     my @mailings = ('errormail','packagesmail','helpdeskmail','otherdomsmail',
13215:                     'lonstatusmail','requestsmail','updatesmail','idconflictsmail','hostipmail');
13216:     my @toggles = ('reporterrors','reportupdates','reportstatus');
13217:     my @lonstatus = ('threshold','sysmail','weights','excluded');
13218:     my ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
13219:     foreach my $type (@mailings) {
13220:         @{$newsetting{$type}} = 
13221:             &Apache::loncommon::get_env_multiple('form.'.$type);
13222:         foreach my $item (@contacts) {
13223:             if (grep(/^\Q$item\E$/,@{$newsetting{$type}})) {
13224:                 $contacts_hash{contacts}{$type}{$item} = 1;
13225:             } else {
13226:                 $contacts_hash{contacts}{$type}{$item} = 0;
13227:             }
13228:         }
13229:         $others{$type} = $env{'form.'.$type.'_others'};
13230:         $contacts_hash{contacts}{$type}{'others'} = $others{$type};
13231:         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
13232:             $bcc{$type} = $env{'form.'.$type.'_bcc'};
13233:             $contacts_hash{contacts}{$type}{'bcc'} = $bcc{$type};
13234:             if (($env{'form.'.$type.'_includestr'} ne '') && ($env{'form.'.$type.'_includeloc'} =~ /^s|b$/)) {
13235:                 $includestr{$type} = $env{'form.'.$type.'_includestr'};
13236:                 $includeloc{$type} = $env{'form.'.$type.'_includeloc'};
13237:                 $contacts_hash{contacts}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
13238:             }
13239:         }
13240:     }
13241:     foreach my $item (@contacts) {
13242:         $to{$item} = $env{'form.'.$item};
13243:         $contacts_hash{'contacts'}{$item} = $to{$item};
13244:     }
13245:     foreach my $item (@toggles) {
13246:         if ($env{'form.'.$item} =~ /^(0|1)$/) {
13247:             $contacts_hash{'contacts'}{$item} = $env{'form.'.$item};
13248:         }
13249:     }
13250:     my ($lonstatus_defs,$lonstatus_names) = &Apache::loncommon::lon_status_items();
13251:     foreach my $item (@lonstatus) {
13252:         if ($item eq 'excluded') {
13253:             my (%serverhomes,@excluded);
13254:             map { $serverhomes{$_} = 1; } values(%Apache::lonnet::serverhomeIDs);
13255:             my @possexcluded = &Apache::loncommon::get_env_multiple('form.errorexcluded');
13256:             if (@possexcluded) {
13257:                 foreach my $id (sort(@possexcluded)) {
13258:                     if ($serverhomes{$id}) {
13259:                         push(@excluded,$id);
13260:                     }
13261:                 }
13262:             }
13263:             if (@excluded) {
13264:                 $contacts_hash{'contacts'}{'lonstatus'}{$item} = \@excluded;
13265:             }
13266:         } elsif ($item eq 'weights') {
13267:             foreach my $type ('E','W','N','U') {
13268:                 $env{'form.error'.$item.'_'.$type} =~ s/^\s+|\s+$//g;
13269:                 if ($env{'form.error'.$item.'_'.$type} =~ /^\d+$/) {
13270:                     unless ($env{'form.error'.$item.'_'.$type} == $lonstatus_defs->{$type}) {
13271:                         $contacts_hash{'contacts'}{'lonstatus'}{$item}{$type} =
13272:                             $env{'form.error'.$item.'_'.$type};
13273:                     }
13274:                 }
13275:             }
13276:         } elsif (($item eq 'threshold') || ($item eq 'sysmail')) {
13277:             $env{'form.error'.$item} =~ s/^\s+|\s+$//g;
13278:             if ($env{'form.error'.$item} =~ /^\d+$/) {
13279:                 unless ($env{'form.error'.$item} == $lonstatus_defs->{$item}) {
13280:                     $contacts_hash{'contacts'}{'lonstatus'}{$item} = $env{'form.error'.$item};
13281:                 }
13282:             }
13283:         }
13284:     }
13285:     if ((ref($fields) eq 'ARRAY') && (ref($possoptions) eq 'HASH')) {
13286:         foreach my $field (@{$fields}) {
13287:             if (ref($possoptions->{$field}) eq 'ARRAY') {
13288:                 my $value = $env{'form.helpform_'.$field};
13289:                 $value =~ s/^\s+|\s+$//g;
13290:                 if (grep(/^\Q$value\E$/,@{$possoptions->{$field}})) {
13291:                     $contacts_hash{'contacts'}{'helpform'}{$field} = $value;
13292:                     if ($field eq 'screenshot') {
13293:                         $env{'form.helpform_maxsize'} =~ s/^\s+|\s+$//g;
13294:                         if ($env{'form.helpform_maxsize'} =~ /^\d+\.?\d*$/) {
13295:                             $contacts_hash{'contacts'}{'helpform'}{'maxsize'} = $env{'form.helpform_maxsize'};
13296:                         }
13297:                     }
13298:                 }
13299:             }
13300:         }
13301:     }
13302:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
13303:     my (@statuses,%usertypeshash,@overrides);
13304:     if ((ref($types) eq 'ARRAY') && (@{$types} > 0)) {
13305:         @statuses = @{$types};
13306:         if (ref($usertypes) eq 'HASH') {
13307:             %usertypeshash = %{$usertypes};
13308:         }
13309:     }
13310:     if (@statuses) {
13311:         my @possoverrides = &Apache::loncommon::get_env_multiple('form.overrides');
13312:         foreach my $type (@possoverrides) {
13313:             if (($type ne '') && (grep(/^\Q$type\E$/,@statuses))) {
13314:                 push(@overrides,$type);
13315:             }
13316:         }
13317:         if (@overrides) {
13318:             foreach my $type (@overrides) {
13319:                 my @standard = &Apache::loncommon::get_env_multiple('form.override_'.$type);
13320:                 foreach my $item (@contacts) {
13321:                     if (grep(/^\Q$item\E$/,@standard)) {
13322:                         $contacts_hash{'contacts'}{'overrides'}{$type}{$item} = 1;
13323:                         $newsetting{'override_'.$type}{$item} = 1;
13324:                     } else {
13325:                         $contacts_hash{'contacts'}{'overrides'}{$type}{$item} = 0;
13326:                         $newsetting{'override_'.$type}{$item} = 0;
13327:                     }
13328:                 }
13329:                 $contacts_hash{'contacts'}{'overrides'}{$type}{'others'} = $env{'form.override_'.$type.'_others'};
13330:                 $contacts_hash{'contacts'}{'overrides'}{$type}{'bcc'} = $env{'form.override_'.$type.'_bcc'};
13331:                 $newsetting{'override_'.$type}{'others'} = $env{'form.override_'.$type.'_others'};
13332:                 $newsetting{'override_'.$type}{'bcc'} = $env{'form.override_'.$type.'_bcc'};
13333:                 if (($env{'form.override_'.$type.'_includestr'} ne '') && ($env{'form.override_'.$type.'_includeloc'} =~ /^s|b$/)) {
13334:                     $includestr{$type} = $env{'form.override_'.$type.'_includestr'};
13335:                     $includeloc{$type} = $env{'form.override_'.$type.'_includeloc'};
13336:                     $contacts_hash{'contacts'}{'overrides'}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
13337:                     $newsetting{'override_'.$type}{'include'} = $contacts_hash{'contacts'}{'overrides'}{$type}{'include'};
13338:                 }
13339:             }    
13340:         }
13341:     }
13342:     if (keys(%currsetting) > 0) {
13343:         foreach my $item (@contacts) {
13344:             if ($to{$item} ne $currsetting{$item}) {
13345:                 $changes{$item} = 1;
13346:             }
13347:         }
13348:         foreach my $type (@mailings) {
13349:             foreach my $item (@contacts) {
13350:                 if (ref($currsetting{$type}) eq 'HASH') {
13351:                     if ($currsetting{$type}{$item} ne $contacts_hash{contacts}{$type}{$item}) {
13352:                         push(@{$changes{$type}},$item);
13353:                     }
13354:                 } else {
13355:                     push(@{$changes{$type}},@{$newsetting{$type}});
13356:                 }
13357:             }
13358:             if ($others{$type} ne $currsetting{$type}{'others'}) {
13359:                 push(@{$changes{$type}},'others');
13360:             }
13361:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
13362:                 if ($bcc{$type} ne $currsetting{$type}{'bcc'}) {
13363:                     push(@{$changes{$type}},'bcc'); 
13364:                 }
13365:                 my ($currloc,$currstr) = split(/:/,$currsetting{$type}{'include'},2);
13366:                 if (($includeloc{$type} ne $currloc) || (&escape($includestr{$type}) ne $currstr)) {
13367:                     push(@{$changes{$type}},'include');
13368:                 }
13369:             }
13370:         }
13371:         if (ref($fields) eq 'ARRAY') {
13372:             if (ref($currsetting{'helpform'}) eq 'HASH') {
13373:                 foreach my $field (@{$fields}) {
13374:                     if ($currsetting{'helpform'}{$field} ne $contacts_hash{'contacts'}{'helpform'}{$field}) {
13375:                         push(@{$changes{'helpform'}},$field);
13376:                     }
13377:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
13378:                         if ($currsetting{'helpform'}{'maxsize'} ne $contacts_hash{'contacts'}{'helpform'}{'maxsize'}) {
13379:                             push(@{$changes{'helpform'}},'maxsize');
13380:                         }
13381:                     }
13382:                 }
13383:             } else {
13384:                 foreach my $field (@{$fields}) {
13385:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
13386:                         push(@{$changes{'helpform'}},$field);
13387:                     }
13388:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
13389:                         if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
13390:                             push(@{$changes{'helpform'}},'maxsize');
13391:                         }
13392:                     }
13393:                 }
13394:             }
13395:         }
13396:         if (@statuses) {
13397:             if (ref($currsetting{'overrides'}) eq 'HASH') {
13398:                 foreach my $key (keys(%{$currsetting{'overrides'}})) {
13399:                     if (ref($currsetting{'overrides'}{$key}) eq 'HASH') {
13400:                         if (ref($newsetting{'override_'.$key}) eq 'HASH') {
13401:                             foreach my $item (@contacts,'bcc','others','include') {
13402:                                 if ($currsetting{'overrides'}{$key}{$item} ne $newsetting{'override_'.$key}{$item}) {
13403:                                     push(@{$changes{'overrides'}},$key);
13404:                                     last;
13405:                                 }
13406:                             }
13407:                         } else {
13408:                             push(@{$changes{'overrides'}},$key);
13409:                         }
13410:                     }
13411:                 }
13412:                 foreach my $key (@overrides) {
13413:                     unless (exists($currsetting{'overrides'}{$key})) {
13414:                         push(@{$changes{'overrides'}},$key);
13415:                     }
13416:                 }
13417:             } else {
13418:                 foreach my $key (@overrides) {
13419:                     push(@{$changes{'overrides'}},$key);
13420:                 }
13421:             }
13422:         }
13423:         if (ref($currsetting{'lonstatus'}) eq 'HASH') {
13424:             foreach my $key ('excluded','weights','threshold','sysmail') {
13425:                 if ($key eq 'excluded') {
13426:                     if ((ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') &&
13427:                         (ref($contacts_hash{contacts}{lonstatus}{excluded}) eq 'ARRAY')) {
13428:                         if ((ref($currsetting{'lonstatus'}{$key}) eq 'ARRAY') &&
13429:                             (@{$currsetting{'lonstatus'}{$key}})) {
13430:                             my @diffs =
13431:                                 &Apache::loncommon::compare_arrays($contacts_hash{contacts}{lonstatus}{excluded},
13432:                                                                    $currsetting{'lonstatus'}{$key});
13433:                             if (@diffs) {
13434:                                 push(@{$changes{'lonstatus'}},$key);
13435:                             }
13436:                         } elsif (@{$contacts_hash{contacts}{lonstatus}{excluded}}) {
13437:                             push(@{$changes{'lonstatus'}},$key);
13438:                         }
13439:                     } elsif ((ref($currsetting{'lonstatus'}{$key}) eq 'ARRAY') &&
13440:                              (@{$currsetting{'lonstatus'}{$key}})) {
13441:                         push(@{$changes{'lonstatus'}},$key);
13442:                     }
13443:                 } elsif ($key eq 'weights') {
13444:                     if ((ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') &&
13445:                         (ref($contacts_hash{contacts}{lonstatus}{$key}) eq 'HASH')) {
13446:                         if (ref($currsetting{'lonstatus'}{$key}) eq 'HASH') {
13447:                             foreach my $type ('E','W','N','U') {
13448:                                 unless ($contacts_hash{contacts}{lonstatus}{$key}{$type} eq
13449:                                         $currsetting{'lonstatus'}{$key}{$type}) {
13450:                                     push(@{$changes{'lonstatus'}},$key);
13451:                                     last;
13452:                                 }
13453:                             }
13454:                         } else {
13455:                             foreach my $type ('E','W','N','U') {
13456:                                 if ($contacts_hash{contacts}{lonstatus}{$key}{$type} ne '') {
13457:                                     push(@{$changes{'lonstatus'}},$key);
13458:                                     last;
13459:                                 }
13460:                             }
13461:                         }
13462:                     } elsif (ref($currsetting{'lonstatus'}{$key}) eq 'HASH') {
13463:                         foreach my $type ('E','W','N','U') {
13464:                             if ($currsetting{'lonstatus'}{$key}{$type} ne '') {
13465:                                 push(@{$changes{'lonstatus'}},$key);
13466:                                 last;
13467:                             }
13468:                         }
13469:                     }
13470:                 } elsif (($key eq 'threshold') || ($key eq 'sysmail')) {
13471:                     if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
13472:                         if ($currsetting{'lonstatus'}{$key} =~ /^\d+$/) {
13473:                             if ($currsetting{'lonstatus'}{$key} != $contacts_hash{contacts}{lonstatus}{$key}) {
13474:                                 push(@{$changes{'lonstatus'}},$key);
13475:                             }
13476:                         } elsif ($contacts_hash{contacts}{lonstatus}{$key} =~ /^\d+$/) {
13477:                             push(@{$changes{'lonstatus'}},$key);
13478:                         }
13479:                     } elsif ($currsetting{'lonstatus'}{$key} =~ /^\d+$/) {
13480:                         push(@{$changes{'lonstatus'}},$key);
13481:                     }
13482:                 }
13483:             }
13484:         } else {
13485:             if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
13486:                 foreach my $key ('excluded','weights','threshold','sysmail') {
13487:                     if (exists($contacts_hash{contacts}{lonstatus}{$key})) {
13488:                         push(@{$changes{'lonstatus'}},$key);
13489:                     }
13490:                 }
13491:             }
13492:         }
13493:     } else {
13494:         my %default;
13495:         $default{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
13496:         $default{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
13497:         $default{'errormail'} = 'adminemail';
13498:         $default{'packagesmail'} = 'adminemail';
13499:         $default{'helpdeskmail'} = 'supportemail';
13500:         $default{'otherdomsmail'} = 'supportemail';
13501:         $default{'lonstatusmail'} = 'adminemail';
13502:         $default{'requestsmail'} = 'adminemail';
13503:         $default{'updatesmail'} = 'adminemail';
13504:         $default{'hostipmail'} = 'adminemail';
13505:         foreach my $item (@contacts) {
13506:            if ($to{$item} ne $default{$item}) {
13507:                $changes{$item} = 1;
13508:            }
13509:         }
13510:         foreach my $type (@mailings) {
13511:             if ((@{$newsetting{$type}} != 1) || ($newsetting{$type}[0] ne $default{$type})) {
13512:                 push(@{$changes{$type}},@{$newsetting{$type}});
13513:             }
13514:             if ($others{$type} ne '') {
13515:                 push(@{$changes{$type}},'others');
13516:             }
13517:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
13518:                 if ($bcc{$type} ne '') {
13519:                     push(@{$changes{$type}},'bcc');
13520:                 }
13521:                 if (($includeloc{$type} =~ /^b|s$/) && ($includestr{$type} ne '')) {
13522:                     push(@{$changes{$type}},'include');
13523:                 }
13524:             }
13525:         }
13526:         if (ref($fields) eq 'ARRAY') {
13527:             foreach my $field (@{$fields}) {
13528:                 if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
13529:                     push(@{$changes{'helpform'}},$field);
13530:                 }
13531:                 if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
13532:                     if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
13533:                         push(@{$changes{'helpform'}},'maxsize');
13534:                     }
13535:                 }
13536:             }
13537:         }
13538:         if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
13539:             foreach my $key ('excluded','weights','threshold','sysmail') {
13540:                 if (exists($contacts_hash{contacts}{lonstatus}{$key})) {
13541:                     push(@{$changes{'lonstatus'}},$key);
13542:                 }
13543:             }
13544:         }
13545:     }
13546:     foreach my $item (@toggles) {
13547:         if (($env{'form.'.$item} == 1) && ($currsetting{$item} == 0)) {
13548:             $changes{$item} = 1;
13549:         } elsif ((!$env{'form.'.$item}) &&
13550:                  (($currsetting{$item} eq '') || ($currsetting{$item} == 1))) {
13551:             $changes{$item} = 1;
13552:         }
13553:     }
13554:     my $putresult = &Apache::lonnet::put_dom('configuration',\%contacts_hash,
13555:                                              $dom);
13556:     if ($putresult eq 'ok') {
13557:         if (keys(%changes) > 0) {
13558:             &Apache::loncommon::devalidate_domconfig_cache($dom);
13559:             if (ref($lastactref) eq 'HASH') {
13560:                 $lastactref->{'domainconfig'} = 1;
13561:             }
13562:             my ($titles,$short_titles)  = &contact_titles();
13563:             $resulttext = &mt('Changes made:').'<ul>';
13564:             foreach my $item (@contacts) {
13565:                 if ($changes{$item}) {
13566:                     $resulttext .= '<li>'.$titles->{$item}.
13567:                                     &mt(' set to: ').
13568:                                     '<span class="LC_cusr_emph">'.
13569:                                     $to{$item}.'</span></li>';
13570:                 }
13571:             }
13572:             foreach my $type (@mailings) {
13573:                 if (ref($changes{$type}) eq 'ARRAY') {
13574:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
13575:                         $resulttext .= '<li>'.$titles->{$type}.' -- '.&mt('sent to').': ';
13576:                     } else {
13577:                         $resulttext .= '<li>'.$titles->{$type}.': ';
13578:                     }
13579:                     my @text;
13580:                     foreach my $item (@{$newsetting{$type}}) {
13581:                         push(@text,$short_titles->{$item});
13582:                     }
13583:                     if ($others{$type} ne '') {
13584:                         push(@text,$others{$type});
13585:                     }
13586:                     if (@text) {
13587:                         $resulttext .= '<span class="LC_cusr_emph">'.
13588:                                        join(', ',@text).'</span>';
13589:                     }
13590:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
13591:                         if ($bcc{$type} ne '') {
13592:                             my $bcctext;
13593:                             if (@text) {
13594:                                 $bcctext = '&nbsp;'.&mt('with Bcc to');
13595:                             } else {
13596:                                 $bcctext = '(Bcc)';
13597:                             }
13598:                             $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$bcc{$type}.'</span>';
13599:                         } elsif (!@text) {
13600:                             $resulttext .= &mt('No one');
13601:                         }
13602:                         if ($includestr{$type} ne '') {
13603:                             if ($includeloc{$type} eq 'b') {
13604:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail body:').' '.$includestr{$type};
13605:                             } elsif ($includeloc{$type} eq 's') {
13606:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail subject:').' '.$includestr{$type};
13607:                             }
13608:                         }
13609:                     } elsif (!@text) {
13610:                         $resulttext .= &mt('No recipients');
13611:                     }
13612:                     $resulttext .= '</li>';
13613:                 }
13614:             }
13615:             if (ref($changes{'overrides'}) eq 'ARRAY') {
13616:                 my @deletions;
13617:                 foreach my $type (@{$changes{'overrides'}}) {
13618:                     if ($usertypeshash{$type}) {
13619:                         if (grep(/^\Q$type\E/,@overrides)) {
13620:                             $resulttext .= '<li>'.&mt("Overrides based on requester's affiliation set for [_1]",
13621:                                                       $usertypeshash{$type}).'<ul><li>';
13622:                             if (ref($newsetting{'override_'.$type}) eq 'HASH') {
13623:                                 my @text;
13624:                                 foreach my $item (@contacts) {
13625:                                     if ($newsetting{'override_'.$type}{$item}) {
13626:                                         push(@text,$short_titles->{$item});
13627:                                     }
13628:                                 }
13629:                                 if ($newsetting{'override_'.$type}{'others'} ne '') {
13630:                                     push(@text,$newsetting{'override_'.$type}{'others'});
13631:                                 }
13632: 
13633:                                 if (@text) {
13634:                                     $resulttext .= &mt('Helpdesk e-mail sent to: [_1]',
13635:                                                        '<span class="LC_cusr_emph">'.join(', ',@text).'</span>');
13636:                                 }
13637:                                 if ($newsetting{'override_'.$type}{'bcc'} ne '') {
13638:                                     my $bcctext;
13639:                                     if (@text) {
13640:                                         $bcctext = '&nbsp;'.&mt('with Bcc to');
13641:                                     } else {
13642:                                         $bcctext = '(Bcc)';
13643:                                     }
13644:                                     $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$newsetting{'override_'.$type}{'bcc'}.'</span>';
13645:                                 } elsif (!@text) {
13646:                                      $resulttext .= &mt('Helpdesk e-mail sent to no one');
13647:                                 }
13648:                                 $resulttext .= '</li>';
13649:                                 if ($newsetting{'override_'.$type}{'include'} ne '') {
13650:                                     my ($loc,$str) = split(/:/,$newsetting{'override_'.$type}{'include'});
13651:                                     if ($loc eq 'b') {
13652:                                         $resulttext .= '<li>'.&mt('Text automatically added to e-mail body:').' '.&unescape($str).'</li>';
13653:                                     } elsif ($loc eq 's') {
13654:                                         $resulttext .= '<li>'.&mt('Text automatically added to e-mail subject:').' '.&unescape($str).'</li>';
13655:                                     }
13656:                                 }
13657:                             }
13658:                             $resulttext .= '</li></ul></li>';
13659:                         } else {
13660:                             push(@deletions,$usertypeshash{$type});
13661:                         }
13662:                     }
13663:                 }
13664:                 if (@deletions) {
13665:                     $resulttext .= '<li>'.&mt("Overrides based on requester's affiliation discontinued for: [_1]",
13666:                                               join(', ',@deletions)).'</li>';
13667:                 }
13668:             }
13669:             my @offon = ('off','on');
13670:             my $corelink = &core_link_msu();
13671:             if ($changes{'reporterrors'}) {
13672:                 $resulttext .= '<li>'.
13673:                                &mt('E-mail error reports to [_1] set to "'.
13674:                                    $offon[$env{'form.reporterrors'}].'".',
13675:                                    $corelink).
13676:                                '</li>';
13677:             }
13678:             if ($changes{'reportupdates'}) {
13679:                 $resulttext .= '<li>'.
13680:                                 &mt('E-mail record of completed LON-CAPA updates to [_1] set to "'.
13681:                                     $offon[$env{'form.reportupdates'}].'".',
13682:                                     $corelink).
13683:                                 '</li>';
13684:             }
13685:             if ($changes{'reportstatus'}) {
13686:                 $resulttext .= '<li>'.
13687:                                 &mt('E-mail status if errors above threshold to [_1] set to "'.
13688:                                     $offon[$env{'form.reportstatus'}].'".',
13689:                                     $corelink).
13690:                                 '</li>';
13691:             }
13692:             if (ref($changes{'lonstatus'}) eq 'ARRAY') {
13693:                 $resulttext .= '<li>'.
13694:                                &mt('Nightly status check e-mail settings').':<ul>';
13695:                 my (%defval,%use_def,%shown);
13696:                 $defval{'threshold'} = $lonstatus_defs->{'threshold'};
13697:                 $defval{'sysmail'} = $lonstatus_defs->{'sysmail'};
13698:                 $defval{'weights'} =
13699:                     join(', ',map { $lonstatus_names->{$_}.'='.$lonstatus_defs->{$_}; } ('E','W','N','U'));
13700:                 $defval{'excluded'} = &mt('None');
13701:                 if (ref($contacts_hash{'contacts'}{'lonstatus'}) eq 'HASH') {
13702:                     foreach my $item ('threshold','sysmail','weights','excluded') {
13703:                         if (exists($contacts_hash{'contacts'}{'lonstatus'}{$item})) {
13704:                             if (($item eq 'threshold') || ($item eq 'sysmail')) {
13705:                                 $shown{$item} = $contacts_hash{'contacts'}{'lonstatus'}{$item};
13706:                             } elsif ($item eq 'weights') {
13707:                                 if (ref($contacts_hash{'contacts'}{'lonstatus'}{$item}) eq 'HASH') {
13708:                                     foreach my $type ('E','W','N','U') {
13709:                                         $shown{$item} .= $lonstatus_names->{$type}.'=';
13710:                                         if (exists($contacts_hash{'contacts'}{'lonstatus'}{$item}{$type})) {
13711:                                             $shown{$item} .= $contacts_hash{'contacts'}{'lonstatus'}{$item}{$type};
13712:                                         } else {
13713:                                             $shown{$item} .= $lonstatus_defs->{$type};
13714:                                         }
13715:                                         $shown{$item} .= ', ';
13716:                                     }
13717:                                     $shown{$item} =~ s/, $//;
13718:                                 } else {
13719:                                     $shown{$item} = $defval{$item};
13720:                                 }
13721:                             } elsif ($item eq 'excluded') {
13722:                                 if (ref($contacts_hash{'contacts'}{'lonstatus'}{$item}) eq 'ARRAY') {
13723:                                     $shown{$item} = join(', ',@{$contacts_hash{'contacts'}{'lonstatus'}{$item}});
13724:                                 } else {
13725:                                     $shown{$item} = $defval{$item};
13726:                                 }
13727:                             }
13728:                         } else {
13729:                             $shown{$item} = $defval{$item};
13730:                         }
13731:                     }
13732:                 } else {
13733:                     foreach my $item ('threshold','weights','excluded','sysmail') {
13734:                         $shown{$item} = $defval{$item};
13735:                     }
13736:                 }
13737:                 foreach my $item ('threshold','weights','excluded','sysmail') {
13738:                     $resulttext .= '<li>'.&mt($titles->{'error'.$item}.' -- [_1]',
13739:                                           $shown{$item}).'</li>';
13740:                 }
13741:                 $resulttext .= '</ul></li>';
13742:             }
13743:             if ((ref($changes{'helpform'}) eq 'ARRAY') && (ref($fields) eq 'ARRAY')) {
13744:                 my (@optional,@required,@unused,$maxsizechg);
13745:                 foreach my $field (@{$changes{'helpform'}}) {
13746:                     if ($field eq 'maxsize') {
13747:                         $maxsizechg = 1;
13748:                         next;
13749:                     }
13750:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'yes') {
13751:                         push(@optional,$field);
13752:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'no') {
13753:                         push(@unused,$field);
13754:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'req') {
13755:                         push(@required,$field);
13756:                     }
13757:                 }
13758:                 if (@optional) {
13759:                     $resulttext .= '<li>'.
13760:                                    &mt('Help form fields changed to "Optional": [_1].',
13761:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @optional)).'</span>'.
13762:                                    '</li>';
13763:                 }
13764:                 if (@required) {
13765:                     $resulttext .= '<li>'.
13766:                                    &mt('Help form fields changed to "Required": [_1].',
13767:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @required)).'</span>'.
13768:                                    '</li>';
13769:                 }
13770:                 if (@unused) {
13771:                     $resulttext .= '<li>'.
13772:                                    &mt('Help form fields changed to "Not shown": [_1].',
13773:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @unused)).'</span>'.
13774:                                    '</li>';
13775:                 }
13776:                 if ($maxsizechg) {
13777:                     $resulttext .= '<li>'.
13778:                                    &mt('Max size for file uploaded to help form by logged-in user set to [_1] MB.',
13779:                                        $contacts_hash{'contacts'}{'helpform'}{'maxsize'}).
13780:                                    '</li>';
13781:                 }
13782:             }
13783:             $resulttext .= '</ul>';
13784:         } else {
13785:             $resulttext = &mt('No changes made to contacts and form settings');
13786:         }
13787:     } else {
13788:         $resulttext = '<span class="LC_error">'.
13789:             &mt('An error occurred: [_1].',$putresult).'</span>';
13790:     }
13791:     return $resulttext;
13792: }
13793: 
13794: sub modify_passwords {
13795:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
13796:     my ($resulttext,%current,%changes,%newvalues,@oktypes,$errors,
13797:         $updatedefaults,$updateconf);
13798:     my $customfn = 'resetpw.html';
13799:     if (ref($domconfig{'passwords'}) eq 'HASH') {
13800:         %current = %{$domconfig{'passwords'}};
13801:     }
13802:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
13803:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
13804:     if (ref($types) eq 'ARRAY') {
13805:         @oktypes = @{$types};
13806:     }
13807:     push(@oktypes,'default');
13808: 
13809:     my %titles = &Apache::lonlocal::texthash (
13810:         intauth_cost   => 'Encryption cost for bcrypt (positive integer)',
13811:         intauth_check  => 'Check bcrypt cost if authenticated',
13812:         intauth_switch => 'Existing crypt-based switched to bcrypt on authentication',
13813:         permanent      => 'Permanent e-mail address',
13814:         critical       => 'Critical notification address',
13815:         notify         => 'Notification address',
13816:         min            => 'Minimum password length',
13817:         max            => 'Maximum password length',
13818:         chars          => 'Required characters',
13819:         numsaved       => 'Number of previous passwords to save',
13820:         reset          => 'Resetting Forgotten Password',
13821:         intauth        => 'Encryption of Stored Passwords (Internal Auth)',
13822:         rules          => 'Rules for LON-CAPA Passwords',
13823:         crsownerchg    => 'Course Owner Changing Student Passwords',
13824:         username       => 'Username',
13825:         email          => 'E-mail address',
13826:     );
13827: 
13828: #
13829: # Retrieve current domain configuration for internal authentication from $domconfig{'defaults'}.
13830: #
13831:     my (%curr_defaults,%save_defaults);
13832:     if (ref($domconfig{'defaults'}) eq 'HASH') {
13833:         foreach my $key (keys(%{$domconfig{'defaults'}})) {
13834:             if ($key =~ /^intauth_(cost|check|switch)$/) {
13835:                 $curr_defaults{$key} = $domconfig{'defaults'}{$key};
13836:             } else {
13837:                 $save_defaults{$key} = $domconfig{'defaults'}{$key};
13838:             }
13839:         }
13840:     }
13841:     my %staticdefaults = (
13842:         'resetlink'      => 2,
13843:         'resetcase'      => \@oktypes,
13844:         'resetprelink'   => 'both',
13845:         'resetemail'     => ['critical','notify','permanent'],
13846:         'intauth_cost'   => 10,
13847:         'intauth_check'  => 0,
13848:         'intauth_switch' => 0,
13849:     );
13850:     $staticdefaults{'min'} = $Apache::lonnet::passwdmin;
13851:     foreach my $type (@oktypes) {
13852:         $staticdefaults{'resetpostlink'}{$type} = ['email','username'];
13853:     }
13854:     my $linklife = $env{'form.passwords_link'};
13855:     $linklife =~ s/^\s+|\s+$//g;
13856:     if (($linklife =~ /^\d+(|\.\d*)$/) && ($linklife > 0)) {
13857:         $newvalues{'resetlink'} = $linklife;
13858:         if ($current{'resetlink'}) {
13859:             if ($current{'resetlink'} ne $linklife) {
13860:                 $changes{'reset'} = 1;
13861:             }
13862:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
13863:             if ($staticdefaults{'resetlink'} ne $linklife) {
13864:                 $changes{'reset'} = 1;
13865:             }
13866:         }
13867:     } elsif ($current{'resetlink'}) {
13868:         $changes{'reset'} = 1;
13869:     }
13870:     my @casesens;
13871:     my @posscase = &Apache::loncommon::get_env_multiple('form.passwords_case_sensitive');
13872:     foreach my $case (sort(@posscase)) {
13873:         if (grep(/^\Q$case\E$/,@oktypes)) {
13874:             push(@casesens,$case);
13875:         }
13876:     }
13877:     $newvalues{'resetcase'} = \@casesens;
13878:     if (ref($current{'resetcase'}) eq 'ARRAY') {
13879:         my @diffs = &Apache::loncommon::compare_arrays($current{'resetcase'},\@casesens);
13880:         if (@diffs > 0) {
13881:             $changes{'reset'} = 1;
13882:         }
13883:     } elsif (!ref($domconfig{passwords}) eq 'HASH') {
13884:         my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetcase'},\@casesens);
13885:         if (@diffs > 0) {
13886:             $changes{'reset'} = 1;
13887:         }
13888:     }
13889:     if ($env{'form.passwords_prelink'} =~ /^(both|either)$/) {
13890:         $newvalues{'resetprelink'} = $env{'form.passwords_prelink'};
13891:         if (exists($current{'resetprelink'})) {
13892:             if ($current{'resetprelink'} ne $newvalues{'resetprelink'}) {
13893:                 $changes{'reset'} = 1;
13894:             }
13895:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
13896:             if ($staticdefaults{'resetprelink'} ne $newvalues{'resetprelink'}) {
13897:                 $changes{'reset'} = 1;
13898:             }
13899:         }
13900:     } elsif ($current{'resetprelink'}) {
13901:         $changes{'reset'} = 1;
13902:     }
13903:     foreach my $type (@oktypes) {
13904:         my @possplink = &Apache::loncommon::get_env_multiple('form.passwords_postlink_'.$type);
13905:         my @postlink;
13906:         foreach my $item (sort(@possplink)) {
13907:             if ($item =~ /^(email|username)$/) {
13908:                 push(@postlink,$item);
13909:             }
13910:         }
13911:         $newvalues{'resetpostlink'}{$type} = \@postlink;
13912:         unless ($changes{'reset'}) {
13913:             if (ref($current{'resetpostlink'}) eq 'HASH') {
13914:                 if (ref($current{'resetpostlink'}{$type}) eq 'ARRAY') {
13915:                     my @diffs = &Apache::loncommon::compare_arrays($current{'resetpostlink'}{$type},\@postlink);
13916:                     if (@diffs > 0) {
13917:                         $changes{'reset'} = 1;
13918:                     }
13919:                 } else {
13920:                     $changes{'reset'} = 1;
13921:                 }
13922:             } elsif (!ref($domconfig{passwords}) eq 'HASH') {
13923:                 my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetpostlink'}{$type},\@postlink);
13924:                 if (@diffs > 0) {
13925:                     $changes{'reset'} = 1;
13926:                 }
13927:             }
13928:         }
13929:     }
13930:     my @possemailsrc = &Apache::loncommon::get_env_multiple('form.passwords_emailsrc');
13931:     my @resetemail;
13932:     foreach my $item (sort(@possemailsrc)) {
13933:         if ($item =~ /^(permanent|critical|notify)$/) {
13934:             push(@resetemail,$item);
13935:         }
13936:     }
13937:     $newvalues{'resetemail'} = \@resetemail;
13938:     unless ($changes{'reset'}) {
13939:         if (ref($current{'resetemail'}) eq 'ARRAY') {
13940:             my @diffs = &Apache::loncommon::compare_arrays($current{'resetemail'},\@resetemail);
13941:             if (@diffs > 0) {
13942:                 $changes{'reset'} = 1;
13943:             }
13944:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
13945:             my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetemail'},\@resetemail);
13946:             if (@diffs > 0) {
13947:                 $changes{'reset'} = 1;
13948:             }
13949:         }
13950:     }
13951:     if ($env{'form.passwords_stdtext'} == 0) {
13952:         $newvalues{'resetremove'} = 1;
13953:         unless ($current{'resetremove'}) {
13954:             $changes{'reset'} = 1;
13955:         }
13956:     } elsif ($current{'resetremove'}) {
13957:         $changes{'reset'} = 1;
13958:     }
13959:     if ($env{'form.passwords_customfile.filename'} ne '') {
13960:         my $servadm = $r->dir_config('lonAdmEMail');
13961:         my $servadm = $r->dir_config('lonAdmEMail');
13962:         my ($configuserok,$author_ok,$switchserver) =
13963:             &config_check($dom,$confname,$servadm);
13964:         my $error;
13965:         if ($configuserok eq 'ok') {
13966:             if ($switchserver) {
13967:                 $error = &mt("Upload of file containing domain-specific text is not permitted to this server: [_1]",$switchserver);
13968:             } else {
13969:                 if ($author_ok eq 'ok') {
13970:                     my ($result,$customurl) =
13971:                         &publishlogo($r,'upload','passwords_customfile',$dom,
13972:                                      $confname,'customtext/resetpw','','',$customfn);
13973:                     if ($result eq 'ok') {
13974:                         $newvalues{'resetcustom'} = $customurl;
13975:                         $changes{'reset'} = 1;
13976:                     } else {
13977:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$customfn,$result);
13978:                     }
13979:                 } else {
13980:                     $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);
13981:                 }
13982:             }
13983:         } else {
13984:             $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);
13985:         }
13986:         if ($error) {
13987:             &Apache::lonnet::logthis($error);
13988:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
13989:         }
13990:     } elsif ($current{'resetcustom'}) {
13991:         if ($env{'form.passwords_custom_del'}) {
13992:             $changes{'reset'} = 1;
13993:         } else {
13994:             $newvalues{'resetcustom'} = $current{'resetcustom'};
13995:         }
13996:     }
13997:     $env{'form.intauth_cost'} =~ s/^\s+|\s+$//g;
13998:     if (($env{'form.intauth_cost'} ne '') && ($env{'form.intauth_cost'} =~ /^\d+$/)) {
13999:         $save_defaults{'intauth_cost'} = $env{'form.intauth_cost'};
14000:         if ($save_defaults{'intauth_cost'} ne $curr_defaults{'intauth_cost'}) {
14001:             $changes{'intauth'} = 1;
14002:         }
14003:     } else {
14004:         $save_defaults{'intauth_cost'} = $curr_defaults{'intauth_cost'};
14005:     }
14006:     if ($env{'form.intauth_check'} =~ /^(0|1|2)$/) {
14007:         $save_defaults{'intauth_check'} = $env{'form.intauth_check'};
14008:         if ($save_defaults{'intauth_check'} ne $curr_defaults{'intauth_check'}) {
14009:             $changes{'intauth'} = 1;
14010:         }
14011:     } else {
14012:         $save_defaults{'intauth_check'} = $curr_defaults{'intauth_check'};
14013:     }
14014:     if ($env{'form.intauth_switch'} =~ /^(0|1|2)$/) {
14015:         $save_defaults{'intauth_switch'} = $env{'form.intauth_switch'};
14016:         if ($save_defaults{'intauth_switch'} ne $curr_defaults{'intauth_switch'}) {
14017:             $changes{'intauth'} = 1;
14018:         }
14019:     } else {
14020:         $save_defaults{'intauth_check'} = $curr_defaults{'intauth_check'};
14021:     }
14022:     foreach my $item ('cost','check','switch') {
14023:         if ($save_defaults{'intauth_'.$item} ne $domdefaults{'intauth_'.$item}) {
14024:             $domdefaults{'intauth_'.$item} = $save_defaults{'intauth_'.$item};
14025:             $updatedefaults = 1;
14026:         }
14027:     }
14028:     foreach my $rule ('min','max','numsaved') {
14029:         $env{'form.passwords_'.$rule} =~ s/^\s+|\s+$//g;
14030:         my $ruleok;
14031:         if ($rule eq 'min') {
14032:             if ($env{'form.passwords_'.$rule} =~ /^\d+$/) {
14033:                 if ($env{'form.passwords_'.$rule} >= $Apache::lonnet::passwdmin) {
14034:                     $ruleok = 1;
14035:                 }
14036:             }
14037:         } elsif (($env{'form.passwords_'.$rule} =~ /^\d+$/) &&
14038:                  ($env{'form.passwords_'.$rule} ne '0')) {
14039:             $ruleok = 1;
14040:         }
14041:         if ($ruleok) {
14042:             $newvalues{$rule} = $env{'form.passwords_'.$rule};
14043:             if (exists($current{$rule})) {
14044:                 if ($newvalues{$rule} ne $current{$rule}) {
14045:                     $changes{'rules'} = 1;
14046:                 }
14047:             } elsif ($rule eq 'min') {
14048:                 if ($staticdefaults{$rule} ne $newvalues{$rule}) {
14049:                     $changes{'rules'} = 1;
14050:                 }
14051:             } else {
14052:                 $changes{'rules'} = 1;
14053:             }
14054:         } elsif (exists($current{$rule})) {
14055:             $changes{'rules'} = 1;
14056:         }
14057:     }
14058:     my @posschars = &Apache::loncommon::get_env_multiple('form.passwords_chars');
14059:     my @chars;
14060:     foreach my $item (sort(@posschars)) {
14061:         if ($item =~ /^(uc|lc|num|spec)$/) {
14062:             push(@chars,$item);
14063:         }
14064:     }
14065:     $newvalues{'chars'} = \@chars;
14066:     unless ($changes{'rules'}) {
14067:         if (ref($current{'chars'}) eq 'ARRAY') {
14068:             my @diffs = &Apache::loncommon::compare_arrays($current{'chars'},\@chars);
14069:             if (@diffs > 0) {
14070:                 $changes{'rules'} = 1;
14071:             }
14072:         } else {
14073:             if (@chars > 0) {
14074:                 $changes{'rules'} = 1;
14075:             }
14076:         }
14077:     }
14078:     my %crsownerchg = (
14079:                         by => [],
14080:                         for => [],
14081:                       );
14082:     foreach my $item ('by','for') {
14083:         my @posstypes = &Apache::loncommon::get_env_multiple('form.passwords_crsowner_'.$item);
14084:         foreach my $type (sort(@posstypes)) {
14085:             if (grep(/^\Q$type\E$/,@oktypes)) {
14086:                 push(@{$crsownerchg{$item}},$type);
14087:             }
14088:         }
14089:     }
14090:     $newvalues{'crsownerchg'} = \%crsownerchg;
14091:     if (ref($current{'crsownerchg'}) eq 'HASH') {
14092:         foreach my $item ('by','for') {
14093:             if (ref($current{'crsownerchg'}{$item}) eq 'ARRAY') {
14094:                 my @diffs = &Apache::loncommon::compare_arrays($current{'crsownerchg'}{$item},$crsownerchg{$item});
14095:                 if (@diffs > 0) {
14096:                     $changes{'crsownerchg'} = 1;
14097:                     last;
14098:                 }
14099:             }
14100:         }
14101:     } elsif (!(ref($domconfig{passwords}) eq 'HASH')) {
14102:         foreach my $item ('by','for') {
14103:             if (@{$crsownerchg{$item}} > 0) {
14104:                 $changes{'crsownerchg'} = 1;
14105:                 last;
14106:             }
14107:         }
14108:     }
14109: 
14110:     my %confighash = (
14111:                         defaults  => \%save_defaults,
14112:                         passwords => \%newvalues,
14113:                      );
14114:     &process_captcha('passwords',\%changes,$confighash{'passwords'},$domconfig{'passwords'});
14115: 
14116:     my $putresult = &Apache::lonnet::put_dom('configuration',\%confighash,$dom);
14117:     if ($putresult eq 'ok') {
14118:         if (keys(%changes) > 0) {
14119:             $resulttext = &mt('Changes made: ').'<ul>';
14120:             foreach my $key ('reset','intauth','rules','crsownerchg') {
14121:                 if ($changes{$key}) {
14122:                     unless ($key eq 'intauth') {
14123:                         $updateconf = 1;
14124:                     }
14125:                     $resulttext .= '<li>'.$titles{$key}.':<ul>';
14126:                     if ($key eq 'reset') {
14127:                         if ($confighash{'passwords'}{'captcha'} eq 'original') {
14128:                             $resulttext .= '<li>'.&mt('CAPTCHA validation set to use: original CAPTCHA').'</li>';
14129:                         } elsif ($confighash{'passwords'}{'captcha'} eq 'recaptcha') {
14130:                             $resulttext .= '<li>'.&mt('CAPTCHA validation set to use: reCAPTCHA').' '.
14131:                                            &mt('version: [_1]',$confighash{'passwords'}{'recaptchaversion'}).'<br />';
14132:                             if (ref($confighash{'passwords'}{'recaptchakeys'}) eq 'HASH') {
14133:                                 $resulttext .= &mt('Public key: [_1]',$confighash{'passwords'}{'recaptchakeys'}{'public'}).'</br>'.
14134:                                                &mt('Private key: [_1]',$confighash{'passwords'}{'recaptchakeys'}{'private'}).'</li>';
14135:                             }
14136:                         } else {
14137:                             $resulttext .= '<li>'.&mt('No CAPTCHA validation').'</li>';
14138:                         }
14139:                         if ($confighash{'passwords'}{'resetlink'}) {
14140:                             $resulttext .= '<li>'.&mt('Reset link expiration set to [quant,_1,hour]',$confighash{'passwords'}{'resetlink'}).'</li>';
14141:                         } else {
14142:                             $resulttext .= '<li>'.&mt('No reset link expiration set.').' '.
14143:                                                   &mt('Will default to 2 hours').'</li>';
14144:                         }
14145:                         if (ref($confighash{'passwords'}{'resetcase'}) eq 'ARRAY') {
14146:                             if (@{$confighash{'passwords'}{'resetcase'}} == 0) {
14147:                                 $resulttext .= '<li>'.&mt('User input for username and/or e-mail address not case sensitive for "Forgot Password" web form').'</li>';
14148:                             } else {
14149:                                 my $casesens;
14150:                                 foreach my $type (@{$confighash{'passwords'}{'resetcase'}}) {
14151:                                     if ($type eq 'default') {
14152:                                         $casesens .= $othertitle.', ';
14153:                                     } elsif ($usertypes->{$type} ne '') {
14154:                                         $casesens .= $usertypes->{$type}.', ';
14155:                                     }
14156:                                 }
14157:                                 $casesens =~ s/\Q, \E$//;
14158:                                 $resulttext .= '<li>'.&mt('"Forgot Password" web form input for username and/or e-mail address is case-sensitive for: [_1]',$casesens).'</li>';
14159:                             }
14160:                         } else {
14161:                             $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>';
14162:                         }
14163:                         if ($confighash{'passwords'}{'resetprelink'} eq 'either') {
14164:                             $resulttext .= '<li>'.&mt('Users can enter either a username or an e-mail address in "Forgot Password" web form').'</li>';
14165:                         } else {
14166:                             $resulttext .= '<li>'.&mt('Users can enter both a username and an e-mail address in "Forgot Password" web form').'</li>';
14167:                         }
14168:                         if (ref($confighash{'passwords'}{'resetpostlink'}) eq 'HASH') {
14169:                             my $output;
14170:                             if (ref($types) eq 'ARRAY') {
14171:                                 foreach my $type (@{$types}) {
14172:                                     if (ref($confighash{'passwords'}{'resetpostlink'}{$type}) eq 'ARRAY') {
14173:                                         if (@{$confighash{'passwords'}{'resetpostlink'}{$type}} == 0) {
14174:                                             $output .= $usertypes->{$type}.' -- '.&mt('none');
14175:                                         } else {
14176:                                             $output .= $usertypes->{$type}.' -- '.
14177:                                                        join(', ',map { $titles{$_}; } (@{$confighash{'passwords'}{'resetpostlink'}{$type}})).'; ';
14178:                                         }
14179:                                     }
14180:                                 }
14181:                             }
14182:                             if (ref($confighash{'passwords'}{'resetpostlink'}{'default'}) eq 'ARRAY') {
14183:                                 if (@{$confighash{'passwords'}{'resetpostlink'}{'default'}} == 0) {
14184:                                     $output .= $othertitle.' -- '.&mt('none');
14185:                                 } else {
14186:                                     $output .= $othertitle.' -- '.
14187:                                                join(', ',map { $titles{$_}; } (@{$confighash{'passwords'}{'resetpostlink'}{'default'}}));
14188:                                 }
14189:                             }
14190:                             if ($output) {
14191:                                 $resulttext .= '<li>'.&mt('Information required for new password form (by user type) set to: [_1]',$output).'</li>';
14192:                             } else {
14193:                                 $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>';
14194:                             }
14195:                         } else {
14196:                             $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>';
14197:                         }
14198:                         if (ref($confighash{'passwords'}{'resetemail'}) eq 'ARRAY') {
14199:                             if (@{$confighash{'passwords'}{'resetemail'}} > 0) {
14200:                                 $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$confighash{'passwords'}{'resetemail'}})).'</li>';
14201:                             } else {
14202:                                 $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$staticdefaults{'resetemail'}})).'</li>';
14203:                             }
14204:                         } else {
14205:                             $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$staticdefaults{'resetemail'}})).'</li>';
14206:                         }
14207:                         if ($confighash{'passwords'}{'resetremove'}) {
14208:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" web form not shown').'</li>';
14209:                         } else {
14210:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" web form is shown').'</li>';
14211:                         }
14212:                         if ($confighash{'passwords'}{'resetcustom'}) {
14213:                             my $customlink = &Apache::loncommon::modal_link($confighash{'passwords'}{'resetcustom'},
14214:                                                                             &mt('custom text'),600,500,undef,undef,
14215:                                                                             undef,undef,'background-color:#ffffff');
14216:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" form includes: [_1]',$customlink).'</li>';
14217:                         } else {
14218:                             $resulttext .= '<li>'.&mt('No custom text included in preamble to "Forgot Password" form').'</li>';
14219:                         }
14220:                     } elsif ($key eq 'intauth') {
14221:                         foreach my $item ('cost','switch','check') {
14222:                             my $value = $save_defaults{$key.'_'.$item};
14223:                             if ($item eq 'switch') {
14224:                                 my %optiondesc = &Apache::lonlocal::texthash (
14225:                                                      0 => 'No',
14226:                                                      1 => 'Yes',
14227:                                                      2 => 'Yes, and copy existing passwd file to passwd.bak file',
14228:                                                  );
14229:                                 if ($value =~ /^(0|1|2)$/) {
14230:                                     $value = $optiondesc{$value};
14231:                                 } else {
14232:                                     $value = &mt('none -- defaults to No');
14233:                                 }
14234:                             } elsif ($item eq 'check') {
14235:                                 my %optiondesc = &Apache::lonlocal::texthash (
14236:                                                      0 => 'No',
14237:                                                      1 => 'Yes, allow login then update passwd file using default cost (if higher)',
14238:                                                      2 => 'Yes, disallow login if stored cost is less than domain default',
14239:                                                  );
14240:                                 if ($value =~ /^(0|1|2)$/) {
14241:                                     $value = $optiondesc{$value};
14242:                                 } else {
14243:                                     $value = &mt('none -- defaults to No');
14244:                                 }
14245:                             }
14246:                             $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$titles{$key.'_'.$item},$value).'</li>';
14247:                         }
14248:                     } elsif ($key eq 'rules') {
14249:                         foreach my $rule ('min','max','numsaved') {
14250:                             if ($confighash{'passwords'}{$rule} eq '') {
14251:                                 if ($rule eq 'min') {
14252:                                     $resulttext .= '<li>'.&mt('[_1] not set.',$titles{$rule});
14253:                                                    ' '.&mt('Default of [_1] will be used',
14254:                                                            $Apache::lonnet::passwdmin).'</li>';
14255:                                 } else {
14256:                                     $resulttext .= '<li>'.&mt('[_1] set to none',$titles{$rule}).'</li>';
14257:                                 }
14258:                             } else {
14259:                                 $resulttext .= '<li>'.&mt('[_1] set to [_2]',$titles{$rule},$confighash{'passwords'}{$rule}).'</li>';
14260:                             }
14261:                         }
14262:                         if (ref($confighash{'passwords'}{'chars'}) eq 'ARRAY') {
14263:                             if (@{$confighash{'passwords'}{'chars'}} > 0) {
14264:                                 my %rulenames = &Apache::lonlocal::texthash(
14265:                                                      uc => 'At least one upper case letter',
14266:                                                      lc => 'At least one lower case letter',
14267:                                                      num => 'At least one number',
14268:                                                      spec => 'At least one non-alphanumeric',
14269:                                                    );
14270:                                 my $needed = '<ul><li>'.
14271:                                              join('</li><li>',map {$rulenames{$_} } @{$confighash{'passwords'}{'chars'}}).
14272:                                              '</li></ul>';
14273:                                 $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$titles{'chars'},$needed).'</li>';
14274:                             } else {
14275:                                 $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
14276:                             }
14277:                         } else {
14278:                             $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
14279:                         }
14280:                     } elsif ($key eq 'crsownerchg') {
14281:                         if (ref($confighash{'passwords'}{'crsownerchg'}) eq 'HASH') {
14282:                             if ((@{$confighash{'passwords'}{'crsownerchg'}{'by'}} == 0) ||
14283:                                 (@{$confighash{'passwords'}{'crsownerchg'}{'for'}} == 0)) {
14284:                                 $resulttext .= '<li>'.&mt('Course owner may not change student passwords.').'</li>';
14285:                             } else {
14286:                                 my %crsownerstr;
14287:                                 foreach my $item ('by','for') {
14288:                                     if (ref($confighash{'passwords'}{'crsownerchg'}{$item}) eq 'ARRAY') {
14289:                                         foreach my $type (@{$confighash{'passwords'}{'crsownerchg'}{$item}}) {
14290:                                             if ($type eq 'default') {
14291:                                                 $crsownerstr{$item} .= $othertitle.', ';
14292:                                             } elsif ($usertypes->{$type} ne '') {
14293:                                                 $crsownerstr{$item} .= $usertypes->{$type}.', ';
14294:                                             }
14295:                                         }
14296:                                         $crsownerstr{$item} =~ s/\Q, \E$//;
14297:                                     }
14298:                                 }
14299:                                 $resulttext .= '<li>'.&mt('Course owner (with status: [_1]) may change passwords for students (with status: [_2]).',
14300:                                            $crsownerstr{'by'},$crsownerstr{'for'}).'</li>';
14301:                             }
14302:                         } else {
14303:                             $resulttext .= '<li>'.&mt('Course owner may not change student passwords.').'</li>';
14304:                         }
14305:                     }
14306:                     $resulttext .= '</ul></li>';
14307:                 }
14308:             }
14309:             $resulttext .= '</ul>';
14310:         } else {
14311:             $resulttext = &mt('No changes made to password settings');
14312:         }
14313:         my $cachetime = 24*60*60;
14314:         if ($updatedefaults) {
14315:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
14316:             if (ref($lastactref) eq 'HASH') {
14317:                 $lastactref->{'domdefaults'} = 1;
14318:             }
14319:         }
14320:         if ($updateconf) {
14321:             &Apache::lonnet::do_cache_new('passwdconf',$dom,$confighash{'passwords'},$cachetime);
14322:             if (ref($lastactref) eq 'HASH') {
14323:                 $lastactref->{'passwdconf'} = 1;
14324:             }
14325:         }
14326:     } else {
14327:         $resulttext = '<span class="LC_error">'.
14328:             &mt('An error occurred: [_1]',$putresult).'</span>';
14329:     }
14330:     if ($errors) {
14331:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
14332:                        $errors.'</ul></p>';
14333:     }
14334:     return $resulttext;
14335: }
14336: 
14337: sub modify_usercreation {
14338:     my ($dom,%domconfig) = @_;
14339:     my ($resulttext,%curr_usercreation,%changes,%authallowed,%cancreate,%save_usercreate);
14340:     my $warningmsg;
14341:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
14342:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
14343:             if ($key eq 'cancreate') {
14344:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
14345:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
14346:                         if (($item eq 'requestcrs') || ($item eq 'course') || ($item eq 'author')) {
14347:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
14348:                         } else {
14349:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
14350:                         }
14351:                     }
14352:                 }
14353:             } elsif ($key eq 'email_rule') {
14354:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
14355:             } else {
14356:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
14357:             }
14358:         }
14359:     }
14360:     my @username_rule = &Apache::loncommon::get_env_multiple('form.username_rule');
14361:     my @id_rule = &Apache::loncommon::get_env_multiple('form.id_rule');
14362:     my @contexts = ('author','course','requestcrs');
14363:     foreach my $item(@contexts) {
14364:         $cancreate{$item} = $env{'form.can_createuser_'.$item};
14365:     }
14366:     if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
14367:         foreach my $item (@contexts) {
14368:             if ($curr_usercreation{'cancreate'}{$item} ne $cancreate{$item}) {
14369:                 push(@{$changes{'cancreate'}},$item);
14370:             }
14371:         }
14372:     } elsif (ref($curr_usercreation{'cancreate'}) eq 'ARRAY') {
14373:         foreach my $item (@contexts) {
14374:             if (!grep(/^\Q$item\E$/,@{$curr_usercreation{'cancreate'}})) {
14375:                 if ($cancreate{$item} ne 'any') {
14376:                     push(@{$changes{'cancreate'}},$item);
14377:                 }
14378:             } else {
14379:                 if ($cancreate{$item} ne 'none') {
14380:                     push(@{$changes{'cancreate'}},$item);
14381:                 }
14382:             }
14383:         }
14384:     } else {
14385:         foreach my $item (@contexts)  {
14386:             push(@{$changes{'cancreate'}},$item);
14387:         }
14388:     }
14389: 
14390:     if (ref($curr_usercreation{'username_rule'}) eq 'ARRAY') {
14391:         foreach my $type (@{$curr_usercreation{'username_rule'}}) {
14392:             if (!grep(/^\Q$type\E$/,@username_rule)) {
14393:                 push(@{$changes{'username_rule'}},$type);
14394:             }
14395:         }
14396:         foreach my $type (@username_rule) {
14397:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'username_rule'}})) {
14398:                 push(@{$changes{'username_rule'}},$type);
14399:             }
14400:         }
14401:     } else {
14402:         push(@{$changes{'username_rule'}},@username_rule);
14403:     }
14404: 
14405:     if (ref($curr_usercreation{'id_rule'}) eq 'ARRAY') {
14406:         foreach my $type (@{$curr_usercreation{'id_rule'}}) {
14407:             if (!grep(/^\Q$type\E$/,@id_rule)) {
14408:                 push(@{$changes{'id_rule'}},$type);
14409:             }
14410:         }
14411:         foreach my $type (@id_rule) {
14412:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'id_rule'}})) {
14413:                 push(@{$changes{'id_rule'}},$type);
14414:             }
14415:         }
14416:     } else {
14417:         push(@{$changes{'id_rule'}},@id_rule);
14418:     }
14419: 
14420:     my @authen_contexts = ('author','course','domain');
14421:     my @authtypes = ('int','krb4','krb5','loc');
14422:     my %authhash;
14423:     foreach my $item (@authen_contexts) {
14424:         my @authallowed =  &Apache::loncommon::get_env_multiple('form.'.$item.'_auth');
14425:         foreach my $auth (@authtypes) {
14426:             if (grep(/^\Q$auth\E$/,@authallowed)) {
14427:                 $authhash{$item}{$auth} = 1;
14428:             } else {
14429:                 $authhash{$item}{$auth} = 0;
14430:             }
14431:         }
14432:     }
14433:     if (ref($curr_usercreation{'authtypes'}) eq 'HASH') {
14434:         foreach my $item (@authen_contexts) {
14435:             if (ref($curr_usercreation{'authtypes'}{$item}) eq 'HASH') {
14436:                 foreach my $auth (@authtypes) {
14437:                     if ($authhash{$item}{$auth} ne $curr_usercreation{'authtypes'}{$item}{$auth}) {
14438:                         push(@{$changes{'authtypes'}},$item);
14439:                         last;
14440:                     }
14441:                 }
14442:             }
14443:         }
14444:     } else {
14445:         foreach my $item (@authen_contexts) {
14446:             push(@{$changes{'authtypes'}},$item);
14447:         }
14448:     }
14449: 
14450:     $save_usercreate{'cancreate'}{'course'} = $cancreate{'course'}; 
14451:     $save_usercreate{'cancreate'}{'author'} = $cancreate{'author'};
14452:     $save_usercreate{'cancreate'}{'requestcrs'} = $cancreate{'requestcrs'};
14453:     $save_usercreate{'id_rule'} = \@id_rule;
14454:     $save_usercreate{'username_rule'} = \@username_rule,
14455:     $save_usercreate{'authtypes'} = \%authhash;
14456: 
14457:     my %usercreation_hash =  (
14458:         usercreation     => \%save_usercreate,
14459:     );
14460: 
14461:     my $putresult = &Apache::lonnet::put_dom('configuration',\%usercreation_hash,
14462:                                              $dom);
14463: 
14464:     if ($putresult eq 'ok') {
14465:         if (keys(%changes) > 0) {
14466:             $resulttext = &mt('Changes made:').'<ul>';
14467:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
14468:                 my %lt = &usercreation_types();
14469:                 foreach my $type (@{$changes{'cancreate'}}) {
14470:                     my $chgtext = $lt{$type}.', ';
14471:                     if ($cancreate{$type} eq 'none') {
14472:                         $chgtext .= &mt('creation of new users is not permitted, except by a Domain Coordinator.');
14473:                     } elsif ($cancreate{$type} eq 'any') {
14474:                         $chgtext .= &mt('creation of new users is permitted for both institutional and non-institutional usernames.');
14475:                     } elsif ($cancreate{$type} eq 'official') {
14476:                         $chgtext .= &mt('creation of new users is only permitted for institutional usernames.');
14477:                     } elsif ($cancreate{$type} eq 'unofficial') {
14478:                         $chgtext .= &mt('creation of new users is only permitted for non-institutional usernames.');
14479:                     }
14480:                     $resulttext .= '<li>'.$chgtext.'</li>';
14481:                 }
14482:             }
14483:             if (ref($changes{'username_rule'}) eq 'ARRAY') {
14484:                 my ($rules,$ruleorder) = 
14485:                     &Apache::lonnet::inst_userrules($dom,'username');
14486:                 my $chgtext = '<ul>';
14487:                 foreach my $type (@username_rule) {
14488:                     if (ref($rules->{$type}) eq 'HASH') {
14489:                         $chgtext .= '<li>'.$rules->{$type}{'name'}.'</li>';
14490:                     }
14491:                 }
14492:                 $chgtext .= '</ul>';
14493:                 if (@username_rule > 0) {
14494:                     $resulttext .= '<li>'.&mt('Usernames with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';     
14495:                 } else {
14496:                     $resulttext .= '<li>'.&mt('There are now no username formats restricted to verified users in the institutional directory.').'</li>'; 
14497:                 }
14498:             }
14499:             if (ref($changes{'id_rule'}) eq 'ARRAY') {
14500:                 my ($idrules,$idruleorder) = 
14501:                     &Apache::lonnet::inst_userrules($dom,'id');
14502:                 my $chgtext = '<ul>';
14503:                 foreach my $type (@id_rule) {
14504:                     if (ref($idrules->{$type}) eq 'HASH') {
14505:                         $chgtext .= '<li>'.$idrules->{$type}{'name'}.'</li>';
14506:                     }
14507:                 }
14508:                 $chgtext .= '</ul>';
14509:                 if (@id_rule > 0) {
14510:                     $resulttext .= '<li>'.&mt('IDs with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';
14511:                 } else {
14512:                     $resulttext .= '<li>'.&mt('There are now no ID formats restricted to verified users in the institutional directory.').'</li>';
14513:                 }
14514:             }
14515:             my %authname = &authtype_names();
14516:             my %context_title = &context_names();
14517:             if (ref($changes{'authtypes'}) eq 'ARRAY') {
14518:                 my $chgtext = '<ul>';
14519:                 foreach my $type (@{$changes{'authtypes'}}) {
14520:                     my @allowed;
14521:                     $chgtext .= '<li><span class="LC_cusr_emph">'.$context_title{$type}.'</span> - '.&mt('assignable authentication types: ');
14522:                     foreach my $auth (@authtypes) {
14523:                         if ($authhash{$type}{$auth}) {
14524:                             push(@allowed,$authname{$auth});
14525:                         }
14526:                     }
14527:                     if (@allowed > 0) {
14528:                         $chgtext .= join(', ',@allowed).'</li>';
14529:                     } else {
14530:                         $chgtext .= &mt('none').'</li>';
14531:                     }
14532:                 }
14533:                 $chgtext .= '</ul>';
14534:                 $resulttext .= '<li>'.&mt('Authentication types available for assignment to new users').'<br />'.$chgtext;
14535:                 $resulttext .= '</li>';
14536:             }
14537:             $resulttext .= '</ul>';
14538:         } else {
14539:             $resulttext = &mt('No changes made to user creation settings');
14540:         }
14541:     } else {
14542:         $resulttext = '<span class="LC_error">'.
14543:             &mt('An error occurred: [_1]',$putresult).'</span>';
14544:     }
14545:     if ($warningmsg ne '') {
14546:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
14547:     }
14548:     return $resulttext;
14549: }
14550: 
14551: sub modify_selfcreation {
14552:     my ($dom,$lastactref,%domconfig) = @_;
14553:     my ($resulttext,$warningmsg,%curr_usercreation,%curr_usermodify,%curr_inststatus,%changes,%cancreate);
14554:     my (%save_usercreate,%save_usermodify,%save_inststatus,@types,%usertypes);
14555:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
14556:     my ($othertitle,$usertypesref,$typesref) = &Apache::loncommon::sorted_inst_types($dom);
14557:     if (ref($typesref) eq 'ARRAY') {
14558:         @types = @{$typesref};
14559:     }
14560:     if (ref($usertypesref) eq 'HASH') {
14561:         %usertypes = %{$usertypesref};
14562:     }
14563:     $usertypes{'default'} = $othertitle;
14564: #
14565: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usercreation'}.
14566: #
14567:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
14568:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
14569:             if ($key eq 'cancreate') {
14570:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
14571:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
14572:                         if (($item eq 'selfcreate') || ($item eq 'statustocreate') ||
14573:                             ($item eq 'captcha') || ($item eq 'recaptchakeys') ||
14574:                             ($item eq 'recaptchaversion') || ($item eq 'notify') ||
14575:                             ($item eq 'emailusername') || ($item eq 'shibenv') ||
14576:                             ($item eq 'selfcreateprocessing') || ($item eq 'emailverified') ||
14577:                             ($item eq 'emailoptions') || ($item eq 'emaildomain')) {
14578:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
14579:                         } else {
14580:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
14581:                         }
14582:                     }
14583:                 }
14584:             } elsif ($key eq 'email_rule') {
14585:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
14586:             } else {
14587:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
14588:             }
14589:         }
14590:     }
14591: #
14592: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usermodification'}.
14593: #
14594:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
14595:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
14596:             if ($key eq 'selfcreate') {
14597:                 $curr_usermodify{$key} = $domconfig{'usermodification'}{$key};
14598:             } else {
14599:                 $save_usermodify{$key} = $domconfig{'usermodification'}{$key};
14600:             }
14601:         }
14602:     }
14603: #
14604: # Retrieve current domain configuration for institutional status types from $domconfig{'inststatus'}.
14605: #
14606:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
14607:         foreach my $key (keys(%{$domconfig{'inststatus'}})) {
14608:             if ($key eq 'inststatusguest') {
14609:                 $curr_inststatus{$key} = $domconfig{'inststatus'}{$key};
14610:             } else {
14611:                 $save_inststatus{$key} = $domconfig{'inststatus'}{$key};
14612:             }
14613:         }
14614:     }
14615: 
14616:     my @contexts = ('selfcreate');
14617:     @{$cancreate{'selfcreate'}} = ();
14618:     %{$cancreate{'emailusername'}} = ();
14619:     if (@types) {
14620:         @{$cancreate{'statustocreate'}} = ();
14621:     }
14622:     %{$cancreate{'selfcreateprocessing'}} = ();
14623:     %{$cancreate{'shibenv'}} = ();
14624:     %{$cancreate{'emailverified'}} = ();
14625:     %{$cancreate{'emailoptions'}} = ();
14626:     %{$cancreate{'emaildomain'}} = ();
14627:     my %selfcreatetypes = (
14628:                              sso   => 'users authenticated by institutional single sign on',
14629:                              login => 'users authenticated by institutional log-in',
14630:                              email => 'users verified by e-mail',
14631:                           );
14632: #
14633: # Populate $cancreate{'selfcreate'} array reference with types of user, for which self-creation of user accounts
14634: # is permitted.
14635: #
14636: 
14637:     my ($emailrules,$emailruleorder) = &Apache::lonnet::inst_userrules($dom,'email');
14638: 
14639:     my (@statuses,%email_rule);
14640:     foreach my $item ('login','sso','email') {
14641:         if ($item eq 'email') {
14642:             if ($env{'form.cancreate_email'}) {
14643:                 if (@types) {
14644:                     my @poss_statuses = &Apache::loncommon::get_env_multiple('form.selfassign');
14645:                     foreach my $status (@poss_statuses) {
14646:                         if (grep(/^\Q$status\E$/,(@types,'default'))) {
14647:                             push(@statuses,$status);
14648:                         }
14649:                     }
14650:                     $save_inststatus{'inststatusguest'} = \@statuses;
14651:                 } else {
14652:                     push(@statuses,'default');
14653:                 }
14654:                 if (@statuses) {
14655:                     my %curr_rule;
14656:                     if (ref($curr_usercreation{'email_rule'}) eq 'ARRAY') {
14657:                         foreach my $type (@statuses) {
14658:                             $curr_rule{$type} = $curr_usercreation{'email_rule'};
14659:                         }
14660:                     } elsif (ref($curr_usercreation{'email_rule'}) eq 'HASH') {
14661:                         foreach my $type (@statuses) {
14662:                             $curr_rule{$type} = $curr_usercreation{'email_rule'}{$type};
14663:                         }
14664:                     }
14665:                     push(@{$cancreate{'selfcreate'}},'email');
14666:                     push(@contexts,('selfcreateprocessing','emailverified','emailoptions'));
14667:                     my %curremaildom;
14668:                     if (ref($curr_usercreation{'cancreate'}{'emaildomain'}) eq 'HASH') {
14669:                         %curremaildom = %{$curr_usercreation{'cancreate'}{'emaildomain'}};
14670:                     }
14671:                     foreach my $type (@statuses) {
14672:                         if ($env{'form.cancreate_emailprocess_'.$type} =~ /^(?:approval|automatic)$/) {
14673:                             $cancreate{'selfcreateprocessing'}{$type} = $env{'form.cancreate_emailprocess_'.$type};
14674:                         }
14675:                         if ($env{'form.cancreate_usernameoptions_'.$type} =~ /^(?:all|first|free)$/) {
14676:                             $cancreate{'emailverified'}{$type} = $env{'form.cancreate_usernameoptions_'.$type};
14677:                         }
14678:                         if ($env{'form.cancreate_emailoptions_'.$type} =~ /^(any|inst|noninst|custom)$/) {
14679: #
14680: # Retrieve rules (if any) governing types of e-mail address which may be used to verify a username.
14681: #
14682:                             my $chosen = $1;
14683:                             if (($chosen eq 'inst') || ($chosen eq 'noninst')) {
14684:                                 my $emaildom;
14685:                                 if ($env{'form.cancreate_emaildomain_'.$chosen.'_'.$type} =~ /^\@[^\@]+$/) {
14686:                                     $emaildom = $env{'form.cancreate_emaildomain_'.$chosen.'_'.$type};
14687:                                     $cancreate{'emaildomain'}{$type}{$chosen} = $emaildom;
14688:                                     if (ref($curremaildom{$type}) eq 'HASH') {
14689:                                         if (exists($curremaildom{$type}{$chosen})) {
14690:                                             if ($curremaildom{$type}{$chosen} ne $emaildom) {
14691:                                                 push(@{$changes{'cancreate'}},'emaildomain');
14692:                                             }
14693:                                         } elsif ($emaildom ne '') {
14694:                                             push(@{$changes{'cancreate'}},'emaildomain');
14695:                                         }
14696:                                     } elsif ($emaildom ne '') {
14697:                                         push(@{$changes{'cancreate'}},'emaildomain');
14698:                                     }
14699:                                 }
14700:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
14701:                             } elsif ($chosen eq 'custom') {
14702:                                 my @possemail_rules = &Apache::loncommon::get_env_multiple('form.email_rule_'.$type);
14703:                                 $email_rule{$type} = [];
14704:                                 if (ref($emailrules) eq 'HASH') {
14705:                                     foreach my $rule (@possemail_rules) {
14706:                                         if (exists($emailrules->{$rule})) {
14707:                                             push(@{$email_rule{$type}},$rule);
14708:                                         }
14709:                                     }
14710:                                 }
14711:                                 if (@{$email_rule{$type}}) {
14712:                                     $cancreate{'emailoptions'}{$type} = 'custom';
14713:                                     if (ref($curr_rule{$type}) eq 'ARRAY') {
14714:                                         if (@{$curr_rule{$type}} > 0) {
14715:                                             foreach my $rule (@{$curr_rule{$type}}) {
14716:                                                 if (!grep(/^\Q$rule\E$/,@{$email_rule{$type}})) {
14717:                                                     push(@{$changes{'email_rule'}},$type);
14718:                                                 }
14719:                                             }
14720:                                         }
14721:                                         foreach my $type (@{$email_rule{$type}}) {
14722:                                             if (!grep(/^\Q$type\E$/,@{$curr_rule{$type}})) {
14723:                                                 push(@{$changes{'email_rule'}},$type);
14724:                                             }
14725:                                         }
14726:                                     } else {
14727:                                         push(@{$changes{'email_rule'}},$type);
14728:                                     }
14729:                                 }
14730:                             } else {
14731:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
14732:                             }
14733:                         }
14734:                     }
14735:                     if (@types) {
14736:                         if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
14737:                             my @changed = &Apache::loncommon::compare_arrays(\@statuses,$curr_inststatus{'inststatusguest'});
14738:                             if (@changed) {
14739:                                 push(@{$changes{'inststatus'}},'inststatusguest');
14740:                             }
14741:                         } else {
14742:                             push(@{$changes{'inststatus'}},'inststatusguest');
14743:                         }
14744:                     }
14745:                 } else {
14746:                     delete($env{'form.cancreate_email'});
14747:                     if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
14748:                         if (@{$curr_inststatus{'inststatusguest'}} > 0) {
14749:                             push(@{$changes{'inststatus'}},'inststatusguest');
14750:                         }
14751:                     }
14752:                 }
14753:             } else {
14754:                 $save_inststatus{'inststatusguest'} = [];
14755:                 if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
14756:                     if (@{$curr_inststatus{'inststatusguest'}} > 0) {
14757:                         push(@{$changes{'inststatus'}},'inststatusguest');
14758:                     }
14759:                 }
14760:             }
14761:         } else {
14762:             if ($env{'form.cancreate_'.$item}) {
14763:                 push(@{$cancreate{'selfcreate'}},$item);
14764:             }
14765:         }
14766:     }
14767:     my (%userinfo,%savecaptcha);
14768:     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
14769: #
14770: # Populate $cancreate{'emailusername'}{$type} hash ref with information fields (if new user will provide data
14771: # value set to one), if self-creation with e-mail address permitted, where $type is user type: faculty, staff, student etc.
14772: #
14773: 
14774:     if ($env{'form.cancreate_email'}) {
14775:         push(@contexts,'emailusername');
14776:         if (@statuses) {
14777:             foreach my $type (@statuses) {
14778:                 if (ref($infofields) eq 'ARRAY') {
14779:                     foreach my $field (@{$infofields}) {
14780:                         if ($env{'form.canmodify_emailusername_'.$type.'_'.$field} =~ /^(required|optional)$/) {
14781:                             $cancreate{'emailusername'}{$type}{$field} = $1;
14782:                         }
14783:                     }
14784:                 }
14785:             }
14786:         }
14787: #
14788: # Populate $cancreate{'notify'} hash ref with names of Domain Coordinators who are to be notified of
14789: # queued requests for self-creation of account verified by e-mail.
14790: #
14791: 
14792:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.selfcreationnotifyapproval');
14793:         @approvalnotify = sort(@approvalnotify);
14794:         $cancreate{'notify'}{'approval'} = join(',',@approvalnotify);
14795:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
14796:             if (ref($curr_usercreation{'cancreate'}{'notify'}) eq 'HASH') {
14797:                 if ($curr_usercreation{'cancreate'}{'notify'}{'approval'} ne $cancreate{'notify'}{'approval'}) {
14798:                     push(@{$changes{'cancreate'}},'notify');
14799:                 }
14800:             } else {
14801:                 if ($cancreate{'notify'}{'approval'}) {
14802:                     push(@{$changes{'cancreate'}},'notify');
14803:                 }
14804:             }
14805:         } elsif ($cancreate{'notify'}{'approval'}) {
14806:             push(@{$changes{'cancreate'}},'notify');
14807:         }
14808: 
14809:         &process_captcha('cancreate',\%changes,\%savecaptcha,$curr_usercreation{'cancreate'});
14810:     }
14811: #  
14812: # Check if domain default is set appropriately, if self-creation of accounts is to be available for
14813: # institutional log-in.
14814: #
14815:     if (grep(/^login$/,@{$cancreate{'selfcreate'}})) {
14816:         if (!((($domdefaults{'auth_def'} =~/^krb/) && ($domdefaults{'auth_arg_def'} ne '')) || 
14817:                ($domdefaults{'auth_def'} eq 'localauth'))) {
14818:             $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.').' '.
14819:                           &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.');
14820:         }
14821:     }
14822:     my @fields = ('lastname','firstname','middlename','generation',
14823:                   'permanentemail','id');
14824:     my @shibfields = (@fields,'inststatus');
14825:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
14826: #
14827: # Where usernames may created for institutional log-in and/or institutional single sign on:
14828: # (a) populate $cancreate{'statustocreate'} array reference with institutional status types who
14829: # may self-create accounts 
14830: # (b) populate $save_usermodify{'selfcreate'} hash reference with status types, and information fields
14831: # which the user may supply, if institutional data is unavailable.
14832: #
14833:     if (($env{'form.cancreate_login'}) || ($env{'form.cancreate_sso'})) {
14834:         if (@types) {
14835:             @{$cancreate{'statustocreate'}} = &Apache::loncommon::get_env_multiple('form.statustocreate');
14836:             push(@contexts,'statustocreate');
14837:             foreach my $type (@types) {
14838:                 my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$type);
14839:                 foreach my $field (@fields) {
14840:                     if (grep(/^\Q$field\E$/,@modifiable)) {
14841:                         $save_usermodify{'selfcreate'}{$type}{$field} = 1;
14842:                     } else {
14843:                         $save_usermodify{'selfcreate'}{$type}{$field} = 0;
14844:                     }
14845:                 }
14846:             }
14847:             if (ref($curr_usermodify{'selfcreate'}) eq 'HASH') {
14848:                 foreach my $type (@types) {
14849:                     if (ref($curr_usermodify{'selfcreate'}{$type}) eq 'HASH') {
14850:                         foreach my $field (@fields) {
14851:                             if ($save_usermodify{'selfcreate'}{$type}{$field} ne
14852:                                 $curr_usermodify{'selfcreate'}{$type}{$field}) {
14853:                                 push(@{$changes{'selfcreate'}},$type);
14854:                                 last;
14855:                             }
14856:                         }
14857:                     }
14858:                 }
14859:             } else {
14860:                 foreach my $type (@types) {
14861:                     push(@{$changes{'selfcreate'}},$type);
14862:                 }
14863:             }
14864:         }
14865:         foreach my $field (@shibfields) {
14866:             if ($env{'form.shibenv_'.$field} ne '') {
14867:                 $cancreate{'shibenv'}{$field} = $env{'form.shibenv_'.$field};
14868:             }
14869:         }
14870:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
14871:             if (ref($curr_usercreation{'cancreate'}{'shibenv'}) eq 'HASH') {
14872:                 foreach my $field (@shibfields) {
14873:                     if ($env{'form.shibenv_'.$field} ne $curr_usercreation{'cancreate'}{'shibenv'}{$field}) {
14874:                         push(@{$changes{'cancreate'}},'shibenv');
14875:                     }
14876:                 }
14877:             } else {
14878:                 foreach my $field (@shibfields) {
14879:                     if ($env{'form.shibenv_'.$field}) {
14880:                         push(@{$changes{'cancreate'}},'shibenv');
14881:                         last;
14882:                     }
14883:                 }
14884:             }
14885:         }
14886:     }
14887:     foreach my $item (@contexts) {
14888:         if (ref($curr_usercreation{'cancreate'}{$item}) eq 'ARRAY') {
14889:             foreach my $curr (@{$curr_usercreation{'cancreate'}{$item}}) {
14890:                 if (ref($cancreate{$item}) eq 'ARRAY') {
14891:                     if (!grep(/^$curr$/,@{$cancreate{$item}})) {
14892:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
14893:                             push(@{$changes{'cancreate'}},$item);
14894:                         }
14895:                     }
14896:                 }
14897:             }
14898:             if (ref($cancreate{$item}) eq 'ARRAY') {
14899:                 foreach my $type (@{$cancreate{$item}}) {
14900:                     if (!grep(/^$type$/,@{$curr_usercreation{'cancreate'}{$item}})) {
14901:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
14902:                             push(@{$changes{'cancreate'}},$item);
14903:                         }
14904:                     }
14905:                 }
14906:             }
14907:         } elsif (ref($curr_usercreation{'cancreate'}{$item}) eq 'HASH') {
14908:             if (ref($cancreate{$item}) eq 'HASH') {
14909:                 foreach my $type (keys(%{$curr_usercreation{'cancreate'}{$item}})) {
14910:                     if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
14911:                         foreach my $field (keys(%{$curr_usercreation{'cancreate'}{$item}{$type}})) {
14912:                             unless ($curr_usercreation{'cancreate'}{$item}{$type}{$field} eq $cancreate{$item}{$type}{$field}) {
14913:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
14914:                                     push(@{$changes{'cancreate'}},$item);
14915:                                 }
14916:                             }
14917:                         }
14918:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
14919:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
14920:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
14921:                                 push(@{$changes{'cancreate'}},$item);
14922:                             }
14923:                         }
14924:                     }
14925:                 }
14926:                 foreach my $type (keys(%{$cancreate{$item}})) {
14927:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
14928:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
14929:                             if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
14930:                                 unless ($curr_usercreation{'cancreate'}{$item}{$type}{$field} eq $cancreate{$item}{$type}{$field}) {
14931:                                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
14932:                                         push(@{$changes{'cancreate'}},$item);
14933:                                     }
14934:                                 }
14935:                             } else {
14936:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
14937:                                     push(@{$changes{'cancreate'}},$item);
14938:                                 }
14939:                             }
14940:                         }
14941:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
14942:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
14943:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
14944:                                 push(@{$changes{'cancreate'}},$item);
14945:                             }
14946:                         }
14947:                     }
14948:                 }
14949:             }
14950:         } elsif ($curr_usercreation{'cancreate'}{$item}) {
14951:             if (ref($cancreate{$item}) eq 'ARRAY') {
14952:                 if (!grep(/^\Q$curr_usercreation{'cancreate'}{$item}\E$/,@{$cancreate{$item}})) {
14953:                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
14954:                         push(@{$changes{'cancreate'}},$item);
14955:                     }
14956:                 }
14957:             }
14958:         } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
14959:             if (ref($cancreate{$item}) eq 'HASH') {
14960:                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
14961:                     push(@{$changes{'cancreate'}},$item);
14962:                 }
14963:             }
14964:         } elsif ($item eq 'emailusername') {
14965:             if (ref($cancreate{$item}) eq 'HASH') {
14966:                 foreach my $type (keys(%{$cancreate{$item}})) {
14967:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
14968:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
14969:                             if ($cancreate{$item}{$type}{$field}) {
14970:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
14971:                                     push(@{$changes{'cancreate'}},$item);
14972:                                 }
14973:                                 last;
14974:                             }
14975:                         }
14976:                     }
14977:                 }
14978:             }
14979:         }
14980:     }
14981: #
14982: # Populate %save_usercreate hash with updates to self-creation configuration.
14983: #
14984:     $save_usercreate{'cancreate'}{'captcha'} = $savecaptcha{'captcha'};
14985:     $save_usercreate{'cancreate'}{'recaptchakeys'} = $savecaptcha{'recaptchakeys'};
14986:     $save_usercreate{'cancreate'}{'recaptchaversion'} = $savecaptcha{'recaptchaversion'};
14987:     $save_usercreate{'cancreate'}{'selfcreate'} = $cancreate{'selfcreate'};
14988:     if (ref($cancreate{'notify'}) eq 'HASH') {
14989:         $save_usercreate{'cancreate'}{'notify'} = $cancreate{'notify'};
14990:     }
14991:     if (ref($cancreate{'selfcreateprocessing'}) eq 'HASH') {
14992:         $save_usercreate{'cancreate'}{'selfcreateprocessing'} = $cancreate{'selfcreateprocessing'};
14993:     }
14994:     if (ref($cancreate{'emailverified'}) eq 'HASH') {
14995:         $save_usercreate{'cancreate'}{'emailverified'} = $cancreate{'emailverified'};
14996:     }
14997:     if (ref($cancreate{'emailoptions'}) eq 'HASH') {
14998:         $save_usercreate{'cancreate'}{'emailoptions'} = $cancreate{'emailoptions'};
14999:     }
15000:     if (ref($cancreate{'emaildomain'}) eq 'HASH') {
15001:         $save_usercreate{'cancreate'}{'emaildomain'} = $cancreate{'emaildomain'};
15002:     }
15003:     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
15004:         $save_usercreate{'cancreate'}{'statustocreate'} = $cancreate{'statustocreate'};
15005:     }
15006:     if (ref($cancreate{'shibenv'}) eq 'HASH') {
15007:         $save_usercreate{'cancreate'}{'shibenv'} = $cancreate{'shibenv'};
15008:     }
15009:     $save_usercreate{'cancreate'}{'emailusername'} = $cancreate{'emailusername'};
15010:     $save_usercreate{'email_rule'} = \%email_rule;
15011: 
15012:     my %userconfig_hash = (
15013:             usercreation     => \%save_usercreate,
15014:             usermodification => \%save_usermodify,
15015:             inststatus       => \%save_inststatus,
15016:     );
15017: 
15018:     my $putresult = &Apache::lonnet::put_dom('configuration',\%userconfig_hash,
15019:                                              $dom);
15020: #
15021: # Accumulate details of changes to domain configuration for self-creation of usernames in $resulttext
15022: #
15023:     if ($putresult eq 'ok') {
15024:         if (keys(%changes) > 0) {
15025:             $resulttext = &mt('Changes made:').'<ul>';
15026:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
15027:                 my %lt = &selfcreation_types();
15028:                 foreach my $type (@{$changes{'cancreate'}}) {
15029:                     my $chgtext = '';
15030:                     if ($type eq 'selfcreate') {
15031:                         if (@{$cancreate{$type}} == 0) {
15032:                             $chgtext .= &mt('Self creation of a new user account is not permitted.');
15033:                         } else {
15034:                             $chgtext .= &mt('Self-creation of a new account is permitted for:').
15035:                                         '<ul>';
15036:                             foreach my $case (@{$cancreate{$type}}) {
15037:                                 $chgtext .= '<li>'.$selfcreatetypes{$case}.'</li>';
15038:                             }
15039:                             $chgtext .= '</ul>';
15040:                             if (ref($cancreate{$type}) eq 'ARRAY') {
15041:                                 if (grep(/^(login|sso)$/,@{$cancreate{$type}})) {
15042:                                     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
15043:                                         if (@{$cancreate{'statustocreate'}} == 0) {
15044:                                             $chgtext .= '<span class="LC_warning">'.
15045:                                                         &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts via log-in or single sign-on.").
15046:                                                         '</span><br />';
15047:                                         }
15048:                                     }
15049:                                 }
15050:                                 if (grep(/^email$/,@{$cancreate{$type}})) {
15051:                                     if (!@statuses) {
15052:                                         $chgtext .= '<span class="LC_warning">'.
15053:                                                     &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.").
15054:                                                     '</span><br />';
15055: 
15056:                                     }
15057:                                 }
15058:                             }
15059:                         }
15060:                     } elsif ($type eq 'shibenv') {
15061:                         if (keys(%{$cancreate{$type}}) == 0) {
15062:                             $chgtext .= &mt('Shibboleth-autheticated user does not use environment variables to set user information').'<br />'; 
15063:                         } else {
15064:                             $chgtext .= &mt('Shibboleth-autheticated user information set from environment variables, as follows:').
15065:                                         '<ul>';
15066:                             foreach my $field (@shibfields) {
15067:                                 next if ($cancreate{$type}{$field} eq '');
15068:                                 if ($field eq 'inststatus') {
15069:                                     $chgtext .= '<li>'.&mt('Institutional status').' -- '.$cancreate{$type}{$field}.'</li>';
15070:                                 } else {
15071:                                     $chgtext .= '<li>'.$fieldtitles{$field}.' -- '.$cancreate{$type}{$field}.'</li>';
15072:                                 }
15073:                             }
15074:                             $chgtext .= '</ul>';
15075:                         }
15076:                     } elsif ($type eq 'statustocreate') {
15077:                         if ((ref($cancreate{'selfcreate'}) eq 'ARRAY') &&
15078:                             (ref($cancreate{'statustocreate'}) eq 'ARRAY')) {
15079:                             if (@{$cancreate{'selfcreate'}} > 0) {
15080:                                 if (@{$cancreate{'statustocreate'}} == 0) {
15081:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts set to 'None'.");
15082:                                     if (!grep(/^email$/,@{$cancreate{'selfcreate'}})) {
15083:                                         $chgtext .= '<br />'.
15084:                                                     '<span class="LC_warning">'.
15085:                                                     &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts.").
15086:                                                     '</span>';
15087:                                     }
15088:                                 } elsif (keys(%usertypes) > 0) {
15089:                                     if (grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
15090:                                         $chgtext .= &mt('Creation of a new account for an institutional user is restricted to the following institutional affiliation(s):');
15091:                                     } else {
15092:                                         $chgtext .= &mt('Institutional affiliations permitted to create accounts with institutional authentication were set as follows:');
15093:                                     }
15094:                                     $chgtext .= '<ul>';
15095:                                     foreach my $case (@{$cancreate{$type}}) {
15096:                                         if ($case eq 'default') {
15097:                                             $chgtext .= '<li>'.$othertitle.'</li>';
15098:                                         } else {
15099:                                             $chgtext .= '<li>'.$usertypes{$case}.'</li>';
15100:                                         }
15101:                                     }
15102:                                     $chgtext .= '</ul>';
15103:                                     if (!grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
15104:                                         $chgtext .= '<span class="LC_warning">'.
15105:                                                     &mt('However, users authenticated by institutional login/single sign on are not currently permitted to create accounts.').
15106:                                                     '</span>';
15107:                                     }
15108:                                 }
15109:                             } else {
15110:                                 if (@{$cancreate{$type}} == 0) {
15111:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts were set to 'none'.");
15112:                                 } else {
15113:                                     $chgtext .= &mt('Although institutional affiliations permitted to create accounts were changed, self creation of accounts is not currently permitted for any authentication types.');
15114:                                 }
15115:                             }
15116:                             $chgtext .= '<br />';
15117:                         }
15118:                     } elsif ($type eq 'selfcreateprocessing') {
15119:                         my %choices = &Apache::lonlocal::texthash (
15120:                                                                     automatic => 'Automatic approval',
15121:                                                                     approval  => 'Queued for approval',
15122:                                                                   );
15123:                         if (@types) {
15124:                             if (@statuses) {
15125:                                 $chgtext .= &mt('Processing of requests to create account with e-mail verification set as follows:').
15126:                                             '<ul>';
15127:                                 foreach my $status (@statuses) {
15128:                                     if ($status eq 'default') {
15129:                                         $chgtext .= '<li>'.$othertitle.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
15130:                                     } else {
15131:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
15132:                                     }
15133:                                 }
15134:                                 $chgtext .= '</ul>';
15135:                             }
15136:                         } else {
15137:                             $chgtext .= &mt('Processing of requests to create account with e-mail verification set to: "[_1]"',
15138:                                             $choices{$cancreate{'selfcreateprocessing'}{'default'}});
15139:                         }
15140:                     } elsif ($type eq 'emailverified') {
15141:                         my %options = &Apache::lonlocal::texthash (
15142:                                                                     all   => 'Same as e-mail',
15143:                                                                     first => 'Omit @domain',
15144:                                                                     free  => 'Free to choose',
15145:                                                                   );
15146:                         if (@types) {
15147:                             if (@statuses) {
15148:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, username is set as follows:').
15149:                                             '<ul>';
15150:                                 foreach my $status (@statuses) {
15151:                                     if ($status eq 'default') {
15152:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
15153:                                     } else {
15154:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
15155:                                     }
15156:                                 }
15157:                                 $chgtext .= '</ul>';
15158:                             }
15159:                         } else {
15160:                             $chgtext .= &mt("For self-created accounts verified by e-mail address, user's username is: '[_1]'",
15161:                                             $options{$cancreate{'emailverified'}{'default'}});
15162:                         }
15163:                     } elsif ($type eq 'emailoptions') {
15164:                         my %options = &Apache::lonlocal::texthash (
15165:                                                                     any     => 'Any e-mail',
15166:                                                                     inst    => 'Institutional only',
15167:                                                                     noninst => 'Non-institutional only',
15168:                                                                     custom  => 'Custom restrictions',
15169:                                                                   );
15170:                         if (@types) {
15171:                             if (@statuses) {
15172:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, requirements for e-mail address are as follows:').
15173:                                             '<ul>';
15174:                                 foreach my $status (@statuses) {
15175:                                     if ($type eq 'default') {
15176:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
15177:                                     } else {
15178:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
15179:                                     }
15180:                                 }
15181:                                 $chgtext .= '</ul>';
15182:                             }
15183:                         } else {
15184:                             if ($cancreate{'emailoptions'}{'default'} eq 'any') {
15185:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, any e-mail may be used');
15186:                             } else {
15187:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, e-mail restricted to: "[_1]"',
15188:                                                 $options{$cancreate{'emailoptions'}{'default'}});
15189:                             }
15190:                         }
15191:                     } elsif ($type eq 'emaildomain') {
15192:                         my $output;
15193:                         if (@statuses) {
15194:                             foreach my $type (@statuses) {
15195:                                 if (ref($cancreate{'emaildomain'}{$type}) eq 'HASH') {
15196:                                     if ($cancreate{'emailoptions'}{$type} eq 'inst') {
15197:                                         if ($type eq 'default') {
15198:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
15199:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} eq '')) {
15200:                                                 $output = '<li>'.$othertitle.' -- '.&mt('No restriction on e-mail domain').'</li>';
15201:                                             } else {
15202:                                                 $output = '<li>'.$othertitle.' -- '.&mt("User's e-mail address needs to end: [_1]",
15203:                                                                                         $cancreate{'emaildomain'}{$type}{'inst'}).'</li>';
15204:                                             }
15205:                                         } else {
15206:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
15207:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} eq '')) {
15208:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
15209:                                             } else {
15210:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address needs to end: [_1]",
15211:                                                                                               $cancreate{'emaildomain'}{$type}{'inst'}).'</li>';
15212:                                             }
15213:                                         }
15214:                                     } elsif ($cancreate{'emailoptions'}{$type} eq 'noninst') {
15215:                                         if ($type eq 'default') {
15216:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
15217:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
15218:                                                 $output = '<li>'.$othertitle.' -- '.&mt('No restriction on e-mail domain').'</li>';
15219:                                             } else {
15220:                                                 $output = '<li>'.$othertitle.' -- '.&mt("User's e-mail address must not end: [_1]",
15221:                                                                                         $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';
15222:                                             }
15223:                                         } else {
15224:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
15225:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
15226:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
15227:                                             } else {
15228:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address must not end: [_1]",
15229:                                                                                                 $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';
15230:                                             }
15231:                                         }
15232:                                     }
15233:                                 }
15234:                             }
15235:                         }
15236:                         if ($output ne '') {
15237:                             $chgtext .= &mt('For self-created accounts verified by e-mail address:').
15238:                                         '<ul>'.$output.'</ul>';
15239:                         }
15240:                     } elsif ($type eq 'captcha') {
15241:                         if ($savecaptcha{$type} eq 'notused') {
15242:                             $chgtext .= &mt('No CAPTCHA validation in use for self-creation screen.');
15243:                         } else {
15244:                             my %captchas = &captcha_phrases();
15245:                             if ($captchas{$savecaptcha{$type}}) {
15246:                                 $chgtext .= &mt("Validation for self-creation screen set to $captchas{$savecaptcha{$type}}.");
15247:                             } else {
15248:                                 $chgtext .= &mt('Validation for self-creation screen set to unknown type.');
15249:                             }
15250:                         }
15251:                     } elsif ($type eq 'recaptchakeys') {
15252:                         my ($privkey,$pubkey);
15253:                         if (ref($savecaptcha{$type}) eq 'HASH') {
15254:                             $pubkey = $savecaptcha{$type}{'public'};
15255:                             $privkey = $savecaptcha{$type}{'private'};
15256:                         }
15257:                         $chgtext .= &mt('ReCAPTCHA keys changes').'<ul>';
15258:                         if (!$pubkey) {
15259:                             $chgtext .= '<li>'.&mt('Public key deleted').'</li>';
15260:                         } else {
15261:                             $chgtext .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
15262:                         }
15263:                         if (!$privkey) {
15264:                             $chgtext .= '<li>'.&mt('Private key deleted').'</li>';
15265:                         } else {
15266:                             $chgtext .= '<li>'.&mt('Private key set to [_1]',$pubkey).'</li>';
15267:                         }
15268:                         $chgtext .= '</ul>';
15269:                     } elsif ($type eq 'recaptchaversion') {
15270:                         if ($savecaptcha{'captcha'} eq 'recaptcha') {
15271:                             $chgtext .= &mt('ReCAPTCHA set to version [_1]',$savecaptcha{$type});
15272:                         }
15273:                     } elsif ($type eq 'emailusername') {
15274:                         if (ref($cancreate{'emailusername'}) eq 'HASH') {
15275:                             if (@statuses) {
15276:                                 foreach my $type (@statuses) {
15277:                                     if (ref($cancreate{'emailusername'}{$type}) eq 'HASH') {
15278:                                         if (keys(%{$cancreate{'emailusername'}{$type}}) > 0) {
15279:                                             $chgtext .= &mt('When self-creating account with e-mail verification, the following information will be provided by [_1]:',"'$usertypes{$type}'").
15280:                                                     '<ul>';
15281:                                             foreach my $field (@{$infofields}) {
15282:                                                 if ($cancreate{'emailusername'}{$type}{$field}) {
15283:                                                     $chgtext .= '<li>'.$infotitles->{$field}.'</li>';
15284:                                                 }
15285:                                             }
15286:                                             $chgtext .= '</ul>';
15287:                                         } else {
15288:                                             $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
15289:                                         }
15290:                                     } else {
15291:                                         $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
15292:                                     }
15293:                                 }
15294:                             }
15295:                         }
15296:                     } elsif ($type eq 'notify') {
15297:                         my $numapprove = 0;
15298:                         if (ref($changes{'cancreate'}) eq 'ARRAY') {
15299:                             if ((grep(/^notify$/,@{$changes{'cancreate'}})) && (ref($cancreate{'notify'}) eq 'HASH')) {
15300:                                 if ($cancreate{'notify'}{'approval'}) {
15301:                                     $chgtext .= &mt('Notification of username requests requiring approval will be sent to: ').$cancreate{'notify'}{'approval'};
15302:                                     $numapprove ++;
15303:                                 }
15304:                             }
15305:                         }
15306:                         unless ($numapprove) {
15307:                             $chgtext .= &mt('No Domain Coordinators will receive notification of username requests requiring approval.');
15308:                         }
15309:                     }
15310:                     if ($chgtext) {
15311:                         $resulttext .= '<li>'.$chgtext.'</li>';
15312:                     }
15313:                 }
15314:             }
15315:             if ((ref($changes{'email_rule'}) eq 'ARRAY') && (@{$changes{'email_rule'}} > 0)) {
15316:                 my ($emailrules,$emailruleorder) =
15317:                     &Apache::lonnet::inst_userrules($dom,'email');
15318:                 foreach my $type (@{$changes{'email_rule'}}) {
15319:                     if (ref($email_rule{$type}) eq 'ARRAY') {
15320:                         my $chgtext = '<ul>';
15321:                         foreach my $rule (@{$email_rule{$type}}) {
15322:                             if (ref($emailrules->{$rule}) eq 'HASH') {
15323:                                 $chgtext .= '<li>'.$emailrules->{$rule}{'name'}.'</li>';
15324:                             }
15325:                         }
15326:                         $chgtext .= '</ul>';
15327:                         my $typename;
15328:                         if (@types) {
15329:                             if ($type eq 'default') {
15330:                                 $typename = $othertitle;
15331:                             } else {
15332:                                 $typename = $usertypes{$type};
15333:                             }
15334:                             $chgtext .= &mt('(Affiliation: [_1])',$typename);
15335:                         }
15336:                         if (@{$email_rule{$type}} > 0) {
15337:                             $resulttext .= '<li>'.
15338:                                            &mt('Accounts may not be created by users verified by e-mail, for e-mail addresses of the following types: ',
15339:                                                $usertypes{$type}).
15340:                                            $chgtext.
15341:                                            '</li>';
15342:                         } else {
15343:                             $resulttext .= '<li>'.
15344:                                            &mt('There are now no restrictions on e-mail addresses which may be used for verification when a user requests an account.').
15345:                                            '</li>'.
15346:                                            &mt('(Affiliation: [_1])',$typename);
15347:                         }
15348:                     }
15349:                 }
15350:             }
15351:             if (ref($changes{'inststatus'}) eq 'ARRAY') {
15352:                 if (ref($save_inststatus{'inststatusguest'}) eq 'ARRAY') {
15353:                     if (@{$save_inststatus{'inststatusguest'}} > 0) {
15354:                         my $chgtext = '<ul>';
15355:                         foreach my $type (@{$save_inststatus{'inststatusguest'}}) {
15356:                             $chgtext .= '<li>'.$usertypes{$type}.'</li>';
15357:                         }
15358:                         $chgtext .= '</ul>';
15359:                         $resulttext .= '<li>'.
15360:                                        &mt('A user will self-report one of the following affiliations when requesting an account verified by e-mail: ').
15361:                                           $chgtext.
15362:                                        '</li>';
15363:                     } else {
15364:                         $resulttext .= '<li>'.
15365:                                        &mt('No affiliations available for self-reporting when requesting an account verified by e-mail.').
15366:                                        '</li>';
15367:                     }
15368:                 }
15369:             }
15370:             if (ref($changes{'selfcreate'}) eq 'ARRAY') {
15371:                 $resulttext .= '<li>'.&mt('When self-creating institutional account:').'<ul>';
15372:                 my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
15373:                 foreach my $type (@{$changes{'selfcreate'}}) {
15374:                     my $typename = $type;
15375:                     if (keys(%usertypes) > 0) {
15376:                         if ($usertypes{$type} ne '') {
15377:                             $typename = $usertypes{$type};
15378:                         }
15379:                     }
15380:                     my @modifiable;
15381:                     $resulttext .= '<li>'.
15382:                                     &mt('Self-creation of account by users with status: [_1]',
15383:                                         '<span class="LC_cusr_emph">'.$typename.'</span>').
15384:                                     ' - '.&mt('modifiable fields (if institutional data blank): ');
15385:                     foreach my $field (@fields) {
15386:                         if ($save_usermodify{'selfcreate'}{$type}{$field}) {
15387:                             push(@modifiable,'<b>'.$fieldtitles{$field}.'</b>');
15388:                         }
15389:                     }
15390:                     if (@modifiable > 0) {
15391:                         $resulttext .= join(', ',@modifiable);
15392:                     } else {
15393:                         $resulttext .= &mt('none');
15394:                     }
15395:                     $resulttext .= '</li>';
15396:                 }
15397:                 $resulttext .= '</ul></li>';
15398:             }
15399:             $resulttext .= '</ul>';
15400:             my $cachetime = 24*60*60;
15401:             $domdefaults{'inststatusguest'} = $save_inststatus{'inststatusguest'};
15402:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
15403:             if (ref($lastactref) eq 'HASH') {
15404:                 $lastactref->{'domdefaults'} = 1;
15405:             }
15406:         } else {
15407:             $resulttext = &mt('No changes made to self-creation settings');
15408:         }
15409:     } else {
15410:         $resulttext = '<span class="LC_error">'.
15411:             &mt('An error occurred: [_1]',$putresult).'</span>';
15412:     }
15413:     if ($warningmsg ne '') {
15414:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
15415:     }
15416:     return $resulttext;
15417: }
15418: 
15419: sub process_captcha {
15420:     my ($container,$changes,$newsettings,$currsettings) = @_;
15421:     return unless ((ref($changes) eq 'HASH') && (ref($newsettings) eq 'HASH'));
15422:     $newsettings->{'captcha'} = $env{'form.'.$container.'_captcha'};
15423:     unless ($newsettings->{'captcha'} eq 'recaptcha' || $newsettings->{'captcha'} eq 'notused') {
15424:         $newsettings->{'captcha'} = 'original';
15425:     }
15426:     my %current;
15427:     if (ref($currsettings) eq 'HASH') {
15428:         %current = %{$currsettings};
15429:     }
15430:     if ($current{'captcha'} ne $newsettings->{'captcha'}) {
15431:         if ($container eq 'cancreate') {
15432:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
15433:                 push(@{$changes->{'cancreate'}},'captcha');
15434:             } elsif (!defined($changes->{'cancreate'})) {
15435:                 $changes->{'cancreate'} = ['captcha'];
15436:             }
15437:         } elsif ($container eq 'passwords') {
15438:             $changes->{'reset'} = 1;
15439:         } else {
15440:             $changes->{'captcha'} = 1;
15441:         }
15442:     }
15443:     my ($newpub,$newpriv,$currpub,$currpriv,$newversion,$currversion);
15444:     if ($newsettings->{'captcha'} eq 'recaptcha') {
15445:         $newpub = $env{'form.'.$container.'_recaptchapub'};
15446:         $newpriv = $env{'form.'.$container.'_recaptchapriv'};
15447:         $newpub =~ s/[^\w\-]//g;
15448:         $newpriv =~ s/[^\w\-]//g;
15449:         $newsettings->{'recaptchakeys'} = {
15450:                                              public  => $newpub,
15451:                                              private => $newpriv,
15452:                                           };
15453:         $newversion = $env{'form.'.$container.'_recaptchaversion'};
15454:         $newversion =~ s/\D//g;
15455:         if ($newversion ne '2') {
15456:             $newversion = 1;
15457:         }
15458:         $newsettings->{'recaptchaversion'} = $newversion;
15459:     }
15460:     if (ref($current{'recaptchakeys'}) eq 'HASH') {
15461:         $currpub = $current{'recaptchakeys'}{'public'};
15462:         $currpriv = $current{'recaptchakeys'}{'private'};
15463:         unless ($newsettings->{'captcha'} eq 'recaptcha') {
15464:             $newsettings->{'recaptchakeys'} = {
15465:                                                  public  => '',
15466:                                                  private => '',
15467:                                               }
15468:         }
15469:     }
15470:     if ($current{'captcha'} eq 'recaptcha') {
15471:         $currversion = $current{'recaptchaversion'};
15472:         if ($currversion ne '2') {
15473:             $currversion = 1;
15474:         }
15475:     }
15476:     if ($currversion ne $newversion) {
15477:         if ($container eq 'cancreate') {
15478:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
15479:                 push(@{$changes->{'cancreate'}},'recaptchaversion');
15480:             } elsif (!defined($changes->{'cancreate'})) {
15481:                 $changes->{'cancreate'} = ['recaptchaversion'];
15482:             }
15483:         } elsif ($container eq 'passwords') {
15484:             $changes->{'reset'} = 1;
15485:         } else {
15486:             $changes->{'recaptchaversion'} = 1;
15487:         }
15488:     }
15489:     if (($newpub ne $currpub) || ($newpriv ne $currpriv)) {
15490:         if ($container eq 'cancreate') {
15491:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
15492:                 push(@{$changes->{'cancreate'}},'recaptchakeys');
15493:             } elsif (!defined($changes->{'cancreate'})) {
15494:                 $changes->{'cancreate'} = ['recaptchakeys'];
15495:             }
15496:         } elsif ($container eq 'passwords') {
15497:             $changes->{'reset'} = 1;
15498:         } else {
15499:             $changes->{'recaptchakeys'} = 1;
15500:         }
15501:     }
15502:     return;
15503: }
15504: 
15505: sub modify_usermodification {
15506:     my ($dom,%domconfig) = @_;
15507:     my ($resulttext,%curr_usermodification,%changes,%modifyhash);
15508:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
15509:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
15510:             if ($key eq 'selfcreate') {
15511:                 $modifyhash{$key} = $domconfig{'usermodification'}{$key};
15512:             } else {  
15513:                 $curr_usermodification{$key} = $domconfig{'usermodification'}{$key};
15514:             }
15515:         }
15516:     }
15517:     my @contexts = ('author','course');
15518:     my %context_title = (
15519:                            author => 'In author context',
15520:                            course => 'In course context',
15521:                         );
15522:     my @fields = ('lastname','firstname','middlename','generation',
15523:                   'permanentemail','id');
15524:     my %roles = (
15525:                   author => ['ca','aa'],
15526:                   course => ['st','ep','ta','in','cr'],
15527:                 );
15528:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
15529:     foreach my $context (@contexts) {
15530:         foreach my $role (@{$roles{$context}}) {
15531:             my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$role);
15532:             foreach my $item (@fields) {
15533:                 if (grep(/^\Q$item\E$/,@modifiable)) {
15534:                     $modifyhash{$context}{$role}{$item} = 1;
15535:                 } else {
15536:                     $modifyhash{$context}{$role}{$item} = 0;
15537:                 }
15538:             }
15539:         }
15540:         if (ref($curr_usermodification{$context}) eq 'HASH') {
15541:             foreach my $role (@{$roles{$context}}) {
15542:                 if (ref($curr_usermodification{$context}{$role}) eq 'HASH') {
15543:                     foreach my $field (@fields) {
15544:                         if ($modifyhash{$context}{$role}{$field} ne 
15545:                                 $curr_usermodification{$context}{$role}{$field}) {
15546:                             push(@{$changes{$context}},$role);
15547:                             last;
15548:                         }
15549:                     }
15550:                 }
15551:             }
15552:         } else {
15553:             foreach my $context (@contexts) {
15554:                 foreach my $role (@{$roles{$context}}) {
15555:                     push(@{$changes{$context}},$role);
15556:                 }
15557:             }
15558:         }
15559:     }
15560:     my %usermodification_hash =  (
15561:                                    usermodification => \%modifyhash,
15562:                                  );
15563:     my $putresult = &Apache::lonnet::put_dom('configuration',
15564:                                              \%usermodification_hash,$dom);
15565:     if ($putresult eq 'ok') {
15566:         if (keys(%changes) > 0) {
15567:             $resulttext = &mt('Changes made: ').'<ul>';
15568:             foreach my $context (@contexts) {
15569:                 if (ref($changes{$context}) eq 'ARRAY') {
15570:                     $resulttext .= '<li>'.$context_title{$context}.':<ul>';
15571:                     if (ref($changes{$context}) eq 'ARRAY') {
15572:                         foreach my $role (@{$changes{$context}}) {
15573:                             my $rolename;
15574:                             if ($role eq 'cr') {
15575:                                 $rolename = &mt('Custom');
15576:                             } else {
15577:                                 $rolename = &Apache::lonnet::plaintext($role);
15578:                             }
15579:                             my @modifiable;
15580:                             $resulttext .= '<li><span class="LC_cusr_emph">'.&mt('Target user with [_1] role',$rolename).'</span> - '.&mt('modifiable fields: ');
15581:                             foreach my $field (@fields) {
15582:                                 if ($modifyhash{$context}{$role}{$field}) {
15583:                                     push(@modifiable,$fieldtitles{$field});
15584:                                 }
15585:                             }
15586:                             if (@modifiable > 0) {
15587:                                 $resulttext .= join(', ',@modifiable);
15588:                             } else {
15589:                                 $resulttext .= &mt('none'); 
15590:                             }
15591:                             $resulttext .= '</li>';
15592:                         }
15593:                         $resulttext .= '</ul></li>';
15594:                     }
15595:                 }
15596:             }
15597:             $resulttext .= '</ul>';
15598:         } else {
15599:             $resulttext = &mt('No changes made to user modification settings');
15600:         }
15601:     } else {
15602:         $resulttext = '<span class="LC_error">'.
15603:             &mt('An error occurred: [_1]',$putresult).'</span>';
15604:     }
15605:     return $resulttext;
15606: }
15607: 
15608: sub modify_defaults {
15609:     my ($dom,$lastactref,%domconfig) = @_;
15610:     my ($resulttext,$mailmsgtxt,%newvalues,%changes,@errors);
15611:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
15612:     my @items = ('auth_def','auth_arg_def','lang_def','timezone_def','datelocale_def',
15613:                  'portal_def');
15614:     my @authtypes = ('internal','krb4','krb5','localauth');
15615:     foreach my $item (@items) {
15616:         $newvalues{$item} = $env{'form.'.$item};
15617:         if ($item eq 'auth_def') {
15618:             if ($newvalues{$item} ne '') {
15619:                 if (!grep(/^\Q$newvalues{$item}\E$/,@authtypes)) {
15620:                     push(@errors,$item);
15621:                 }
15622:             }
15623:         } elsif ($item eq 'lang_def') {
15624:             if ($newvalues{$item} ne '') {
15625:                 if ($newvalues{$item} =~ /^(\w+)/) {
15626:                     my $langcode = $1;
15627:                     if ($langcode ne 'x_chef') {
15628:                         if (code2language($langcode) eq '') {
15629:                             push(@errors,$item);
15630:                         }
15631:                     }
15632:                 } else {
15633:                     push(@errors,$item);
15634:                 }
15635:             }
15636:         } elsif ($item eq 'timezone_def') {
15637:             if ($newvalues{$item} ne '') {
15638:                 if (!DateTime::TimeZone->is_valid_name($newvalues{$item})) {
15639:                     push(@errors,$item);   
15640:                 }
15641:             }
15642:         } elsif ($item eq 'datelocale_def') {
15643:             if ($newvalues{$item} ne '') {
15644:                 my @datelocale_ids = DateTime::Locale->ids();
15645:                 if (!grep(/^\Q$newvalues{$item}\E$/,@datelocale_ids)) {
15646:                     push(@errors,$item);
15647:                 }
15648:             }
15649:         } elsif ($item eq 'portal_def') {
15650:             if ($newvalues{$item} ne '') {
15651:                 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])\/?$/) {
15652:                     push(@errors,$item);
15653:                 }
15654:             }
15655:         }
15656:         if (grep(/^\Q$item\E$/,@errors)) {
15657:             $newvalues{$item} = $domdefaults{$item};
15658:         } elsif ($domdefaults{$item} ne $newvalues{$item}) {
15659:             $changes{$item} = 1;
15660:         }
15661:         $domdefaults{$item} = $newvalues{$item};
15662:     }
15663:     my %staticdefaults = (
15664:                            'intauth_cost'   => 10,
15665:                            'intauth_check'  => 0,
15666:                            'intauth_switch' => 0,
15667:                          );
15668:     foreach my $item ('intauth_cost','intauth_check','intauth_switch') {
15669:         if (exists($domdefaults{$item})) {
15670:             $newvalues{$item} = $domdefaults{$item};
15671:         } else {
15672:             $newvalues{$item} = $staticdefaults{$item};
15673:         }
15674:     }
15675:     my %defaults_hash = (
15676:                          defaults => \%newvalues,
15677:                         );
15678:     my $title = &defaults_titles();
15679: 
15680:     my $currinststatus;
15681:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
15682:         $currinststatus = $domconfig{'inststatus'};
15683:     } else {
15684:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
15685:         $currinststatus = {
15686:                              inststatustypes => $usertypes,
15687:                              inststatusorder => $types,
15688:                              inststatusguest => [],
15689:                           };
15690:     }
15691:     my @todelete = &Apache::loncommon::get_env_multiple('form.inststatus_delete');
15692:     my @allpos;
15693:     my %alltypes;
15694:     my @inststatusguest;
15695:     if (ref($currinststatus) eq 'HASH') {
15696:         if (ref($currinststatus->{'inststatusguest'}) eq 'ARRAY') {
15697:             foreach my $type (@{$currinststatus->{'inststatusguest'}}) {
15698:                 unless (grep(/^\Q$type\E$/,@todelete)) {
15699:                     push(@inststatusguest,$type);
15700:                 }
15701:             }
15702:         }
15703:     }
15704:     my ($currtitles,$currorder);
15705:     if (ref($currinststatus) eq 'HASH') {
15706:         if (ref($currinststatus->{'inststatusorder'}) eq 'ARRAY') {
15707:             foreach my $type (@{$currinststatus->{'inststatusorder'}}) {
15708:                 if (ref($currinststatus->{inststatustypes}) eq 'HASH') {
15709:                     if ($currinststatus->{inststatustypes}->{$type} ne '') {
15710:                         $currtitles .= $currinststatus->{inststatustypes}->{$type}.',';
15711:                     }
15712:                 }
15713:                 unless (grep(/^\Q$type\E$/,@todelete)) { 
15714:                     my $position = $env{'form.inststatus_pos_'.$type};
15715:                     $position =~ s/\D+//g;
15716:                     $allpos[$position] = $type;
15717:                     $alltypes{$type} = $env{'form.inststatus_title_'.$type};
15718:                     $alltypes{$type} =~ s/`//g;
15719:                 }
15720:             }
15721:             $currorder = join(',',@{$currinststatus->{'inststatusorder'}});
15722:             $currtitles =~ s/,$//;
15723:         }
15724:     }
15725:     if ($env{'form.addinststatus'}) {
15726:         my $newtype = $env{'form.addinststatus'};
15727:         $newtype =~ s/\W//g;
15728:         unless (exists($alltypes{$newtype})) {
15729:             $alltypes{$newtype} = $env{'form.addinststatus_title'};
15730:             $alltypes{$newtype} =~ s/`//g; 
15731:             my $position = $env{'form.addinststatus_pos'};
15732:             $position =~ s/\D+//g;
15733:             if ($position ne '') {
15734:                 $allpos[$position] = $newtype;
15735:             }
15736:         }
15737:     }
15738:     my @orderedstatus;
15739:     foreach my $type (@allpos) {
15740:         unless (($type eq '') || (grep(/^\Q$type\E$/,@orderedstatus))) {
15741:             push(@orderedstatus,$type);
15742:         }
15743:     }
15744:     foreach my $type (keys(%alltypes)) {
15745:         unless (grep(/^\Q$type\E$/,@orderedstatus)) {
15746:             delete($alltypes{$type});
15747:         }
15748:     }
15749:     $defaults_hash{'inststatus'} = {
15750:                                      inststatustypes => \%alltypes,
15751:                                      inststatusorder => \@orderedstatus,
15752:                                      inststatusguest => \@inststatusguest,
15753:                                    };
15754:     if (ref($defaults_hash{'inststatus'}) eq 'HASH') {
15755:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
15756:             $domdefaults{$item} = $defaults_hash{'inststatus'}{$item};
15757:         }
15758:     }
15759:     if ($currorder ne join(',',@orderedstatus)) {
15760:         $changes{'inststatus'}{'inststatusorder'} = 1;
15761:     }
15762:     my $newtitles;
15763:     foreach my $item (@orderedstatus) {
15764:         $newtitles .= $alltypes{$item}.',';
15765:     }
15766:     $newtitles =~ s/,$//;
15767:     if ($currtitles ne $newtitles) {
15768:         $changes{'inststatus'}{'inststatustypes'} = 1;
15769:     }
15770:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaults_hash,
15771:                                              $dom);
15772:     if ($putresult eq 'ok') {
15773:         if (keys(%changes) > 0) {
15774:             $resulttext = &mt('Changes made:').'<ul>';
15775:             my $version = &Apache::lonnet::get_server_loncaparev($dom);
15776:             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";
15777:             foreach my $item (sort(keys(%changes))) {
15778:                 if ($item eq 'inststatus') {
15779:                     if (ref($changes{'inststatus'}) eq 'HASH') {
15780:                         if (@orderedstatus) {
15781:                             $resulttext .= '<li>'.&mt('Institutional user status types set to:').' ';
15782:                             foreach my $type (@orderedstatus) { 
15783:                                 $resulttext .= $alltypes{$type}.', ';
15784:                             }
15785:                             $resulttext =~ s/, $//;
15786:                             $resulttext .= '</li>';
15787:                         } else {
15788:                             $resulttext .= '<li>'.&mt('Institutional user status types deleted').'</li>';
15789:                         }
15790:                     }
15791:                 } else {
15792:                     my $value = $env{'form.'.$item};
15793:                     if ($value eq '') {
15794:                         $value = &mt('none');
15795:                     } elsif ($item eq 'auth_def') {
15796:                         my %authnames = &authtype_names();
15797:                         my %shortauth = (
15798:                                           internal   => 'int',
15799:                                           krb4       => 'krb4',
15800:                                           krb5       => 'krb5',
15801:                                           localauth  => 'loc',
15802:                         );
15803:                         $value = $authnames{$shortauth{$value}};
15804:                     }
15805:                     $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$title->{$item},$value).'</li>';
15806:                     $mailmsgtext .= "$title->{$item} set to $value\n";  
15807:                 }
15808:             }
15809:             $resulttext .= '</ul>';
15810:             $mailmsgtext .= "\n";
15811:             my $cachetime = 24*60*60;
15812:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
15813:             if (ref($lastactref) eq 'HASH') {
15814:                 $lastactref->{'domdefaults'} = 1;
15815:             }
15816:             if ($changes{'auth_def'} || $changes{'auth_arg_def'} || $changes{'lang_def'} || $changes{'datelocale_def'}) {
15817:                 my $notify = 1;
15818:                 if (ref($domconfig{'contacts'}) eq 'HASH') {
15819:                     if ($domconfig{'contacts'}{'reportupdates'} == 0) {
15820:                         $notify = 0;
15821:                     }
15822:                 }
15823:                 if ($notify) {
15824:                     &Apache::lonmsg::sendemail('installrecord@loncapa.org',
15825:                                                "LON-CAPA Domain Settings Change - $dom",
15826:                                                $mailmsgtext);
15827:                 }
15828:             }
15829:         } else {
15830:             $resulttext = &mt('No changes made to default authentication/language/timezone settings');
15831:         }
15832:     } else {
15833:         $resulttext = '<span class="LC_error">'.
15834:             &mt('An error occurred: [_1]',$putresult).'</span>';
15835:     }
15836:     if (@errors > 0) {
15837:         $resulttext .= '<br />'.&mt('The following were left unchanged because the values entered were invalid:');
15838:         foreach my $item (@errors) {
15839:             $resulttext .= ' "'.$title->{$item}.'",';
15840:         }
15841:         $resulttext =~ s/,$//;
15842:     }
15843:     return $resulttext;
15844: }
15845: 
15846: sub modify_scantron {
15847:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
15848:     my ($resulttext,%confhash,%changes,$errors);
15849:     my $custom = 'custom.tab';
15850:     my $default = 'default.tab';
15851:     my $servadm = $r->dir_config('lonAdmEMail');
15852:     my ($configuserok,$author_ok,$switchserver) =
15853:         &config_check($dom,$confname,$servadm);
15854:     if ($env{'form.scantronformat.filename'} ne '') {
15855:         my $error;
15856:         if ($configuserok eq 'ok') {
15857:             if ($switchserver) {
15858:                 $error = &mt("Upload of bubblesheet format file is not permitted to this server: [_1]",$switchserver);
15859:             } else {
15860:                 if ($author_ok eq 'ok') {
15861:                     my ($result,$scantronurl) =
15862:                         &publishlogo($r,'upload','scantronformat',$dom,
15863:                                      $confname,'scantron','','',$custom);
15864:                     if ($result eq 'ok') {
15865:                         $confhash{'scantron'}{'scantronformat'} = $scantronurl;
15866:                         $changes{'scantronformat'} = 1;
15867:                     } else {
15868:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$custom,$result);
15869:                     }
15870:                 } else {
15871:                     $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);
15872:                 }
15873:             }
15874:         } else {
15875:             $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);
15876:         }
15877:         if ($error) {
15878:             &Apache::lonnet::logthis($error);
15879:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
15880:         }
15881:     }
15882:     if (ref($domconfig{'scantron'}) eq 'HASH') {
15883:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
15884:             if ($env{'form.scantronformat_del'}) {
15885:                 $confhash{'scantron'}{'scantronformat'} = '';
15886:                 $changes{'scantronformat'} = 1;
15887:             } else {
15888:                 $confhash{'scantron'}{'scantronformat'} = $domconfig{'scantron'}{'scantronformat'};
15889:             }
15890:         }
15891:     }
15892:     my @options = ('hdr','pad','rem');
15893:     my @fields = &scantroncsv_fields();
15894:     my %titles = &scantronconfig_titles();
15895:     my @formats = &Apache::loncommon::get_env_multiple('form.scantronconfig');
15896:     my ($newdat,$currdat,%newcol,%currcol);
15897:     if (grep(/^dat$/,@formats)) {
15898:         $confhash{'scantron'}{config}{dat} = 1;
15899:         $newdat = 1;
15900:     } else {
15901:         $newdat = 0;
15902:     }
15903:     if (grep(/^csv$/,@formats)) {
15904:         my %bynum;
15905:         foreach my $field (@fields) {
15906:             if ($env{'form.scantronconfig_csv_'.$field} =~ /^(\d+)$/) {
15907:                 my $posscol = $1;
15908:                 if (($posscol < 20) && (!$bynum{$posscol})) {
15909:                     $confhash{'scantron'}{config}{csv}{fields}{$field} = $posscol;
15910:                     $bynum{$posscol} = $field;
15911:                     $newcol{$field} = $posscol;
15912:                 }
15913:             }
15914:         }
15915:         if (keys(%newcol)) {
15916:             foreach my $option (@options) {
15917:                 if ($env{'form.scantroncsv_'.$option}) {
15918:                     $confhash{'scantron'}{config}{csv}{options}{$option} = 1;
15919:                 }
15920:             }
15921:         }
15922:     }
15923:     $currdat = 1;
15924:     if (ref($domconfig{'scantron'}) eq 'HASH') {
15925:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
15926:             unless (exists($domconfig{'scantron'}{'config'}{'dat'})) {
15927:                 $currdat = 0;
15928:             }
15929:             if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
15930:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
15931:                     %currcol = %{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}};
15932:                 }
15933:             }
15934:         }
15935:     }
15936:     if ($currdat != $newdat) {
15937:         $changes{'config'} = 1;
15938:     } else {
15939:         foreach my $field (@fields) {
15940:             if ($currcol{$field} ne '') {
15941:                 if ($currcol{$field} ne $newcol{$field}) {
15942:                     $changes{'config'} = 1;
15943:                     last;
15944:                 }
15945:             } elsif ($newcol{$field} ne '') {
15946:                 $changes{'config'} = 1;
15947:                 last;
15948:             }
15949:         }
15950:     }
15951:     if (keys(%confhash) > 0) {
15952:         my $putresult = &Apache::lonnet::put_dom('configuration',\%confhash,
15953:                                                  $dom);
15954:         if ($putresult eq 'ok') {
15955:             if (keys(%changes) > 0) {
15956:                 if (ref($confhash{'scantron'}) eq 'HASH') {
15957:                     $resulttext = &mt('Changes made:').'<ul>';
15958:                     if ($changes{'scantronformat'}) {
15959:                         if ($confhash{'scantron'}{'scantronformat'} eq '') {
15960:                             $resulttext .= '<li>'.&mt('[_1] bubblesheet format file removed; [_2] file will be used for courses in this domain.',$custom,$default).'</li>';
15961:                         } else {
15962:                             $resulttext .= '<li>'.&mt('Custom bubblesheet format file ([_1]) uploaded for use with courses in this domain.',$custom).'</li>';
15963:                         }
15964:                     }
15965:                     if ($changes{'config'}) {
15966:                         if (ref($confhash{'scantron'}{'config'}) eq 'HASH') {
15967:                             if ($confhash{'scantron'}{'config'}{'dat'}) {
15968:                                 $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .dat format').'</li>';
15969:                             }
15970:                             if (ref($confhash{'scantron'}{'config'}{'csv'}) eq 'HASH') {
15971:                                 if (ref($confhash{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
15972:                                     if (keys(%{$confhash{'scantron'}{'config'}{'csv'}{'fields'}})) {
15973:                                         $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .csv format, with following fields/column numbers supported:').'<ul>';
15974:                                         foreach my $field (@fields) {
15975:                                             if ($confhash{'scantron'}{'config'}{'csv'}{'fields'}{$field} ne '') {
15976:                                                 my $showcol = $confhash{'scantron'}{'config'}{'csv'}{'fields'}{$field} + 1;
15977:                                                 $resulttext .= '<li>'.$titles{$field}.': '.$showcol.'</li>';
15978:                                             }
15979:                                         }
15980:                                         $resulttext .= '</ul></li>';
15981:                                         if (ref($confhash{'scantron'}{'config'}{'csv'}{'options'}) eq 'HASH') {
15982:                                             if (keys(%{$confhash{'scantron'}{'config'}{'csv'}{'options'}})) {
15983:                                                 $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .csv format, with following options:').'<ul>';
15984:                                                 foreach my $option (@options) {
15985:                                                     if ($confhash{'scantron'}{'config'}{'csv'}{'options'}{$option} ne '') {
15986:                                                         $resulttext .= '<li>'.$titles{$option}.'</li>';
15987:                                                     }
15988:                                                 }
15989:                                                 $resulttext .= '</ul></li>';
15990:                                             }
15991:                                         }
15992:                                     }
15993:                                 }
15994:                             }
15995:                         } else {
15996:                             $resulttext .= '<li>'.&mt('No bubblesheet data upload formats set -- will default to assuming .dat format').'</li>';
15997:                         }
15998:                     }
15999:                     $resulttext .= '</ul>';
16000:                 } else {
16001:                     $resulttext = &mt('Changes made to bubblesheet format file.');
16002:                 }
16003:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
16004:                 if (ref($lastactref) eq 'HASH') {
16005:                     $lastactref->{'domainconfig'} = 1;
16006:                 }
16007:             } else {
16008:                 $resulttext = &mt('No changes made to bubblesheet format settings');
16009:             }
16010:         } else {
16011:             $resulttext = '<span class="LC_error">'.
16012:                 &mt('An error occurred: [_1]',$putresult).'</span>';
16013:         }
16014:     } else {
16015:         $resulttext = &mt('No changes made to bubblesheet format settings');
16016:     }
16017:     if ($errors) {
16018:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
16019:                        $errors.'</ul>';
16020:     }
16021:     return $resulttext;
16022: }
16023: 
16024: sub modify_coursecategories {
16025:     my ($dom,$lastactref,%domconfig) = @_;
16026:     my ($resulttext,%deletions,%reorderings,%needreordering,%adds,%changes,$errors,
16027:         $cathash);
16028:     my @deletecategory = &Apache::loncommon::get_env_multiple('form.deletecategory');
16029:     my @catitems = ('unauth','auth');
16030:     my @cattypes = ('std','domonly','codesrch','none');
16031:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
16032:         $cathash = $domconfig{'coursecategories'}{'cats'};
16033:         if ($domconfig{'coursecategories'}{'togglecats'} ne $env{'form.togglecats'}) {
16034:             $changes{'togglecats'} = 1;
16035:             $domconfig{'coursecategories'}{'togglecats'} = $env{'form.togglecats'};
16036:         }
16037:         if ($domconfig{'coursecategories'}{'categorize'} ne $env{'form.categorize'}) {
16038:             $changes{'categorize'} = 1;
16039:             $domconfig{'coursecategories'}{'categorize'} = $env{'form.categorize'};
16040:         }
16041:         if ($domconfig{'coursecategories'}{'togglecatscomm'} ne $env{'form.togglecatscomm'}) {
16042:             $changes{'togglecatscomm'} = 1;
16043:             $domconfig{'coursecategories'}{'togglecatscomm'} = $env{'form.togglecatscomm'};
16044:         }
16045:         if ($domconfig{'coursecategories'}{'categorizecomm'} ne $env{'form.categorizecomm'}) {
16046:             $changes{'categorizecomm'} = 1;
16047:             $domconfig{'coursecategories'}{'categorizecomm'} = $env{'form.categorizecomm'};
16048:         }
16049:         foreach my $item (@catitems) {
16050:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
16051:                 if ($domconfig{'coursecategories'}{$item} ne $env{'form.coursecat_'.$item}) {
16052:                     $changes{$item} = 1;
16053:                     $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
16054:                 }
16055:             }
16056:         }
16057:     } else {
16058:         $changes{'togglecats'} = 1;
16059:         $changes{'categorize'} = 1;
16060:         $changes{'togglecatscomm'} = 1;
16061:         $changes{'categorizecomm'} = 1;
16062:         $domconfig{'coursecategories'} = {
16063:                                              togglecats => $env{'form.togglecats'},
16064:                                              categorize => $env{'form.categorize'},
16065:                                              togglecatscomm => $env{'form.togglecatscomm'},
16066:                                              categorizecomm => $env{'form.categorizecomm'},
16067:                                          };
16068:         foreach my $item (@catitems) {
16069:             if ($env{'form.coursecat_'.$item} ne 'std') {
16070:                 $changes{$item} = 1;
16071:             }
16072:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
16073:                 $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
16074:             }
16075:         }
16076:     }
16077:     if (ref($cathash) eq 'HASH') {
16078:         if (($domconfig{'coursecategories'}{'cats'}{'instcode::0'} ne '')  && ($env{'form.instcode'} == 0)) {
16079:             push (@deletecategory,'instcode::0');
16080:         }
16081:         if (($domconfig{'coursecategories'}{'cats'}{'communities::0'} ne '')  && ($env{'form.communities'} == 0)) {
16082:             push(@deletecategory,'communities::0');
16083:         }
16084:     }
16085:     my (@predelcats,@predeltrails,%predelallitems,%sort_by_deltrail);
16086:     if (ref($cathash) eq 'HASH') {
16087:         if (@deletecategory > 0) {
16088:             #FIXME Need to remove category from all courses using a deleted category 
16089:             &Apache::loncommon::extract_categories($cathash,\@predelcats,\@predeltrails,\%predelallitems);
16090:             foreach my $item (@deletecategory) {
16091:                 if ($domconfig{'coursecategories'}{'cats'}{$item} ne '') {
16092:                     delete($domconfig{'coursecategories'}{'cats'}{$item});
16093:                     $deletions{$item} = 1;
16094:                     &recurse_cat_deletes($item,$cathash,\%deletions);
16095:                 }
16096:             }
16097:         }
16098:         foreach my $item (keys(%{$cathash})) {
16099:             my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
16100:             if ($cathash->{$item} ne $env{'form.'.$item}) {
16101:                 $reorderings{$item} = 1;
16102:                 $domconfig{'coursecategories'}{'cats'}{$item} = $env{'form.'.$item};
16103:             }
16104:             if ($env{'form.addcategory_name_'.$item} ne '') {
16105:                 my $newcat = $env{'form.addcategory_name_'.$item};
16106:                 my $newdepth = $depth+1;
16107:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
16108:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos_'.$item};
16109:                 $adds{$newitem} = 1; 
16110:             }
16111:             if ($env{'form.subcat_'.$item} ne '') {
16112:                 my $newcat = $env{'form.subcat_'.$item};
16113:                 my $newdepth = $depth+1;
16114:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
16115:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = 0;
16116:                 $adds{$newitem} = 1;
16117:             }
16118:         }
16119:     }
16120:     if ($env{'form.instcode'} eq '1') {
16121:         if (ref($cathash) eq 'HASH') {
16122:             my $newitem = 'instcode::0';
16123:             if ($cathash->{$newitem} eq '') {  
16124:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
16125:                 $adds{$newitem} = 1;
16126:             }
16127:         } else {
16128:             my $newitem = 'instcode::0';
16129:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
16130:             $adds{$newitem} = 1;
16131:         }
16132:     }
16133:     if ($env{'form.communities'} eq '1') {
16134:         if (ref($cathash) eq 'HASH') {
16135:             my $newitem = 'communities::0';
16136:             if ($cathash->{$newitem} eq '') {
16137:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
16138:                 $adds{$newitem} = 1;
16139:             }
16140:         } else {
16141:             my $newitem = 'communities::0';
16142:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
16143:             $adds{$newitem} = 1;
16144:         }
16145:     }
16146:     if ($env{'form.addcategory_name'} ne '') {
16147:         if (($env{'form.addcategory_name'} ne 'instcode') &&
16148:             ($env{'form.addcategory_name'} ne 'communities')) {
16149:             my $newitem = &escape($env{'form.addcategory_name'}).'::0';
16150:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos'};
16151:             $adds{$newitem} = 1;
16152:         }
16153:     }
16154:     my $putresult;
16155:     if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
16156:         if (keys(%deletions) > 0) {
16157:             foreach my $key (keys(%deletions)) {
16158:                 if ($predelallitems{$key} ne '') {
16159:                     $sort_by_deltrail{$predelallitems{$key}} = $predeltrails[$predelallitems{$key}];
16160:                 }
16161:             }
16162:         }
16163:         my (@chkcats,@chktrails,%chkallitems);
16164:         &Apache::loncommon::extract_categories($domconfig{'coursecategories'}{'cats'},\@chkcats,\@chktrails,\%chkallitems);
16165:         if (ref($chkcats[0]) eq 'ARRAY') {
16166:             my $depth = 0;
16167:             my $chg = 0;
16168:             for (my $i=0; $i<@{$chkcats[0]}; $i++) {
16169:                 my $name = $chkcats[0][$i];
16170:                 my $item;
16171:                 if ($name eq '') {
16172:                     $chg ++;
16173:                 } else {
16174:                     $item = &escape($name).'::0';
16175:                     if ($chg) {
16176:                         $domconfig{'coursecategories'}{'cats'}{$item} -= $chg;
16177:                     }
16178:                     $depth ++; 
16179:                     &recurse_check(\@chkcats,$domconfig{'coursecategories'}{'cats'},$depth,$name);
16180:                     $depth --;
16181:                 }
16182:             }
16183:         }
16184:     }
16185:     if ((keys(%changes) > 0) || (keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
16186:         $putresult = &Apache::lonnet::put_dom('configuration',\%domconfig,$dom);
16187:         if ($putresult eq 'ok') {
16188:             my %title = (
16189:                          togglecats     => 'Show/Hide a course in catalog',
16190:                          categorize     => 'Assign a category to a course',
16191:                          togglecatscomm => 'Show/Hide a community in catalog',
16192:                          categorizecomm => 'Assign a category to a community',
16193:                         );
16194:             my %level = (
16195:                          dom  => 'set in Domain ("Modify Course/Community")',
16196:                          crs  => 'set in Course ("Course Configuration")',
16197:                          comm => 'set in Community ("Community Configuration")',
16198:                          none     => 'No catalog',
16199:                          std      => 'Standard catalog',
16200:                          domonly  => 'Domain-only catalog',
16201:                          codesrch => 'Code search form',
16202:                         );
16203:             $resulttext = &mt('Changes made:').'<ul>';
16204:             if ($changes{'togglecats'}) {
16205:                 $resulttext .= '<li>'.&mt("$title{'togglecats'} $level{$env{'form.togglecats'}}").'</li>'; 
16206:             }
16207:             if ($changes{'categorize'}) {
16208:                 $resulttext .= '<li>'.&mt("$title{'categorize'} $level{$env{'form.categorize'}}").'</li>';
16209:             }
16210:             if ($changes{'togglecatscomm'}) {
16211:                 $resulttext .= '<li>'.&mt("$title{'togglecatscomm'} $level{$env{'form.togglecatscomm'}}").'</li>';
16212:             }
16213:             if ($changes{'categorizecomm'}) {
16214:                 $resulttext .= '<li>'.&mt("$title{'categorizecomm'} $level{$env{'form.categorizecomm'}}").'</li>';
16215:             }
16216:             if ($changes{'unauth'}) {
16217:                 $resulttext .= '<li>'.&mt('Catalog type for unauthenticated users set to "'.$level{$env{'form.coursecat_unauth'}}.'"').'</li>';
16218:             }
16219:             if ($changes{'auth'}) {
16220:                 $resulttext .= '<li>'.&mt('Catalog type for authenticated users set to "'.$level{$env{'form.coursecat_auth'}}.'"').'</li>';
16221:             }
16222:             if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
16223:                 my $cathash;
16224:                 if (ref($domconfig{'coursecategories'}) eq 'HASH') {
16225:                     $cathash = $domconfig{'coursecategories'}{'cats'};
16226:                 } else {
16227:                     $cathash = {};
16228:                 } 
16229:                 my (@cats,@trails,%allitems);
16230:                     &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,\%allitems);
16231:                 if (keys(%deletions) > 0) {
16232:                     $resulttext .= '<li>'.&mt('Deleted categories:').'<ul>';
16233:                     foreach my $predeltrail (sort {$a <=> $b } (keys(%sort_by_deltrail))) { 
16234:                         $resulttext .= '<li>'.$predeltrails[$predeltrail].'</li>';
16235:                     }
16236:                     $resulttext .= '</ul></li>';
16237:                 }
16238:                 if (keys(%reorderings) > 0) {
16239:                     my %sort_by_trail;
16240:                     $resulttext .= '<li>'.&mt('Reordered categories:').'<ul>';
16241:                     foreach my $key (keys(%reorderings)) {
16242:                         if ($allitems{$key} ne '') {
16243:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
16244:                         }
16245:                     }
16246:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
16247:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
16248:                     }
16249:                     $resulttext .= '</ul></li>';
16250:                 }
16251:                 if (keys(%adds) > 0) {
16252:                     my %sort_by_trail;
16253:                     $resulttext .= '<li>'.&mt('Added categories:').'<ul>';
16254:                     foreach my $key (keys(%adds)) {
16255:                         if ($allitems{$key} ne '') {
16256:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
16257:                         }
16258:                     }
16259:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
16260:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
16261:                     }
16262:                     $resulttext .= '</ul></li>';
16263:                 }
16264:                 &Apache::lonnet::do_cache_new('cats',$dom,$cathash,3600);
16265:                 if (ref($lastactref) eq 'HASH') {
16266:                     $lastactref->{'cats'} = 1;
16267:                 }
16268:             }
16269:             $resulttext .= '</ul>';
16270:             if ($changes{'unauth'} || $changes{'auth'}) {
16271:                 my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
16272:                 if ($changes{'auth'}) {
16273:                     $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
16274:                 }
16275:                 if ($changes{'unauth'}) {
16276:                     $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
16277:                 }
16278:                 my $cachetime = 24*60*60;
16279:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
16280:                 if (ref($lastactref) eq 'HASH') {
16281:                     $lastactref->{'domdefaults'} = 1;
16282:                 }
16283:             }
16284:         } else {
16285:             $resulttext = '<span class="LC_error">'.
16286:                           &mt('An error occurred: [_1]',$putresult).'</span>';
16287:         }
16288:     } else {
16289:         $resulttext = &mt('No changes made to course and community categories');
16290:     }
16291:     return $resulttext;
16292: }
16293: 
16294: sub modify_serverstatuses {
16295:     my ($dom,%domconfig) = @_;
16296:     my ($resulttext,%changes,%currserverstatus,%newserverstatus);
16297:     if (ref($domconfig{'serverstatuses'}) eq 'HASH') {
16298:         %currserverstatus = %{$domconfig{'serverstatuses'}};
16299:     }
16300:     my @pages = &serverstatus_pages();
16301:     foreach my $type (@pages) {
16302:         $newserverstatus{$type}{'namedusers'} = '';
16303:         $newserverstatus{$type}{'machines'} = '';
16304:         if (defined($env{'form.'.$type.'_namedusers'})) {
16305:             my @users = split(/,/,$env{'form.'.$type.'_namedusers'});
16306:             my @okusers;
16307:             foreach my $user (@users) {
16308:                 my ($uname,$udom) = split(/:/,$user);
16309:                 if (($udom =~ /^$match_domain$/) &&   
16310:                     (&Apache::lonnet::domain($udom)) &&
16311:                     ($uname =~ /^$match_username$/)) {
16312:                     if (!grep(/^\Q$user\E/,@okusers)) {
16313:                         push(@okusers,$user);
16314:                     }
16315:                 }
16316:             }
16317:             if (@okusers > 0) {
16318:                  @okusers = sort(@okusers);
16319:                  $newserverstatus{$type}{'namedusers'} = join(',',@okusers);
16320:             }
16321:         }
16322:         if (defined($env{'form.'.$type.'_machines'})) {
16323:             my @machines = split(/,/,$env{'form.'.$type.'_machines'});
16324:             my @okmachines;
16325:             foreach my $ip (@machines) {
16326:                 my @parts = split(/\./,$ip);
16327:                 next if (@parts < 4);
16328:                 my $badip = 0;
16329:                 for (my $i=0; $i<4; $i++) {
16330:                     if (!(($parts[$i] >= 0) && ($parts[$i] <= 255))) {
16331:                         $badip = 1;
16332:                         last;
16333:                     }
16334:                 }
16335:                 if (!$badip) {
16336:                     push(@okmachines,$ip);     
16337:                 }
16338:             }
16339:             @okmachines = sort(@okmachines);
16340:             $newserverstatus{$type}{'machines'} = join(',',@okmachines);
16341:         }
16342:     }
16343:     my %serverstatushash =  (
16344:                                 serverstatuses => \%newserverstatus,
16345:                             );
16346:     foreach my $type (@pages) {
16347:         foreach my $setting ('namedusers','machines') {
16348:             my (@current,@new);
16349:             if (ref($currserverstatus{$type}) eq 'HASH') {
16350:                 if ($currserverstatus{$type}{$setting} ne '') { 
16351:                     @current = split(/,/,$currserverstatus{$type}{$setting});
16352:                 }
16353:             }
16354:             if ($newserverstatus{$type}{$setting} ne '') {
16355:                 @new = split(/,/,$newserverstatus{$type}{$setting});
16356:             }
16357:             if (@current > 0) {
16358:                 if (@new > 0) {
16359:                     foreach my $item (@current) {
16360:                         if (!grep(/^\Q$item\E$/,@new)) {
16361:                             $changes{$type}{$setting} = 1;
16362:                             last;
16363:                         }
16364:                     }
16365:                     foreach my $item (@new) {
16366:                         if (!grep(/^\Q$item\E$/,@current)) {
16367:                             $changes{$type}{$setting} = 1;
16368:                             last;
16369:                         }
16370:                     }
16371:                 } else {
16372:                     $changes{$type}{$setting} = 1;
16373:                 }
16374:             } elsif (@new > 0) {
16375:                 $changes{$type}{$setting} = 1;
16376:             }
16377:         }
16378:     }
16379:     if (keys(%changes) > 0) {
16380:         my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
16381:         my $putresult = &Apache::lonnet::put_dom('configuration',
16382:                                                  \%serverstatushash,$dom);
16383:         if ($putresult eq 'ok') {
16384:             $resulttext .= &mt('Changes made:').'<ul>';
16385:             foreach my $type (@pages) {
16386:                 if (ref($changes{$type}) eq 'HASH') {
16387:                     $resulttext .= '<li>'.$titles->{$type}.'<ul>';
16388:                     if ($changes{$type}{'namedusers'}) {
16389:                         if ($newserverstatus{$type}{'namedusers'} eq '') {
16390:                             $resulttext .= '<li>'.&mt("Access terminated for all specific (named) users").'</li>'."\n";
16391:                         } else {
16392:                             $resulttext .= '<li>'.&mt("Access available for the following specified users: ").$newserverstatus{$type}{'namedusers'}.'</li>'."\n";
16393:                         }
16394:                     }
16395:                     if ($changes{$type}{'machines'}) {
16396:                         if ($newserverstatus{$type}{'machines'} eq '') {
16397:                             $resulttext .= '<li>'.&mt("Access terminated for all specific IP addresses").'</li>'."\n";
16398:                         } else {
16399:                             $resulttext .= '<li>'.&mt("Access available for the following specified IP addresses: ").$newserverstatus{$type}{'machines'}.'</li>'."\n";
16400:                         }
16401: 
16402:                     }
16403:                     $resulttext .= '</ul></li>';
16404:                 }
16405:             }
16406:             $resulttext .= '</ul>';
16407:         } else {
16408:             $resulttext = '<span class="LC_error">'.
16409:                           &mt('An error occurred saving access settings for server status pages: [_1].',$putresult).'</span>';
16410: 
16411:         }
16412:     } else {
16413:         $resulttext = &mt('No changes made to access to server status pages');
16414:     }
16415:     return $resulttext;
16416: }
16417: 
16418: sub modify_helpsettings {
16419:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
16420:     my ($resulttext,$errors,%changes,%helphash);
16421:     my %defaultchecked = ('submitbugs' => 'on');
16422:     my @offon = ('off','on');
16423:     my @toggles = ('submitbugs');
16424:     my %current = ('submitbugs' => '',
16425:                    'adhoc'      => {},
16426:                   );
16427:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
16428:         %current = %{$domconfig{'helpsettings'}};
16429:     }
16430:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
16431:     foreach my $item (@toggles) {
16432:         if ($defaultchecked{$item} eq 'on') { 
16433:             if ($current{$item} eq '') {
16434:                 if ($env{'form.'.$item} eq '0') {
16435:                     $changes{$item} = 1;
16436:                 }
16437:             } elsif ($current{$item} ne $env{'form.'.$item}) {
16438:                 $changes{$item} = 1;
16439:             }
16440:         } elsif ($defaultchecked{$item} eq 'off') {
16441:             if ($current{$item} eq '') {
16442:                 if ($env{'form.'.$item} eq '1') {
16443:                     $changes{$item} = 1;
16444:                 }
16445:             } elsif ($current{$item} ne $env{'form.'.$item}) {
16446:                 $changes{$item} = 1;
16447:             }
16448:         }
16449:         if (($env{'form.'.$item} eq '0') || ($env{'form.'.$item} eq '1')) {
16450:             $helphash{'helpsettings'}{$item} = $env{'form.'.$item};
16451:         }
16452:     }
16453:     my $maxnum = $env{'form.helproles_maxnum'};
16454:     my $confname = $dom.'-domainconfig';
16455:     my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
16456:     my (@allpos,%newsettings,%changedprivs,$newrole);
16457:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
16458:     my @accesstypes = ('all','dh','da','none','status','inc','exc');
16459:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh','da']);
16460:     my %lt = &Apache::lonlocal::texthash(
16461:                     s      => 'system',
16462:                     d      => 'domain',
16463:                     order  => 'Display order',
16464:                     access => 'Role usage',
16465:                     all    => 'All with domain helpdesk or helpdesk assistant role',
16466:                     dh     => 'All with domain helpdesk role',
16467:                     da     => 'All with domain helpdesk assistant role',
16468:                     none   => 'None',
16469:                     status => 'Determined based on institutional status',
16470:                     inc    => 'Include all, but exclude specific personnel',
16471:                     exc    => 'Exclude all, but include specific personnel',
16472:     );
16473:     for (my $num=0; $num<=$maxnum; $num++) {
16474:         my ($prefix,$identifier,$rolename,%curr);
16475:         if ($num == $maxnum) {
16476:             next unless ($env{'form.newcusthelp'} == $maxnum);
16477:             $identifier = 'custhelp'.$num;
16478:             $prefix = 'helproles_'.$num;
16479:             $rolename = $env{'form.custhelpname'.$num};
16480:             $rolename=~s/[^A-Za-z0-9]//gs;
16481:             next if ($rolename eq '');
16482:             next if (exists($existing{'rolesdef_'.$rolename}));
16483:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
16484:             my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
16485:                                                      $newprivs{'c'},$confname,$dom);
16486:             if ($result ne 'ok') {
16487:                 $errors .= '<li><span class="LC_error">'.
16488:                            &mt('An error occurred storing the new custom role: [_1]',
16489:                            $result).'</span></li>';
16490:                 next;
16491:             } else {
16492:                 $changedprivs{$rolename} = \%newprivs;
16493:                 $newrole = $rolename;
16494:             }
16495:         } else {
16496:             $prefix = 'helproles_'.$num;
16497:             $rolename = $env{'form.'.$prefix};
16498:             next if ($rolename eq '');
16499:             next unless (exists($existing{'rolesdef_'.$rolename}));
16500:             $identifier = 'custhelp'.$num;
16501:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
16502:             my %currprivs;
16503:             ($currprivs{'s'},$currprivs{'d'},$currprivs{'c'}) =
16504:                 split(/\_/,$existing{'rolesdef_'.$rolename});
16505:             foreach my $level ('c','d','s') {
16506:                 if ($newprivs{$level} ne $currprivs{$level}) {
16507:                     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
16508:                                                              $newprivs{'c'},$confname,$dom);
16509:                     if ($result ne 'ok') {
16510:                         $errors .= '<li><span class="LC_error">'.
16511:                                    &mt('An error occurred storing privileges for existing role [_1]: [_2]',
16512:                                        $rolename,$result).'</span></li>';
16513:                     } else {
16514:                         $changedprivs{$rolename} = \%newprivs;
16515:                     }
16516:                     last;
16517:                 }
16518:             }
16519:             if (ref($current{'adhoc'}) eq 'HASH') {
16520:                 if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
16521:                     %curr = %{$current{'adhoc'}{$rolename}};
16522:                 }
16523:             }
16524:         }
16525:         my $newpos = $env{'form.'.$prefix.'_pos'};
16526:         $newpos =~ s/\D+//g;
16527:         $allpos[$newpos] = $rolename;
16528:         my $newdesc = $env{'form.'.$prefix.'_desc'};
16529:         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'desc'} = $newdesc;
16530:         if ($curr{'desc'}) {
16531:             if ($curr{'desc'} ne $newdesc) {
16532:                 $changes{'customrole'}{$rolename}{'desc'} = 1;
16533:                 $newsettings{$rolename}{'desc'} = $newdesc;
16534:             }
16535:         } elsif ($newdesc ne '') {
16536:             $changes{'customrole'}{$rolename}{'desc'} = 1;
16537:             $newsettings{$rolename}{'desc'} = $newdesc;
16538:         }
16539:         my $access = $env{'form.'.$prefix.'_access'};
16540:         if (grep(/^\Q$access\E$/,@accesstypes)) {
16541:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = $access;
16542:             if ($access eq 'status') {
16543:                 my @statuses = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_status');
16544:                 if (scalar(@statuses) == 0) {
16545:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'none';
16546:                 } else {
16547:                     my (@shownstatus,$numtypes);
16548:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
16549:                     if (ref($types) eq 'ARRAY') {
16550:                         $numtypes = scalar(@{$types});
16551:                         foreach my $type (sort(@statuses)) {
16552:                             if ($type eq 'default') {
16553:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
16554:                             } elsif (grep(/^\Q$type\E$/,@{$types})) {
16555:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
16556:                                 push(@shownstatus,$usertypes->{$type});
16557:                             }
16558:                         }
16559:                     }
16560:                     if (grep(/^default$/,@statuses)) {
16561:                         push(@shownstatus,$othertitle);
16562:                     }
16563:                     if (scalar(@shownstatus) == 1+$numtypes) {
16564:                         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'all';
16565:                         delete($helphash{'helpsettings'}{'adhoc'}{$rolename}{'status'});
16566:                     } else {
16567:                         $newsettings{$rolename}{'status'} = join(' '.&mt('or').' ',@shownstatus);
16568:                         if (ref($curr{'status'}) eq 'ARRAY') {
16569:                             my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
16570:                             if (@diffs) {
16571:                                 $changes{'customrole'}{$rolename}{$access} = 1;
16572:                             }
16573:                         } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
16574:                             $changes{'customrole'}{$rolename}{$access} = 1;
16575:                         }
16576:                     }
16577:                 }
16578:             } elsif (($access eq 'inc') || ($access eq 'exc')) {
16579:                 my @personnel = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_staff_'.$access);
16580:                 my @newspecstaff;
16581:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
16582:                 foreach my $person (sort(@personnel)) {
16583:                     if ($domhelpdesk{$person}) {
16584:                         push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$person);
16585:                     }
16586:                 }
16587:                 if (ref($curr{$access}) eq 'ARRAY') {
16588:                     my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
16589:                     if (@diffs) {
16590:                         $changes{'customrole'}{$rolename}{$access} = 1;
16591:                     }
16592:                 } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
16593:                     $changes{'customrole'}{$rolename}{$access} = 1;
16594:                 }
16595:                 foreach my $person (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
16596:                     my ($uname,$udom) = split(/:/,$person);
16597:                         push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
16598:                 }
16599:                 $newsettings{$rolename}{$access} = join(', ',sort(@newspecstaff));
16600:             }
16601:         } else {
16602:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}= 'all';
16603:         }
16604:         unless ($curr{'access'} eq $access) {
16605:             $changes{'customrole'}{$rolename}{'access'} = 1;
16606:             $newsettings{$rolename}{'access'} = $lt{$helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}};
16607:         }
16608:     }
16609:     if (@allpos > 0) {
16610:         my $idx = 0;
16611:         foreach my $rolename (@allpos) {
16612:             if ($rolename ne '') {
16613:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{'order'} = $idx;
16614:                 if (ref($current{'adhoc'}) eq 'HASH') {
16615:                     if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
16616:                         if ($current{'adhoc'}{$rolename}{'order'} ne $idx) {
16617:                             $changes{'customrole'}{$rolename}{'order'} = 1;
16618:                             $newsettings{$rolename}{'order'} = $idx+1;
16619:                         }
16620:                     }
16621:                 }
16622:                 $idx ++;
16623:             }
16624:         }
16625:     }
16626:     my $putresult;
16627:     if (keys(%changes) > 0) {
16628:         $putresult = &Apache::lonnet::put_dom('configuration',\%helphash,$dom);
16629:         if ($putresult eq 'ok') {
16630:             if (ref($helphash{'helpsettings'}) eq 'HASH') {
16631:                 $domdefaults{'submitbugs'} = $helphash{'helpsettings'}{'submitbugs'};
16632:                 if (ref($helphash{'helpsettings'}{'adhoc'}) eq 'HASH') {
16633:                     $domdefaults{'adhocroles'} = $helphash{'helpsettings'}{'adhoc'};
16634:                 }
16635:             }
16636:             my $cachetime = 24*60*60;
16637:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
16638:             if (ref($lastactref) eq 'HASH') {
16639:                 $lastactref->{'domdefaults'} = 1;
16640:             }
16641:         } else {
16642:             $errors .= '<li><span class="LC_error">'.
16643:                        &mt('An error occurred storing the settings: [_1]',
16644:                            $putresult).'</span></li>';
16645:         }
16646:     }
16647:     if ((keys(%changes) && ($putresult eq 'ok')) || (keys(%changedprivs))) {
16648:         $resulttext = &mt('Changes made:').'<ul>';
16649:         my (%shownprivs,@levelorder);
16650:         @levelorder = ('c','d','s');
16651:         if ((keys(%changes)) && ($putresult eq 'ok')) {
16652:             foreach my $item (sort(keys(%changes))) {
16653:                 if ($item eq 'submitbugs') {
16654:                     $resulttext .= '<li>'.&mt('Display link to: [_1] set to "'.$offon[$env{'form.'.$item}].'".',
16655:                                               &Apache::loncommon::modal_link('http://bugs.loncapa.org',
16656:                                               &mt('LON-CAPA bug tracker'),600,500)).'</li>';
16657:                 } elsif ($item eq 'customrole') {
16658:                     if (ref($changes{'customrole'}) eq 'HASH') {
16659:                         my @keyorder = ('order','desc','access','status','exc','inc');
16660:                         my %keytext = &Apache::lonlocal::texthash(
16661:                                                                    order  => 'Order',
16662:                                                                    desc   => 'Role description',
16663:                                                                    access => 'Role usage',
16664:                                                                    status => 'Allowed institutional types',
16665:                                                                    exc    => 'Allowed personnel',
16666:                                                                    inc    => 'Disallowed personnel',
16667:                         );
16668:                         foreach my $role (sort(keys(%{$changes{'customrole'}}))) {
16669:                             if (ref($changes{'customrole'}{$role}) eq 'HASH') {
16670:                                 if ($role eq $newrole) {
16671:                                     $resulttext .= '<li>'.&mt('New custom role added: [_1]',
16672:                                                               $role).'<ul>';
16673:                                 } else {
16674:                                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
16675:                                                               $role).'<ul>';
16676:                                 }
16677:                                 foreach my $key (@keyorder) {
16678:                                     if ($changes{'customrole'}{$role}{$key}) {
16679:                                         $resulttext .= '<li>'.&mt("[_1] set to: [_2]",
16680:                                                                   $keytext{$key},$newsettings{$role}{$key}).
16681:                                                        '</li>';
16682:                                     }
16683:                                 }
16684:                                 if (ref($changedprivs{$role}) eq 'HASH') {
16685:                                     $shownprivs{$role} = 1;
16686:                                     $resulttext .= '<li>'.&mt('Privileges set to :').'<ul>';
16687:                                     foreach my $level (@levelorder) {
16688:                                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
16689:                                             next if ($item eq '');
16690:                                             my ($priv) = split(/\&/,$item,2);
16691:                                             if (&Apache::lonnet::plaintext($priv)) {
16692:                                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
16693:                                                 unless ($level eq 'c') {
16694:                                                     $resulttext .= ' ('.$lt{$level}.')';
16695:                                                 }
16696:                                                 $resulttext .= '</li>';
16697:                                             }
16698:                                         }
16699:                                     }
16700:                                     $resulttext .= '</ul>';
16701:                                 }
16702:                                 $resulttext .= '</ul></li>';
16703:                             }
16704:                         }
16705:                     }
16706:                 }
16707:             }
16708:         }
16709:         if (keys(%changedprivs)) {
16710:             foreach my $role (sort(keys(%changedprivs))) {
16711:                 unless ($shownprivs{$role}) {
16712:                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
16713:                                               $role).'<ul>'.
16714:                                    '<li>'.&mt('Privileges set to :').'<ul>';
16715:                     foreach my $level (@levelorder) {
16716:                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
16717:                             next if ($item eq '');
16718:                             my ($priv) = split(/\&/,$item,2);
16719:                             if (&Apache::lonnet::plaintext($priv)) {
16720:                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
16721:                                 unless ($level eq 'c') {
16722:                                     $resulttext .= ' ('.$lt{$level}.')';
16723:                                 }
16724:                                 $resulttext .= '</li>';
16725:                             }
16726:                         }
16727:                     }
16728:                     $resulttext .= '</ul></li></ul></li>';
16729:                 }
16730:             }
16731:         }
16732:         $resulttext .= '</ul>';
16733:     } else {
16734:         $resulttext = &mt('No changes made to help settings');
16735:     }
16736:     if ($errors) {
16737:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
16738:                                     $errors.'</ul>';
16739:     }
16740:     return $resulttext;
16741: }
16742: 
16743: sub modify_coursedefaults {
16744:     my ($dom,$lastactref,%domconfig) = @_;
16745:     my ($resulttext,$errors,%changes,%defaultshash);
16746:     my %defaultchecked = (
16747:                            'uselcmath'       => 'on',
16748:                            'usejsme'         => 'on',
16749:                            'inline_chem'     => 'on',
16750:                          );
16751:     my @toggles = ('uselcmath','usejsme','inline_chem');
16752:     my @numbers = ('anonsurvey_threshold','uploadquota_official','uploadquota_unofficial',
16753:                    'uploadquota_community','uploadquota_textbook','mysqltables_official',
16754:                    'mysqltables_unofficial','mysqltables_community','mysqltables_textbook');
16755:     my @types = ('official','unofficial','community','textbook');
16756:     my %staticdefaults = (
16757:                            anonsurvey_threshold => 10,
16758:                            uploadquota          => 500,
16759:                            postsubmit           => 60,
16760:                            mysqltables          => 172800,
16761:                          );
16762:     my %texoptions = (
16763:                         MathJax  => 'MathJax',
16764:                         mimetex  => &mt('Convert to Images'),
16765:                         tth      => &mt('TeX to HTML'),
16766:                      );
16767:     $defaultshash{'coursedefaults'} = {};
16768: 
16769:     if (ref($domconfig{'coursedefaults'}) ne 'HASH') {
16770:         if ($domconfig{'coursedefaults'} eq '') {
16771:             $domconfig{'coursedefaults'} = {};
16772:         }
16773:     }
16774: 
16775:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
16776:         foreach my $item (@toggles) {
16777:             if ($defaultchecked{$item} eq 'on') {
16778:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
16779:                     ($env{'form.'.$item} eq '0')) {
16780:                     $changes{$item} = 1;
16781:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
16782:                     $changes{$item} = 1;
16783:                 }
16784:             } elsif ($defaultchecked{$item} eq 'off') {
16785:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
16786:                     ($env{'form.'.$item} eq '1')) {
16787:                     $changes{$item} = 1;
16788:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
16789:                     $changes{$item} = 1;
16790:                 }
16791:             }
16792:             $defaultshash{'coursedefaults'}{$item} = $env{'form.'.$item};
16793:         }
16794:         foreach my $item (@numbers) {
16795:             my ($currdef,$newdef);
16796:             $newdef = $env{'form.'.$item};
16797:             if ($item eq 'anonsurvey_threshold') {
16798:                 $currdef = $domconfig{'coursedefaults'}{$item};
16799:                 $newdef =~ s/\D//g;
16800:                 if ($newdef eq '' || $newdef < 1) {
16801:                     $newdef = 1;
16802:                 }
16803:                 $defaultshash{'coursedefaults'}{$item} = $newdef;
16804:             } else {
16805:                 my ($setting,$type) = ($item =~ /^(uploadquota|mysqltables)_(\w+)$/);
16806:                 if (ref($domconfig{'coursedefaults'}{$setting}) eq 'HASH') {
16807:                     $currdef = $domconfig{'coursedefaults'}{$setting}{$type};
16808:                 }
16809:                 $newdef =~ s/[^\w.\-]//g;
16810:                 $defaultshash{'coursedefaults'}{$setting}{$type} = $newdef;
16811:             }
16812:             if ($currdef ne $newdef) {
16813:                 if ($item eq 'anonsurvey_threshold') {
16814:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$item})) {
16815:                         $changes{$item} = 1;
16816:                     }
16817:                 } elsif ($item =~ /^(uploadquota|mysqltables)_/) {
16818:                     my $setting = $1;
16819:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$setting})) {
16820:                         $changes{$setting} = 1;
16821:                     }
16822:                 }
16823:             }
16824:         }
16825:         my $texengine;
16826:         if ($env{'form.texengine'} =~ /^(MathJax|mimetex|tth)$/) {
16827:             $texengine = $env{'form.texengine'};
16828:             my $currdef = $domconfig{'coursedefaults'}{'texengine'};
16829:             if ($currdef eq '') {
16830:                 unless ($texengine eq $Apache::lonnet::deftex) {
16831:                     $changes{'texengine'} = 1;
16832:                 }
16833:             } elsif ($currdef ne $texengine) {
16834:                 $changes{'texengine'} = 1;
16835:             }
16836:         }
16837:         if ($texengine ne '') {
16838:             $defaultshash{'coursedefaults'}{'texengine'} = $texengine;
16839:         }
16840:         my $currclone = $domconfig{'coursedefaults'}{'canclone'};
16841:         my @currclonecode;
16842:         if (ref($currclone) eq 'HASH') {
16843:             if (ref($currclone->{'instcode'}) eq 'ARRAY') {
16844:                 @currclonecode = @{$currclone->{'instcode'}};
16845:             }
16846:         }
16847:         my $newclone;
16848:         if ($env{'form.canclone'} =~ /^(none|domain|instcode)$/) {
16849:             $newclone = $env{'form.canclone'};
16850:         }
16851:         if ($newclone eq 'instcode') {
16852:             my @newcodes = &Apache::loncommon::get_env_multiple('form.clonecode');
16853:             my (%codedefaults,@code_order,@clonecode);
16854:             &Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
16855:                                                     \@code_order);
16856:             foreach my $item (@code_order) {
16857:                 if (grep(/^\Q$item\E$/,@newcodes)) {
16858:                     push(@clonecode,$item);
16859:                 }
16860:             }
16861:             if (@clonecode) {
16862:                 $defaultshash{'coursedefaults'}{'canclone'} = { $newclone => \@clonecode };
16863:                 my @diffs = &Apache::loncommon::compare_arrays(\@currclonecode,\@clonecode);
16864:                 if (@diffs) {
16865:                     $changes{'canclone'} = 1;
16866:                 }
16867:             } else {
16868:                 $newclone eq '';
16869:             }
16870:         } elsif ($newclone ne '') {
16871:             $defaultshash{'coursedefaults'}{'canclone'} = $newclone;
16872:         }
16873:         if ($newclone ne $currclone) {
16874:             $changes{'canclone'} = 1;
16875:         }
16876:         my %credits;
16877:         foreach my $type (@types) {
16878:             unless ($type eq 'community') {
16879:                 $credits{$type} = $env{'form.'.$type.'_credits'};
16880:                 $credits{$type} =~ s/[^\d.]+//g;
16881:             }
16882:         }
16883:         if ((ref($domconfig{'coursedefaults'}{'coursecredits'}) ne 'HASH') &&
16884:             ($env{'form.coursecredits'} eq '1')) {
16885:             $changes{'coursecredits'} = 1;
16886:             foreach my $type (keys(%credits)) {
16887:                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
16888:             }
16889:         } else {
16890:             if ($env{'form.coursecredits'} eq '1') {
16891:                 foreach my $type (@types) {
16892:                     unless ($type eq 'community') {
16893:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type} ne $credits{$type}) {
16894:                             $changes{'coursecredits'} = 1;
16895:                         }
16896:                         $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
16897:                     }
16898:                 }
16899:             } elsif (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
16900:                 foreach my $type (@types) {
16901:                     unless ($type eq 'community') {
16902:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type}) {
16903:                             $changes{'coursecredits'} = 1;
16904:                             last;
16905:                         }
16906:                     }
16907:                 }
16908:             }
16909:         }
16910:         if ($env{'form.postsubmit'} eq '1') {
16911:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'on';
16912:             my %currtimeout;
16913:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
16914:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'off') {
16915:                     $changes{'postsubmit'} = 1;
16916:                 }
16917:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
16918:                     %currtimeout = %{$domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}};
16919:                 }
16920:             } else {
16921:                 $changes{'postsubmit'} = 1;
16922:             }
16923:             foreach my $type (@types) {
16924:                 my $timeout = $env{'form.'.$type.'_timeout'};
16925:                 $timeout =~ s/\D//g;
16926:                 if ($timeout == $staticdefaults{'postsubmit'}) {
16927:                     $timeout = '';
16928:                 } elsif (($timeout eq '') || ($timeout =~ /^0+$/)) {
16929:                     $timeout = '0';
16930:                 }
16931:                 unless ($timeout eq '') {
16932:                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type} = $timeout;
16933:                 }
16934:                 if (exists($currtimeout{$type})) {
16935:                     if ($timeout ne $currtimeout{$type}) {
16936:                         $changes{'postsubmit'} = 1;
16937:                     }
16938:                 } elsif ($timeout ne '') {
16939:                     $changes{'postsubmit'} = 1;
16940:                 }
16941:             }
16942:         } else {
16943:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'off';
16944:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
16945:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'on') {
16946:                     $changes{'postsubmit'} = 1;
16947:                 }
16948:             } else {
16949:                 $changes{'postsubmit'} = 1;
16950:             }
16951:         }
16952:     }
16953:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
16954:                                              $dom);
16955:     if ($putresult eq 'ok') {
16956:         if (keys(%changes) > 0) {
16957:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
16958:             if (($changes{'uploadquota'}) || ($changes{'postsubmit'}) ||
16959:                 ($changes{'coursecredits'}) || ($changes{'uselcmath'}) || ($changes{'usejsme'}) ||
16960:                 ($changes{'canclone'}) || ($changes{'mysqltables'}) || ($changes{'texengine'}) ||
16961:                 ($changes{'inline_chem'})) {
16962:                 foreach my $item ('uselcmath','usejsme','inline_chem','texengine') {
16963:                     if ($changes{$item}) {
16964:                         $domdefaults{$item}=$defaultshash{'coursedefaults'}{$item};
16965:                     }
16966:                 }
16967:                 if ($changes{'coursecredits'}) {
16968:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
16969:                         foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'coursecredits'}})) {
16970:                             $domdefaults{$type.'credits'} =
16971:                                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type};
16972:                         }
16973:                     }
16974:                 }
16975:                 if ($changes{'postsubmit'}) {
16976:                     if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
16977:                         $domdefaults{'postsubmit'} = $defaultshash{'coursedefaults'}{'postsubmit'}{'client'};
16978:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
16979:                             foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}})) {
16980:                                 $domdefaults{$type.'postsubtimeout'} =
16981:                                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
16982:                             }
16983:                         }
16984:                     }
16985:                 }
16986:                 if ($changes{'uploadquota'}) {
16987:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
16988:                         foreach my $type (@types) {
16989:                             $domdefaults{$type.'quota'}=$defaultshash{'coursedefaults'}{'uploadquota'}{$type};
16990:                         }
16991:                     }
16992:                 }
16993:                 if ($changes{'canclone'}) {
16994:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
16995:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
16996:                             my @clonecodes = @{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}};
16997:                             if (@clonecodes) {
16998:                                 $domdefaults{'canclone'} = join('+',@clonecodes);
16999:                             }
17000:                         }
17001:                     } else {
17002:                         $domdefaults{'canclone'}=$defaultshash{'coursedefaults'}{'canclone'};
17003:                     }
17004:                 }
17005:                 my $cachetime = 24*60*60;
17006:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
17007:                 if (ref($lastactref) eq 'HASH') {
17008:                     $lastactref->{'domdefaults'} = 1;
17009:                 }
17010:             }
17011:             $resulttext = &mt('Changes made:').'<ul>';
17012:             foreach my $item (sort(keys(%changes))) {
17013:                 if ($item eq 'uselcmath') {
17014:                     if ($env{'form.'.$item} eq '1') {
17015:                         $resulttext .= '<li>'.&mt('Math preview uses LON-CAPA previewer (javascript), if supported by browser.').'</li>';
17016:                     } else {
17017:                         $resulttext .= '<li>'.&mt('Math preview uses DragMath (Java), if supported by client OS.').'</li>';
17018:                     }
17019:                 } elsif ($item eq 'usejsme') {
17020:                     if ($env{'form.'.$item} eq '1') {
17021:                         $resulttext .= '<li>'.&mt('Molecule editor uses JSME (HTML5), if supported by browser.').'</li>';
17022:                     } else {
17023:                         $resulttext .= '<li>'.&mt('Molecule editor uses JME (Java), if supported by client OS.').'</li>';
17024:                     }
17025:                 } elsif ($item eq 'inline_chem') {
17026:                     if ($env{'form.'.$item} eq '1') {
17027:                         $resulttext .= '<li>'.&mt('Chemical Reaction Response uses inline previewer').'</li>';
17028:                     } else {
17029:                         $resulttext .= '<li>'.&mt('Chemical Reaction Response uses pop-up previewer').'</li>';
17030:                     }
17031:                 } elsif ($item eq 'texengine') {
17032:                     if ($defaultshash{'coursedefaults'}{'texengine'} ne '') {
17033:                         $resulttext .= '<li>'.&mt('Default method to display mathematics set to: "[_1]"',
17034:                                                   $texoptions{$defaultshash{'coursedefaults'}{'texengine'}}).'</li>';
17035:                     }
17036:                 } elsif ($item eq 'anonsurvey_threshold') {
17037:                     $resulttext .= '<li>'.&mt('Responder count required for display of anonymous survey submissions set to [_1].',$defaultshash{'coursedefaults'}{'anonsurvey_threshold'}).'</li>';
17038:                 } elsif ($item eq 'uploadquota') {
17039:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
17040:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded to a course/community via Course Editor set as follows:').'<ul>'.
17041:                                        '<li>'.&mt('Official courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'official'}.'</b>').'</li>'.
17042:                                        '<li>'.&mt('Unofficial courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'unofficial'}.'</b>').'</li>'.
17043:                                        '<li>'.&mt('Textbook courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'textbook'}.'</b>').'</li>'.
17044: 
17045:                                        '<li>'.&mt('Communities: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'community'}.'</b>').'</li>'.
17046:                                        '</ul>'.
17047:                                        '</li>';
17048:                     } else {
17049:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded via Course Editor remains default: [_1] MB',$staticdefaults{'uploadquota'}).'</li>';
17050:                     }
17051:                 } elsif ($item eq 'mysqltables') {
17052:                     if (ref($defaultshash{'coursedefaults'}{'mysqltables'}) eq 'HASH') {
17053:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver').'<ul>'.
17054:                                        '<li>'.&mt('Official courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'official'}.'</b>').'</li>'.
17055:                                        '<li>'.&mt('Unofficial courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'unofficial'}.'</b>').'</li>'.
17056:                                        '<li>'.&mt('Textbook courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'textbook'}.'</b>').'</li>'.
17057:                                        '<li>'.&mt('Communities: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'community'}.'</b>').'</li>'.
17058:                                        '</ul>'.
17059:                                        '</li>';
17060:                     } else {
17061:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver remains default: [_1] s',$staticdefaults{'uploadquota'}).'</li>';
17062:                     }
17063:                 } elsif ($item eq 'postsubmit') {
17064:                     if ($domdefaults{'postsubmit'} eq 'off') {
17065:                         $resulttext .= '<li>'.&mt('Submit button(s) remain enabled on page after student makes submission.');
17066:                     } else {
17067:                         $resulttext .= '<li>'.&mt('Submit button(s) disabled on page after student makes submission').'; ';
17068:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
17069:                             $resulttext .= &mt('durations:').'<ul>';
17070:                             foreach my $type (@types) {
17071:                                 $resulttext .= '<li>';
17072:                                 my $timeout;
17073:                                 if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
17074:                                     $timeout = $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
17075:                                 }
17076:                                 my $display;
17077:                                 if ($timeout eq '0') {
17078:                                     $display = &mt('unlimited');
17079:                                 } elsif ($timeout eq '') {
17080:                                     $display = &mt('[quant,_1,second] (default)',$staticdefaults{'postsubmit'});
17081:                                 } else {
17082:                                     $display = &mt('[quant,_1,second]',$timeout);
17083:                                 }
17084:                                 if ($type eq 'community') {
17085:                                     $resulttext .= &mt('Communities');
17086:                                 } elsif ($type eq 'official') {
17087:                                     $resulttext .= &mt('Official courses');
17088:                                 } elsif ($type eq 'unofficial') {
17089:                                     $resulttext .= &mt('Unofficial courses');
17090:                                 } elsif ($type eq 'textbook') {
17091:                                     $resulttext .= &mt('Textbook courses');
17092:                                 }
17093:                                 $resulttext .= ' -- '.$display.'</li>';
17094:                             }
17095:                             $resulttext .= '</ul>';
17096:                         }
17097:                         $resulttext .= '</li>';
17098:                     }
17099:                 } elsif ($item eq 'coursecredits') {
17100:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
17101:                         if (($domdefaults{'officialcredits'} eq '') &&
17102:                             ($domdefaults{'unofficialcredits'} eq '') &&
17103:                             ($domdefaults{'textbookcredits'} eq '')) {
17104:                             $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
17105:                         } else {
17106:                             $resulttext .= '<li>'.&mt('Student credits can be set per course by a Domain Coordinator, with the following defaults applying:').'<ul>'.
17107:                                            '<li>'.&mt('Official courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'official'}).'</li>'.
17108:                                            '<li>'.&mt('Unofficial courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'unofficial'}).'</li>'.
17109:                                            '<li>'.&mt('Textbook courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'textbook'}).'</li>'.
17110:                                            '</ul>'.
17111:                                            '</li>';
17112:                         }
17113:                     } else {
17114:                         $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
17115:                     }
17116:                 } elsif ($item eq 'canclone') {
17117:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
17118:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
17119:                             my $clonecodes = join(' '.&mt('and').' ',@{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}});
17120:                             $resulttext .= '<li>'.&mt('By default, official courses can be cloned from existing courses with the same: [_1]','<b>'.$clonecodes.'</b>').'</li>';
17121:                         }
17122:                     } elsif ($defaultshash{'coursedefaults'}{'canclone'} eq 'domain') {
17123:                         $resulttext .= '<li>'.&mt('By default, a course requester can clone any course from his/her domain.').'</li>';
17124:                     } else {
17125:                         $resulttext .= '<li>'.&mt('By default, only course owner and coordinators may clone a course.').'</li>';
17126:                     }
17127:                 }
17128:             }
17129:             $resulttext .= '</ul>';
17130:         } else {
17131:             $resulttext = &mt('No changes made to course defaults');
17132:         }
17133:     } else {
17134:         $resulttext = '<span class="LC_error">'.
17135:             &mt('An error occurred: [_1]',$putresult).'</span>';
17136:     }
17137:     return $resulttext;
17138: }
17139: 
17140: sub modify_selfenrollment {
17141:     my ($dom,$lastactref,%domconfig) = @_;
17142:     my ($resulttext,$errors,%changes,%selfenrollhash,%ordered);
17143:     my @types = ('official','unofficial','community','textbook');
17144:     my %titles = &tool_titles();
17145:     my %descs = &Apache::lonuserutils::selfenroll_default_descs();
17146:     ($ordered{'admin'},my $titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
17147:     $ordered{'default'} = ['types','registered','approval','limit'];
17148: 
17149:     my (%roles,%shown,%toplevel);
17150:     $roles{'0'} = &Apache::lonnet::plaintext('dc');
17151: 
17152:     if (ref($domconfig{'selfenrollment'}) ne 'HASH') {
17153:         if ($domconfig{'selfenrollment'} eq '') {
17154:             $domconfig{'selfenrollment'} = {};
17155:         }
17156:     }
17157:     %toplevel = (
17158:                   admin      => 'Configuration Rights',
17159:                   default    => 'Default settings',
17160:                   validation => 'Validation of self-enrollment requests',
17161:                 );
17162:     my ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
17163: 
17164:     if (ref($ordered{'admin'}) eq 'ARRAY') {
17165:         foreach my $item (@{$ordered{'admin'}}) {
17166:             foreach my $type (@types) {
17167:                 if ($env{'form.selfenrolladmin_'.$item.'_'.$type}) {
17168:                     $selfenrollhash{'admin'}{$type}{$item} = 1;
17169:                 } else {
17170:                     $selfenrollhash{'admin'}{$type}{$item} = 0;
17171:                 }
17172:                 if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
17173:                     if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
17174:                         if ($selfenrollhash{'admin'}{$type}{$item} ne
17175:                             $domconfig{'selfenrollment'}{'admin'}{$type}{$item})  {
17176:                             push(@{$changes{'admin'}{$type}},$item);
17177:                         }
17178:                     } else {
17179:                         if (!$selfenrollhash{'admin'}{$type}{$item}) {
17180:                             push(@{$changes{'admin'}{$type}},$item);
17181:                         }
17182:                     }
17183:                 } elsif (!$selfenrollhash{'admin'}{$type}{$item}) {
17184:                     push(@{$changes{'admin'}{$type}},$item);
17185:                 }
17186:             }
17187:         }
17188:     }
17189: 
17190:     foreach my $item (@{$ordered{'default'}}) {
17191:         foreach my $type (@types) {
17192:             my $value = $env{'form.selfenrolldefault_'.$item.'_'.$type};
17193:             if ($item eq 'types') {
17194:                 unless (($value eq 'all') || ($value eq 'dom')) {
17195:                     $value = '';
17196:                 }
17197:             } elsif ($item eq 'registered') {
17198:                 unless ($value eq '1') {
17199:                     $value = 0;
17200:                 }
17201:             } elsif ($item eq 'approval') {
17202:                 unless ($value =~ /^[012]$/) {
17203:                     $value = 0;
17204:                 }
17205:             } else {
17206:                 unless (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
17207:                     $value = 'none';
17208:                 }
17209:             }
17210:             $selfenrollhash{'default'}{$type}{$item} = $value;
17211:             if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
17212:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
17213:                     if ($selfenrollhash{'default'}{$type}{$item} ne
17214:                          $domconfig{'selfenrollment'}{'default'}{$type}{$item})  {
17215:                          push(@{$changes{'default'}{$type}},$item);
17216:                     }
17217:                 } else {
17218:                     push(@{$changes{'default'}{$type}},$item);
17219:                 }
17220:             } else {
17221:                 push(@{$changes{'default'}{$type}},$item);
17222:             }
17223:             if ($item eq 'limit') {
17224:                 if (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
17225:                     $env{'form.selfenrolldefault_cap_'.$type} =~ s/\D//g;
17226:                     if ($env{'form.selfenrolldefault_cap_'.$type} ne '') {
17227:                         $selfenrollhash{'default'}{$type}{'cap'} = $env{'form.selfenrolldefault_cap_'.$type};
17228:                     }
17229:                 } else {
17230:                     $selfenrollhash{'default'}{$type}{'cap'} = '';
17231:                 }
17232:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
17233:                     if ($selfenrollhash{'default'}{$type}{'cap'} ne
17234:                          $domconfig{'selfenrollment'}{'admin'}{$type}{'cap'})  {
17235:                          push(@{$changes{'default'}{$type}},'cap');
17236:                     }
17237:                 } elsif ($selfenrollhash{'default'}{$type}{'cap'} ne '') {
17238:                     push(@{$changes{'default'}{$type}},'cap');
17239:                 }
17240:             }
17241:         }
17242:     }
17243: 
17244:     foreach my $item (@{$itemsref}) {
17245:         if ($item eq 'fields') {
17246:             my @changed;
17247:             @{$selfenrollhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.selfenroll_validation_'.$item);
17248:             if (@{$selfenrollhash{'validation'}{$item}} > 0) {
17249:                 @{$selfenrollhash{'validation'}{$item}} = sort(@{$selfenrollhash{'validation'}{$item}});
17250:             }
17251:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
17252:                 if (ref($domconfig{'selfenrollment'}{'validation'}{$item}) eq 'ARRAY') {
17253:                     @changed = &Apache::loncommon::compare_arrays($selfenrollhash{'validation'}{$item},
17254:                                                                   $domconfig{'selfenrollment'}{'validation'}{$item});
17255:                 } else {
17256:                     @changed = @{$selfenrollhash{'validation'}{$item}};
17257:                 }
17258:             } else {
17259:                 @changed = @{$selfenrollhash{'validation'}{$item}};
17260:             }
17261:             if (@changed) {
17262:                 if ($selfenrollhash{'validation'}{$item}) { 
17263:                     $changes{'validation'}{$item} = join(', ',@{$selfenrollhash{'validation'}{$item}});
17264:                 } else {
17265:                     $changes{'validation'}{$item} = &mt('None');
17266:                 }
17267:             }
17268:         } else {
17269:             $selfenrollhash{'validation'}{$item} = $env{'form.selfenroll_validation_'.$item};
17270:             if ($item eq 'markup') {
17271:                if ($env{'form.selfenroll_validation_'.$item}) {
17272:                    $env{'form.selfenroll_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
17273:                }
17274:             }
17275:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
17276:                 if ($domconfig{'selfenrollment'}{'validation'}{$item} ne $selfenrollhash{'validation'}{$item}) {
17277:                     $changes{'validation'}{$item} = $selfenrollhash{'validation'}{$item};
17278:                 }
17279:             }
17280:         }
17281:     }
17282: 
17283:     my $putresult = &Apache::lonnet::put_dom('configuration',{'selfenrollment' => \%selfenrollhash},
17284:                                              $dom);
17285:     if ($putresult eq 'ok') {
17286:         if (keys(%changes) > 0) {
17287:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
17288:             $resulttext = &mt('Changes made:').'<ul>';
17289:             foreach my $key ('admin','default','validation') {
17290:                 if (ref($changes{$key}) eq 'HASH') {
17291:                     $resulttext .= '<li>'.$toplevel{$key}.'<ul>';
17292:                     if ($key eq 'validation') {
17293:                         foreach my $item (@{$itemsref}) {
17294:                             if (exists($changes{$key}{$item})) {
17295:                                 if ($item eq 'markup') {
17296:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
17297:                                                               '<br /><pre>'.$changes{$key}{$item}.'</pre>').'</li>';
17298:                                 } else {  
17299:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
17300:                                                               '<b>'.$changes{$key}{$item}.'</b>').'</li>';
17301:                                 }
17302:                             }
17303:                         }
17304:                     } else {
17305:                         foreach my $type (@types) {
17306:                             if ($type eq 'community') {
17307:                                 $roles{'1'} = &mt('Community personnel');
17308:                             } else {
17309:                                 $roles{'1'} = &mt('Course personnel');
17310:                             }
17311:                             if (ref($changes{$key}{$type}) eq 'ARRAY') {
17312:                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') {
17313:                                     if ($key eq 'admin') {
17314:                                         my @mgrdc = ();
17315:                                         if (ref($ordered{$key}) eq 'ARRAY') {
17316:                                             foreach my $item (@{$ordered{'admin'}}) {
17317:                                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') { 
17318:                                                     if ($selfenrollhash{$key}{$type}{$item} eq '0') {
17319:                                                         push(@mgrdc,$item);
17320:                                                     }
17321:                                                 }
17322:                                             }
17323:                                             if (@mgrdc) {
17324:                                                 $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
17325:                                             } else {
17326:                                                 delete($domdefaults{$type.'selfenrolladmdc'});
17327:                                             }
17328:                                         }
17329:                                     } else {
17330:                                         if (ref($ordered{$key}) eq 'ARRAY') {
17331:                                             foreach my $item (@{$ordered{$key}}) {
17332:                                                 if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
17333:                                                     $domdefaults{$type.'selfenroll'.$item} =
17334:                                                         $selfenrollhash{$key}{$type}{$item};
17335:                                                 }
17336:                                             }
17337:                                         }
17338:                                     }
17339:                                 }
17340:                                 $resulttext .= '<li>'.$titles{$type}.'<ul>';
17341:                                 foreach my $item (@{$ordered{$key}}) {
17342:                                     if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
17343:                                         $resulttext .= '<li>';
17344:                                         if ($key eq 'admin') {
17345:                                             $resulttext .= &mt('[_1] -- management by: [_2]',$titlesref->{$item},
17346:                                                                '<b>'.$roles{$selfenrollhash{'admin'}{$type}{$item}}.'</b>');
17347:                                         } else {
17348:                                             $resulttext .= &mt('[_1] set to: [_2]',$titlesref->{$item},
17349:                                                                '<b>'.$descs{$item}{$selfenrollhash{'default'}{$type}{$item}}.'</b>');
17350:                                         }
17351:                                         $resulttext .= '</li>';
17352:                                     }
17353:                                 }
17354:                                 $resulttext .= '</ul></li>';
17355:                             }
17356:                         }
17357:                         $resulttext .= '</ul></li>'; 
17358:                     }
17359:                 }
17360:             }
17361:             if ((exists($changes{'admin'})) || (exists($changes{'default'}))) {
17362:                 my $cachetime = 24*60*60;
17363:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
17364:                 if (ref($lastactref) eq 'HASH') {
17365:                     $lastactref->{'domdefaults'} = 1;
17366:                 }
17367:             }
17368:             $resulttext .= '</ul>';
17369:         } else {
17370:             $resulttext = &mt('No changes made to self-enrollment settings');
17371:         }
17372:     } else {
17373:         $resulttext = '<span class="LC_error">'.
17374:             &mt('An error occurred: [_1]',$putresult).'</span>';
17375:     }
17376:     return $resulttext;
17377: }
17378: 
17379: sub modify_wafproxy {
17380:     my ($dom,$action,$lastactref,%domconfig) = @_;
17381:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
17382:     my (%othercontrol,%canset,%values,%curralias,%currsaml,%currvalue,@warnings,
17383:         %wafproxy,%changes,%expirecache,%expiresaml);
17384:     foreach my $server (sort(keys(%servers))) {
17385:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
17386:         if ($serverhome eq $server) {
17387:             my $serverdom = &Apache::lonnet::host_domain($server);
17388:             if ($serverdom eq $dom) {
17389:                 $canset{$server} = 1;
17390:             }
17391:         }
17392:     }
17393:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
17394:         %{$values{$dom}} = ();
17395:         if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
17396:             %curralias = %{$domconfig{'wafproxy'}{'alias'}};
17397:         }
17398:         if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
17399:             %currsaml = %{$domconfig{'wafproxy'}{'saml'}};
17400:         }
17401:         foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
17402:             $currvalue{$item} = $domconfig{'wafproxy'}{$item};
17403:         }
17404:     }
17405:     my $output;
17406:     if (keys(%canset)) {
17407:         %{$wafproxy{'alias'}} = ();
17408:         %{$wafproxy{'saml'}} = ();
17409:         foreach my $key (sort(keys(%canset))) {
17410:             if ($env{'form.wafproxy_'.$dom}) {
17411:                 $wafproxy{'alias'}{$key} = $env{'form.wafproxy_alias_'.$key};
17412:                 $wafproxy{'alias'}{$key} =~ s/^\s+|\s+$//g;
17413:                 if ($wafproxy{'alias'}{$key} ne $curralias{$key}) {
17414:                     $changes{'alias'} = 1;
17415:                 }
17416:                 if ($env{'form.wafproxy_alias_saml_'.$key}) {
17417:                     $wafproxy{'saml'}{$key} = 1;
17418:                 }
17419:                 if ($wafproxy{'saml'}{$key} ne $currsaml{$key}) {
17420:                     $changes{'saml'} = 1;
17421:                 }
17422:             } else {
17423:                 $wafproxy{'alias'}{$key} = '';
17424:                 $wafproxy{'saml'}{$key} = '';
17425:                 if ($curralias{$key}) {
17426:                     $changes{'alias'} = 1;
17427:                 }
17428:                 if ($currsaml{$key}) {
17429:                     $changes{'saml'} = 1;
17430:                 }
17431:             }
17432:             if ($wafproxy{'alias'}{$key} eq '') {
17433:                 if ($curralias{$key}) {
17434:                     $expirecache{$key} = 1;
17435:                 }
17436:                 delete($wafproxy{'alias'}{$key});
17437:             }
17438:             if ($wafproxy{'saml'}{$key} eq '') {
17439:                 if ($currsaml{$key}) {
17440:                     $expiresaml{$key} = 1;
17441:                 }
17442:                 delete($wafproxy{'saml'}{$key});
17443:             }
17444:         }
17445:         unless (keys(%{$wafproxy{'alias'}})) {
17446:             delete($wafproxy{'alias'});
17447:         }
17448:         unless (keys(%{$wafproxy{'saml'}})) {
17449:             delete($wafproxy{'saml'});
17450:         }
17451:         # Localization for values in %warn occurs in &mt() calls separately.
17452:         my %warn = (
17453:                      trusted => 'trusted IP range(s)',
17454:                      vpnint => 'internal IP range(s) for VPN sessions(s)',
17455:                      vpnext => 'IP range(s) for backend WAF connections',
17456:                    );
17457:         foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
17458:             my $possible = $env{'form.wafproxy_'.$item};
17459:             $possible =~ s/^\s+|\s+$//g;
17460:             if ($possible ne '') {
17461:                 if ($item eq 'remoteip') {
17462:                     if ($possible =~ /^[mhn]$/) {
17463:                         $wafproxy{$item} = $possible;
17464:                     }
17465:                 } elsif ($item eq 'ipheader') {
17466:                     if ($wafproxy{'remoteip'} eq 'h') {
17467:                         $wafproxy{$item} = $possible;
17468:                     }
17469:                 } elsif ($item eq 'sslopt') {
17470:                     if ($possible =~ /^0|1$/) {
17471:                         $wafproxy{$item} = $possible;
17472:                     }
17473:                 } else {
17474:                     my (@ok,$count);
17475:                     if (($item eq 'vpnint') || ($item eq 'vpnext')) {
17476:                         unless ($env{'form.wafproxy_vpnaccess'}) {
17477:                             $possible = '';
17478:                         }
17479:                     } elsif ($item eq 'trusted') {
17480:                         unless ($wafproxy{'remoteip'} eq 'h') {
17481:                             $possible = '';
17482:                         }
17483:                     }
17484:                     unless ($possible eq '') {
17485:                         $possible =~ s/[\r\n]+/\s/g;
17486:                         $possible =~ s/\s*-\s*/-/g;
17487:                         $possible =~ s/\s+/,/g;
17488:                         $possible =~ s/,+/,/g;
17489:                     }
17490:                     $count = 0;
17491:                     if ($possible ne '') {
17492:                         foreach my $poss (split(/\,/,$possible)) {
17493:                             $count ++;
17494:                             $poss = &validate_ip_pattern($poss);
17495:                             if ($poss ne '') {
17496:                                 push(@ok,$poss);
17497:                             }
17498:                         }
17499:                         my $diff = $count - scalar(@ok);
17500:                         if ($diff) {
17501:                             push(@warnings,'<li>'.
17502:                                  &mt('[quant,_1,IP] invalid and excluded from saved value for [_2]',
17503:                                      $diff,$warn{$item}).
17504:                                  '</li>');
17505:                         }
17506:                         if (@ok) {
17507:                             my @cidr_list;
17508:                             foreach my $item (@ok) {
17509:                                 @cidr_list = &Net::CIDR::cidradd($item,@cidr_list);
17510:                             }
17511:                             $wafproxy{$item} = join(',',@cidr_list);
17512:                         }
17513:                     }
17514:                 }
17515:                 if ($wafproxy{$item} ne $currvalue{$item}) {
17516:                     $changes{$item} = 1;
17517:                 }
17518:             } elsif ($currvalue{$item}) {
17519:                 $changes{$item} = 1;
17520:             }
17521:         }
17522:     } else {
17523:         if (keys(%curralias)) {
17524:             $changes{'alias'} = 1;
17525:         }
17526:         if (keys(%currsaml)) {
17527:             $changes{'saml'} = 1;
17528:         }
17529:         if (keys(%currvalue)) {
17530:             foreach my $key (keys(%currvalue)) {
17531:                 $changes{$key} = 1;
17532:             }
17533:         }
17534:     }
17535:     if (keys(%changes)) {
17536:         my %defaultshash = (
17537:                               wafproxy => \%wafproxy,
17538:                            );
17539:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
17540:                                                  $dom);
17541:         if ($putresult eq 'ok') {
17542:             my $cachetime = 24*60*60;
17543:             my (%domdefaults,$updatedomdefs);
17544:             foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
17545:                 if ($changes{$item}) {
17546:                     unless ($updatedomdefs) {
17547:                         %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
17548:                         $updatedomdefs = 1;
17549:                     }
17550:                     if ($wafproxy{$item}) {
17551:                         $domdefaults{'waf_'.$item} = $wafproxy{$item};
17552:                     } elsif (exists($domdefaults{'waf_'.$item})) {
17553:                         delete($domdefaults{'waf_'.$item});
17554:                     }
17555:                 }
17556:             }
17557:             if ($updatedomdefs) {
17558:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
17559:                 if (ref($lastactref) eq 'HASH') {
17560:                     $lastactref->{'domdefaults'} = 1;
17561:                 }
17562:             }
17563:             if ((exists($wafproxy{'alias'})) || (keys(%expirecache))) {
17564:                 my %updates = %expirecache;
17565:                 foreach my $key (keys(%expirecache)) {
17566:                     &Apache::lonnet::devalidate_cache_new('proxyalias',$key);
17567:                 }
17568:                 if (ref($wafproxy{'alias'}) eq 'HASH') {
17569:                     my $cachetime = 24*60*60;
17570:                     foreach my $key (keys(%{$wafproxy{'alias'}})) {
17571:                         $updates{$key} = 1;
17572:                         &Apache::lonnet::do_cache_new('proxyalias',$key,$wafproxy{'alias'}{$key},
17573:                                                       $cachetime);
17574:                     }
17575:                 }
17576:                 if (ref($lastactref) eq 'HASH') {
17577:                     $lastactref->{'proxyalias'} = \%updates;
17578:                 }
17579:             }
17580:             if ((exists($wafproxy{'saml'})) || (keys(%expiresaml))) {
17581:                 my %samlupdates = %expiresaml;
17582:                 foreach my $key (keys(%expiresaml)) {
17583:                     &Apache::lonnet::devalidate_cache_new('proxysaml',$key);
17584:                 }
17585:                 if (ref($wafproxy{'saml'}) eq 'HASH') {
17586:                     my $cachetime = 24*60*60;
17587:                     foreach my $key (keys(%{$wafproxy{'saml'}})) {
17588:                         $samlupdates{$key} = 1;
17589:                         &Apache::lonnet::do_cache_new('proxysaml',$key,$wafproxy{'saml'}{$key},
17590:                                                       $cachetime);
17591:                     }
17592:                 }
17593:                 if (ref($lastactref) eq 'HASH') {
17594:                     $lastactref->{'proxysaml'} = \%samlupdates;
17595:                 }
17596:             }
17597:             $output = &mt('Changes were made to Web Application Firewall/Reverse Proxy').'<ul>';
17598:             foreach my $item ('alias','saml','remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
17599:                 if ($changes{$item}) {
17600:                     if ($item eq 'alias') {
17601:                         my $numaliased = 0;
17602:                         if (ref($wafproxy{'alias'}) eq 'HASH') {
17603:                             my $shown;
17604:                             if (keys(%{$wafproxy{'alias'}})) {
17605:                                 foreach my $server (sort(keys(%{$wafproxy{'alias'}}))) {
17606:                                     $shown .= '<li>'.&mt('[_1] aliased by [_2]',
17607:                                                          &Apache::lonnet::hostname($server),
17608:                                                          $wafproxy{'alias'}{$server}).'</li>';
17609:                                     $numaliased ++;
17610:                                 }
17611:                                 if ($numaliased) {
17612:                                     $output .= '<li>'.&mt('Aliases for hostnames set to: [_1]',
17613:                                                           '<ul>'.$shown.'</ul>').'</li>';
17614:                                 }
17615:                             }
17616:                         }
17617:                         unless ($numaliased) {
17618:                             $output .= '<li>'.&mt('Aliases deleted for hostnames').'</li>';
17619:                         }
17620:                     } elsif ($item eq 'saml') {
17621:                         my $shown;
17622:                         if (ref($wafproxy{'saml'}) eq 'HASH') {
17623:                             if (keys(%{$wafproxy{'saml'}})) {
17624:                                 $shown = join(', ',sort(keys(%{$wafproxy{'saml'}})));
17625:                             }
17626:                         }
17627:                         if ($shown) {
17628:                             $output .= '<li>'.&mt('Alias used by SSO Auth for: [_1]',
17629:                                                   $shown).'</li>';
17630:                         } else {
17631:                             $output .= '<li>'.&mt('No alias used for SSO Auth').'</li>';
17632:                         }
17633:                     } else {
17634:                         if ($item eq 'remoteip') {
17635:                             my %ip_methods = &remoteip_methods();
17636:                             if ($wafproxy{$item} =~ /^[mh]$/) {
17637:                                 $output .= '<li>'.&mt("Method for determining user's IP set to: [_1]",
17638:                                                       $ip_methods{$wafproxy{$item}}).'</li>';
17639:                             } else {
17640:                                 if (($env{'form.wafproxy_'.$dom}) && (ref($wafproxy{'alias'}) eq 'HASH')) {
17641:                                     $output .= '<li>'.&mt("No method in use to get user's real IP (will report IP used by WAF).").
17642:                                                '</li>';
17643:                                 } else {
17644:                                     $output .= '<li>'.&mt('WAF/Reverse Proxy not in use').'</li>';
17645:                                 }
17646:                             }
17647:                         } elsif ($item eq 'ipheader') {
17648:                             if ($wafproxy{$item}) {
17649:                                 $output .= '<li>'.&mt('Request header with remote IP set to: [_1]',
17650:                                                       $wafproxy{$item}).'</li>';
17651:                             } else {
17652:                                 $output .= '<li>'.&mt('Request header with remote IP deleted').'</li>';
17653:                             }
17654:                         } elsif ($item eq 'trusted') {
17655:                             if ($wafproxy{$item}) {
17656:                                 $output .= '<li>'.&mt('Trusted IP range(s) set to: [_1]',
17657:                                                       $wafproxy{$item}).'</li>';
17658:                             } else {
17659:                                 $output .= '<li>'.&mt('Trusted IP range(s) deleted').'</li>';
17660:                             }
17661:                         } elsif ($item eq 'vpnint') {
17662:                             if ($wafproxy{$item}) {
17663:                                 $output .= '<li>'.&mt('Internal IP Range(s) for VPN sessions set to: [_1]',
17664:                                                        $wafproxy{$item}).'</li>';
17665:                             } else {
17666:                                 $output .= '<li>'.&mt('Internal IP Range(s) for VPN sessions deleted').'</li>';
17667:                             }
17668:                         } elsif ($item eq 'vpnext') {
17669:                             if ($wafproxy{$item}) {
17670:                                 $output .= '<li>'.&mt('IP Range(s) for backend WAF connections set to: [_1]',
17671:                                                        $wafproxy{$item}).'</li>';
17672:                             } else {
17673:                                 $output .= '<li>'.&mt('IP Range(s) for backend WAF connections deleted').'</li>';
17674:                             }
17675:                         } elsif ($item eq 'sslopt') {
17676:                             if ($wafproxy{$item}) {
17677:                                 $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>';
17678:                             } else {
17679:                                 $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>';
17680:                             }
17681:                         }
17682:                     }
17683:                 }
17684:             }
17685:         } else {
17686:             $output = '<span class="LC_error">'.
17687:                       &mt('An error occurred: [_1]',$putresult).'</span>';
17688:         }
17689:     } elsif (keys(%canset)) {
17690:         $output = &mt('No changes made to Web Application Firewall/Reverse Proxy settings');
17691:     }
17692:     if (@warnings) {
17693:         $output .= '<br />'.&mt('Warnings:').'<ul>'.
17694:                        join("\n",@warnings).'</ul>';
17695:     }
17696:     return $output;
17697: }
17698: 
17699: sub validate_ip_pattern {
17700:     my ($pattern) = @_;
17701:     if ($pattern =~ /^([^-]+)\-([^-]+)$/) {
17702:         my ($start,$end) = ($1,$2);
17703:         if ((&Net::CIDR::cidrvalidate($start)) && (&Net::CIDR::cidrvalidate($end))) {
17704:             if (($start !~ m{/}) && ($end !~ m{/})) {
17705:                 return $start.'-'.$end;
17706:             }
17707:         }
17708:     } elsif ($pattern ne '') {
17709:         $pattern = &Net::CIDR::cidrvalidate($pattern);
17710:         if ($pattern ne '') {
17711:             return $pattern;
17712:         }
17713:     }
17714:     return;
17715: }
17716: 
17717: sub modify_usersessions {
17718:     my ($dom,$lastactref,%domconfig) = @_;
17719:     my @hostingtypes = ('version','excludedomain','includedomain');
17720:     my @offloadtypes = ('primary','default');
17721:     my %types = (
17722:                   remote => \@hostingtypes,
17723:                   hosted => \@hostingtypes,
17724:                   spares => \@offloadtypes,
17725:                 );
17726:     my @prefixes = ('remote','hosted','spares');
17727:     my @lcversions = &Apache::lonnet::all_loncaparevs();
17728:     my (%by_ip,%by_location,@intdoms);
17729:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location);
17730:     my @locations = sort(keys(%by_location));
17731:     my (%defaultshash,%changes);
17732:     foreach my $prefix (@prefixes) {
17733:         $defaultshash{'usersessions'}{$prefix} = {};
17734:     }
17735:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
17736:     my $resulttext;
17737:     my %iphost = &Apache::lonnet::get_iphost();
17738:     foreach my $prefix (@prefixes) {
17739:         next if ($prefix eq 'spares');
17740:         foreach my $type (@{$types{$prefix}}) {
17741:             my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
17742:             if ($type eq 'version') {
17743:                 my $value = $env{'form.'.$prefix.'_'.$type};
17744:                 my $okvalue;
17745:                 if ($value ne '') {
17746:                     if (grep(/^\Q$value\E$/,@lcversions)) {
17747:                         $okvalue = $value;
17748:                     }
17749:                 }
17750:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
17751:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
17752:                         if ($domconfig{'usersessions'}{$prefix}{$type} ne '') {
17753:                             if ($inuse == 0) {
17754:                                 $changes{$prefix}{$type} = 1;
17755:                             } else {
17756:                                 if ($okvalue ne $domconfig{'usersessions'}{$prefix}{$type}) {
17757:                                     $changes{$prefix}{$type} = 1;
17758:                                 }
17759:                                 if ($okvalue ne '') {
17760:                                     $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
17761:                                 } 
17762:                             }
17763:                         } else {
17764:                             if (($inuse == 1) && ($okvalue ne '')) {
17765:                                 $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
17766:                                 $changes{$prefix}{$type} = 1;
17767:                             }
17768:                         }
17769:                     } else {
17770:                         if (($inuse == 1) && ($okvalue ne '')) {
17771:                             $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
17772:                             $changes{$prefix}{$type} = 1;
17773:                         }
17774:                     }
17775:                 } else {
17776:                     if (($inuse == 1) && ($okvalue ne '')) {
17777:                         $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
17778:                         $changes{$prefix}{$type} = 1;
17779:                     }
17780:                 }
17781:             } else {
17782:                 my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
17783:                 my @okvals;
17784:                 foreach my $val (@vals) {
17785:                     if ($val =~ /:/) {
17786:                         my @items = split(/:/,$val);
17787:                         foreach my $item (@items) {
17788:                             if (ref($by_location{$item}) eq 'ARRAY') {
17789:                                 push(@okvals,$item);
17790:                             }
17791:                         }
17792:                     } else {
17793:                         if (ref($by_location{$val}) eq 'ARRAY') {
17794:                             push(@okvals,$val);
17795:                         }
17796:                     }
17797:                 }
17798:                 @okvals = sort(@okvals);
17799:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
17800:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
17801:                         if (ref($domconfig{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
17802:                             if ($inuse == 0) {
17803:                                 $changes{$prefix}{$type} = 1; 
17804:                             } else {
17805:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
17806:                                 my @changed = &Apache::loncommon::compare_arrays($domconfig{'usersessions'}{$prefix}{$type},$defaultshash{'usersessions'}{$prefix}{$type});
17807:                                 if (@changed > 0) {
17808:                                     $changes{$prefix}{$type} = 1;
17809:                                 }
17810:                             }
17811:                         } else {
17812:                             if ($inuse == 1) {
17813:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
17814:                                 $changes{$prefix}{$type} = 1;
17815:                             }
17816:                         } 
17817:                     } else {
17818:                         if ($inuse == 1) {
17819:                             $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
17820:                             $changes{$prefix}{$type} = 1;
17821:                         }
17822:                     }
17823:                 } else {
17824:                     if ($inuse == 1) {
17825:                         $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
17826:                         $changes{$prefix}{$type} = 1;
17827:                     }
17828:                 }
17829:             }
17830:         }
17831:     }
17832: 
17833:     my @alldoms = &Apache::lonnet::all_domains();
17834:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
17835:     my %spareid = &current_offloads_to($dom,$domconfig{'usersessions'},\%servers);
17836:     my $savespares;
17837: 
17838:     foreach my $lonhost (sort(keys(%servers))) {
17839:         my $serverhomeID =
17840:             &Apache::lonnet::get_server_homeID($servers{$lonhost});
17841:         my $serverhostname = &Apache::lonnet::hostname($lonhost);
17842:         $defaultshash{'usersessions'}{'spares'}{$lonhost} = {};
17843:         my %spareschg;
17844:         foreach my $type (@{$types{'spares'}}) {
17845:             my @okspares;
17846:             my @checked = &Apache::loncommon::get_env_multiple('form.spare_'.$type.'_'.$lonhost);
17847:             foreach my $server (@checked) {
17848:                 if (&Apache::lonnet::hostname($server) ne '') {
17849:                     unless (&Apache::lonnet::hostname($server) eq $serverhostname) {
17850:                         unless (grep(/^\Q$server\E$/,@okspares)) {
17851:                             push(@okspares,$server);
17852:                         }
17853:                     }
17854:                 }
17855:             }
17856:             my $new = $env{'form.newspare_'.$type.'_'.$lonhost};
17857:             my $newspare;
17858:             if (($new ne '') && (&Apache::lonnet::hostname($new))) {
17859:                 unless (&Apache::lonnet::hostname($new) eq $serverhostname) {
17860:                     $newspare = $new;
17861:                 }
17862:             }
17863:             my @spares;
17864:             if (($newspare ne '') && (!grep(/^\Q$newspare\E$/,@okspares))) {
17865:                 @spares = sort(@okspares,$newspare);
17866:             } else {
17867:                 @spares = sort(@okspares);
17868:             }
17869:             $defaultshash{'usersessions'}{'spares'}{$lonhost}{$type} = \@spares;
17870:             if (ref($spareid{$lonhost}) eq 'HASH') {
17871:                 if (ref($spareid{$lonhost}{$type}) eq 'ARRAY') {
17872:                     my @diffs = &Apache::loncommon::compare_arrays($spareid{$lonhost}{$type},\@spares);
17873:                     if (@diffs > 0) {
17874:                         $spareschg{$type} = 1;
17875:                     }
17876:                 }
17877:             }
17878:         }
17879:         if (keys(%spareschg) > 0) {
17880:             $changes{'spares'}{$lonhost} = \%spareschg;
17881:         }
17882:     }
17883:     $defaultshash{'usersessions'}{'offloadnow'} = {};
17884:     $defaultshash{'usersessions'}{'offloadoth'} = {};
17885:     my @offloadnow = &Apache::loncommon::get_env_multiple('form.offloadnow');
17886:     my @okoffload;
17887:     if (@offloadnow) {
17888:         foreach my $server (@offloadnow) {
17889:             if (&Apache::lonnet::hostname($server) ne '') {
17890:                 unless (grep(/^\Q$server\E$/,@okoffload)) {
17891:                     push(@okoffload,$server);
17892:                 }
17893:             }
17894:         }
17895:         if (@okoffload) {
17896:             foreach my $lonhost (@okoffload) {
17897:                 $defaultshash{'usersessions'}{'offloadnow'}{$lonhost} = 1;
17898:             }
17899:         }
17900:     }
17901:     my @offloadoth = &Apache::loncommon::get_env_multiple('form.offloadoth');
17902:     my @okoffloadoth;
17903:     if (@offloadoth) {
17904:         foreach my $server (@offloadoth) {
17905:             if (&Apache::lonnet::hostname($server) ne '') {
17906:                 unless (grep(/^\Q$server\E$/,@okoffloadoth)) {
17907:                     push(@okoffloadoth,$server);
17908:                 }
17909:             }
17910:         }
17911:         if (@okoffloadoth) {
17912:             foreach my $lonhost (@okoffloadoth) {
17913:                 $defaultshash{'usersessions'}{'offloadoth'}{$lonhost} = 1;
17914:             }
17915:         }
17916:     }
17917:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
17918:         if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
17919:             if (ref($changes{'spares'}) eq 'HASH') {
17920:                 if (keys(%{$changes{'spares'}}) > 0) {
17921:                     $savespares = 1;
17922:                 }
17923:             }
17924:         } else {
17925:             $savespares = 1;
17926:         }
17927:         foreach my $offload ('offloadnow','offloadoth') {
17928:             if (ref($domconfig{'usersessions'}{$offload}) eq 'HASH') {
17929:                 foreach my $lonhost (keys(%{$domconfig{'usersessions'}{$offload}})) {
17930:                     unless ($defaultshash{'usersessions'}{$offload}{$lonhost}) {
17931:                         $changes{$offload} = 1;
17932:                         last;
17933:                     }
17934:                 }
17935:                 unless ($changes{$offload}) {
17936:                     foreach my $lonhost (keys(%{$defaultshash{'usersessions'}{$offload}})) {
17937:                         unless ($domconfig{'usersessions'}{$offload}{$lonhost}) {
17938:                             $changes{$offload} = 1;
17939:                             last;
17940:                         }
17941:                     }
17942:                 }
17943:             } else {
17944:                 if (($offload eq 'offloadnow') && (@okoffload)) {
17945:                      $changes{'offloadnow'} = 1;
17946:                 }
17947:                 if (($offload eq 'offloadoth') && (@okoffloadoth)) {
17948:                     $changes{'offloadoth'} = 1;
17949:                 }
17950:             }
17951:         }
17952:     } else {
17953:         if (@okoffload) {
17954:             $changes{'offloadnow'} = 1;
17955:         }
17956:         if (@okoffloadoth) {
17957:             $changes{'offloadoth'} = 1;
17958:         }
17959:     }
17960:     my $nochgmsg = &mt('No changes made to settings for user session hosting/offloading.');
17961:     if ((keys(%changes) > 0) || ($savespares)) {
17962:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
17963:                                                  $dom);
17964:         if ($putresult eq 'ok') {
17965:             if (ref($defaultshash{'usersessions'}) eq 'HASH') {
17966:                 if (ref($defaultshash{'usersessions'}{'remote'}) eq 'HASH') {
17967:                     $domdefaults{'remotesessions'} = $defaultshash{'usersessions'}{'remote'};
17968:                 }
17969:                 if (ref($defaultshash{'usersessions'}{'hosted'}) eq 'HASH') {
17970:                     $domdefaults{'hostedsessions'} = $defaultshash{'usersessions'}{'hosted'};
17971:                 }
17972:                 if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
17973:                     $domdefaults{'offloadnow'} = $defaultshash{'usersessions'}{'offloadnow'};
17974:                 }
17975:                 if (ref($defaultshash{'usersessions'}{'offloadoth'}) eq 'HASH') {
17976:                     $domdefaults{'offloadoth'} = $defaultshash{'usersessions'}{'offloadoth'};
17977:                 }
17978:             }
17979:             my $cachetime = 24*60*60;
17980:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
17981:             &Apache::lonnet::do_cache_new('usersessions',$dom,$defaultshash{'usersessions'},3600);
17982:             if (ref($lastactref) eq 'HASH') {
17983:                 $lastactref->{'domdefaults'} = 1;
17984:                 $lastactref->{'usersessions'} = 1;
17985:             }
17986:             if (keys(%changes) > 0) {
17987:                 my %lt = &usersession_titles();
17988:                 $resulttext = &mt('Changes made:').'<ul>';
17989:                 foreach my $prefix (@prefixes) {
17990:                     if (ref($changes{$prefix}) eq 'HASH') {
17991:                         $resulttext .= '<li>'.$lt{$prefix}.'<ul>';
17992:                         if ($prefix eq 'spares') {
17993:                             if (ref($changes{$prefix}) eq 'HASH') {
17994:                                 foreach my $lonhost (sort(keys(%{$changes{$prefix}}))) {
17995:                                     $resulttext .= '<li><b>'.$lonhost.'</b> ';
17996:                                     my $lonhostdom = &Apache::lonnet::host_domain($lonhost);
17997:                                     my $cachekey = &escape('spares').':'.&escape($lonhostdom);
17998:                                     &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
17999:                                     if (ref($changes{$prefix}{$lonhost}) eq 'HASH') {
18000:                                         foreach my $type (@{$types{$prefix}}) {
18001:                                             if ($changes{$prefix}{$lonhost}{$type}) {
18002:                                                 my $offloadto = &mt('None');
18003:                                                 if (ref($defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}) eq 'ARRAY') {
18004:                                                     if (@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}} > 0) {   
18005:                                                         $offloadto = join(', ',@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}});
18006:                                                     }
18007:                                                 }
18008:                                                 $resulttext .= &mt('[_1] set to: [_2].','<i>'.$lt{$type}.'</i>',$offloadto).('&nbsp;'x3);
18009:                                             }
18010:                                         }
18011:                                     }
18012:                                     $resulttext .= '</li>';
18013:                                 }
18014:                             }
18015:                         } else {
18016:                             foreach my $type (@{$types{$prefix}}) {
18017:                                 if (defined($changes{$prefix}{$type})) {
18018:                                     my $newvalue;
18019:                                     if (ref($defaultshash{'usersessions'}) eq 'HASH') {
18020:                                         if (ref($defaultshash{'usersessions'}{$prefix})) {
18021:                                             if ($type eq 'version') {
18022:                                                 $newvalue = $defaultshash{'usersessions'}{$prefix}{$type};
18023:                                             } elsif (ref($defaultshash{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
18024:                                                 if (@{$defaultshash{'usersessions'}{$prefix}{$type}} > 0) {
18025:                                                     $newvalue = join(', ',@{$defaultshash{'usersessions'}{$prefix}{$type}});
18026:                                                 }
18027:                                             }
18028:                                         }
18029:                                     }
18030:                                     if ($newvalue eq '') {
18031:                                         if ($type eq 'version') {
18032:                                             $resulttext .= '<li>'.&mt('[_1] set to: off',$lt{$type}).'</li>';
18033:                                         } else {
18034:                                             $resulttext .= '<li>'.&mt('[_1] set to: none',$lt{$type}).'</li>';
18035:                                         }
18036:                                     } else {
18037:                                         if ($type eq 'version') {
18038:                                             $newvalue .= ' '.&mt('(or later)'); 
18039:                                         }
18040:                                         $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$lt{$type},$newvalue).'</li>';
18041:                                     }
18042:                                 }
18043:                             }
18044:                         }
18045:                         $resulttext .= '</ul>';
18046:                     }
18047:                 }
18048:                 if ($changes{'offloadnow'}) {
18049:                     if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
18050:                         if (keys(%{$defaultshash{'usersessions'}{'offloadnow'}}) > 0) {
18051:                             $resulttext .= '<li>'.&mt('Switch any active user on next access, for server(s):').'<ul>';
18052:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadnow'}}))) {
18053:                                 $resulttext .= '<li>'.$lonhost.'</li>';
18054:                             }
18055:                             $resulttext .= '</ul>';
18056:                         } else {
18057:                             $resulttext .= '<li>'.&mt('No servers now set to switch any active user on next access.');
18058:                         }
18059:                     } else {
18060:                         $resulttext .= '<li>'.&mt('No servers now set to switch any active user on next access.').'</li>';
18061:                     }
18062:                 }
18063:                 if ($changes{'offloadoth'}) {
18064:                     if (ref($defaultshash{'usersessions'}{'offloadoth'}) eq 'HASH') {
18065:                         if (keys(%{$defaultshash{'usersessions'}{'offloadoth'}}) > 0) {
18066:                             $resulttext .= '<li>'.&mt('Switch other institutions on next access, for server(s):').'<ul>';
18067:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadoth'}}))) {
18068:                                 $resulttext .= '<li>'.$lonhost.'</li>';
18069:                             }
18070:                             $resulttext .= '</ul>';
18071:                         } else {
18072:                             $resulttext .= '<li>'.&mt('No servers now set to switch other institutions on next access.');
18073:                         }
18074:                     } else {
18075:                         $resulttext .= '<li>'.&mt('No servers now set to switch other institutions on next access.').'</li>';
18076:                     }
18077:                 }
18078:                 $resulttext .= '</ul>';
18079:             } else {
18080:                 $resulttext = $nochgmsg;
18081:             }
18082:         } else {
18083:             $resulttext = '<span class="LC_error">'.
18084:                           &mt('An error occurred: [_1]',$putresult).'</span>';
18085:         }
18086:     } else {
18087:         $resulttext = $nochgmsg;
18088:     }
18089:     return $resulttext;
18090: }
18091: 
18092: sub modify_loadbalancing {
18093:     my ($dom,%domconfig) = @_;
18094:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
18095:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
18096:     my ($othertitle,$usertypes,$types) =
18097:         &Apache::loncommon::sorted_inst_types($dom);
18098:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
18099:     my %libraryservers = &Apache::lonnet::get_servers($dom,'library');
18100:     my @sparestypes = ('primary','default');
18101:     my %typetitles = &sparestype_titles();
18102:     my $resulttext;
18103:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
18104:     if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
18105:         %existing = %{$domconfig{'loadbalancing'}};
18106:     }
18107:     &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
18108:                               \%currtargets,\%currrules,\%currcookies);
18109:     my ($saveloadbalancing,%defaultshash,%changes);
18110:     my ($alltypes,$othertypes,$titles) =
18111:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
18112:     my %ruletitles = &offloadtype_text();
18113:     my @deletions = &Apache::loncommon::get_env_multiple('form.loadbalancing_delete');
18114:     for (my $i=0; $i<$env{'form.loadbalancing_total'}; $i++) {
18115:         my $balancer = $env{'form.loadbalancing_lonhost_'.$i};
18116:         if ($balancer eq '') {
18117:             next;
18118:         }
18119:         if (!exists($servers{$balancer})) {
18120:             if (exists($currbalancer{$balancer})) {
18121:                 push(@{$changes{'delete'}},$balancer);
18122:             }
18123:             next;
18124:         }
18125:         if ((@deletions > 0) && (grep(/^\Q$i\E$/,@deletions))) {
18126:             push(@{$changes{'delete'}},$balancer);
18127:             next;
18128:         }
18129:         if (!exists($currbalancer{$balancer})) {
18130:             push(@{$changes{'add'}},$balancer);
18131:         }
18132:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'} = [];
18133:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'default'} = [];
18134:         $defaultshash{'loadbalancing'}{$balancer}{'rules'} = {};
18135:         unless (ref($domconfig{'loadbalancing'}) eq 'HASH') {
18136:             $saveloadbalancing = 1;
18137:         }
18138:         foreach my $sparetype (@sparestypes) {
18139:             my @targets = &Apache::loncommon::get_env_multiple('form.loadbalancing_target_'.$i.'_'.$sparetype);
18140:             my @offloadto;
18141:             foreach my $target (@targets) {
18142:                 if (($servers{$target}) && ($target ne $balancer)) {
18143:                     if ($sparetype eq 'default') {
18144:                         if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}) eq 'ARRAY') {
18145:                             next if (grep(/^\Q$target\E$/,@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}}));
18146:                         }
18147:                     }
18148:                     unless(grep(/^\Q$target\E$/,@offloadto)) {
18149:                         push(@offloadto,$target);
18150:                     }
18151:                 }
18152:             }
18153:             if ($env{'form.loadbalancing_target_'.$i.'_hosthere'} eq $sparetype) {
18154:                 unless(grep(/^\Q$balancer\E$/,@offloadto)) {
18155:                     push(@offloadto,$balancer);
18156:                 }
18157:             }
18158:             $defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype} = \@offloadto;
18159:         }
18160:         if ($env{'form.loadbalancing_cookie_'.$i}) {
18161:             $defaultshash{'loadbalancing'}{$balancer}{'cookie'} = 1;
18162:             if (exists($currbalancer{$balancer})) {
18163:                 unless ($currcookies{$balancer}) {
18164:                     $changes{'curr'}{$balancer}{'cookie'} = 1;
18165:                 }
18166:             }
18167:         } elsif (exists($currbalancer{$balancer})) {
18168:             if ($currcookies{$balancer}) {
18169:                 $changes{'curr'}{$balancer}{'cookie'} = 1;
18170:             }
18171:         }
18172:         if (ref($currtargets{$balancer}) eq 'HASH') {
18173:             foreach my $sparetype (@sparestypes) {
18174:                 if (ref($currtargets{$balancer}{$sparetype}) eq 'ARRAY') {
18175:                     my @targetdiffs = &Apache::loncommon::compare_arrays($currtargets{$balancer}{$sparetype},$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype});
18176:                     if (@targetdiffs > 0) {
18177:                         $changes{'curr'}{$balancer}{'targets'} = 1;
18178:                     }
18179:                 } elsif (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
18180:                     if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
18181:                         $changes{'curr'}{$balancer}{'targets'} = 1;
18182:                     }
18183:                 }
18184:             }
18185:         } else {
18186:             if (ref($defaultshash{'loadbalancing'}{$balancer}) eq 'HASH') {
18187:                 foreach my $sparetype (@sparestypes) {
18188:                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
18189:                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
18190:                             $changes{'curr'}{$balancer}{'targets'} = 1;
18191:                         }
18192:                     }
18193:                 }
18194:             }
18195:         }
18196:         my $ishomedom;
18197:         if (&Apache::lonnet::host_domain($balancer) eq $dom) {
18198:             $ishomedom = 1;
18199:         }
18200:         if (ref($alltypes) eq 'ARRAY') {
18201:             foreach my $type (@{$alltypes}) {
18202:                 my $rule;
18203:                 unless ((($type eq '_LC_external') || ($type eq '_LC_internetdom')) &&
18204:                          (!$ishomedom)) {
18205:                     $rule = $env{'form.loadbalancing_rules_'.$i.'_'.$type};
18206:                 }
18207:                 if ($rule eq 'specific') {
18208:                     my $specifiedhost = $env{'form.loadbalancing_singleserver_'.$i.'_'.$type};
18209:                     if (exists($servers{$specifiedhost})) {
18210:                         $rule = $specifiedhost;
18211:                     }
18212:                 }
18213:                 $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type} = $rule;
18214:                 if (ref($currrules{$balancer}) eq 'HASH') {
18215:                     if ($rule ne $currrules{$balancer}{$type}) {
18216:                         $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
18217:                     }
18218:                 } elsif ($rule ne '') {
18219:                     $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
18220:                 }
18221:             }
18222:         }
18223:     }
18224:     my $nochgmsg = &mt('No changes made to Load Balancer settings.');
18225:     if ((keys(%changes) > 0) || ($saveloadbalancing)) {
18226:         unless (ref($defaultshash{'loadbalancing'}) eq 'HASH') {
18227:             $defaultshash{'loadbalancing'} = {};
18228:         }
18229:         my $putresult = &Apache::lonnet::put_dom('configuration',
18230:                                                  \%defaultshash,$dom);
18231:         if ($putresult eq 'ok') {
18232:             if (keys(%changes) > 0) {
18233:                 my %toupdate;
18234:                 if (ref($changes{'delete'}) eq 'ARRAY') {
18235:                     foreach my $balancer (sort(@{$changes{'delete'}})) {
18236:                         $resulttext .= '<li>'.&mt('Load Balancing discontinued for: [_1]',$balancer).'</li>';
18237:                         $toupdate{$balancer} = 1;
18238:                     }
18239:                 }
18240:                 if (ref($changes{'add'}) eq 'ARRAY') {
18241:                     foreach my $balancer (sort(@{$changes{'add'}})) {
18242:                         $resulttext .= '<li>'.&mt('Load Balancing enabled for: [_1]',$balancer);
18243:                         $toupdate{$balancer} = 1;
18244:                     }
18245:                 }
18246:                 if (ref($changes{'curr'}) eq 'HASH') {
18247:                     foreach my $balancer (sort(keys(%{$changes{'curr'}}))) {
18248:                         $toupdate{$balancer} = 1;
18249:                         if (ref($changes{'curr'}{$balancer}) eq 'HASH') {
18250:                             if ($changes{'curr'}{$balancer}{'targets'}) {
18251:                                 my %offloadstr;
18252:                                 foreach my $sparetype (@sparestypes) {
18253:                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
18254:                                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
18255:                                             $offloadstr{$sparetype} = join(', ',@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
18256:                                         }
18257:                                     }
18258:                                 }
18259:                                 if (keys(%offloadstr) == 0) {
18260:                                     $resulttext .= '<li>'.&mt("Servers to which Load Balance server offloads set to 'None', by default").'</li>';
18261:                                 } else {
18262:                                     my $showoffload;
18263:                                     foreach my $sparetype (@sparestypes) {
18264:                                         $showoffload .= '<i>'.$typetitles{$sparetype}.'</i>:&nbsp;';
18265:                                         if (defined($offloadstr{$sparetype})) {
18266:                                             $showoffload .= $offloadstr{$sparetype};
18267:                                         } else {
18268:                                             $showoffload .= &mt('None');
18269:                                         }
18270:                                         $showoffload .= ('&nbsp;'x3);
18271:                                     }
18272:                                     $resulttext .= '<li>'.&mt('By default, Load Balancer: [_1] set to offload to - [_2]',$balancer,$showoffload).'</li>';
18273:                                 }
18274:                             }
18275:                         }
18276:                         if (ref($changes{'curr'}{$balancer}{'rules'}) eq 'HASH') {
18277:                             if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH')) {
18278:                                 foreach my $type (@{$alltypes}) {
18279:                                     if ($changes{'curr'}{$balancer}{'rules'}{$type}) {
18280:                                         my $rule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
18281:                                         my $balancetext;
18282:                                         if ($rule eq '') {
18283:                                             $balancetext =  $ruletitles{'default'};
18284:                                         } elsif (($rule eq 'homeserver') || ($rule eq 'externalbalancer') ||
18285:                                                  ($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
18286:                                             if (($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
18287:                                                 foreach my $sparetype (@sparestypes) {
18288:                                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
18289:                                                         map { $toupdate{$_} = 1; } (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
18290:                                                     }
18291:                                                 }
18292:                                                 foreach my $item (@{$alltypes}) {
18293:                                                     next if ($item =~  /^_LC_ipchange/);
18294:                                                     my $hasrule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$item};
18295:                                                     if ($hasrule eq 'homeserver') {
18296:                                                         map { $toupdate{$_} = 1; } (keys(%libraryservers));
18297:                                                     } else {
18298:                                                         unless (($hasrule eq 'default') || ($hasrule eq 'none') || ($hasrule eq 'externalbalancer')) {
18299:                                                             if ($servers{$hasrule}) {
18300:                                                                 $toupdate{$hasrule} = 1;
18301:                                                             }
18302:                                                         }
18303:                                                     }
18304:                                                 }
18305:                                                 if (($rule eq 'balancer') || ($rule eq 'offloadedto')) {
18306:                                                     $balancetext =  $ruletitles{$rule};
18307:                                                 } else {
18308:                                                     my $receiver = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
18309:                                                     $balancetext = $ruletitles{'particular'}.' '.$receiver;
18310:                                                     if ($receiver) {
18311:                                                         $toupdate{$receiver};
18312:                                                     }
18313:                                                 }
18314:                                             } else {
18315:                                                 $balancetext =  $ruletitles{$rule};
18316:                                             }
18317:                                         } else {
18318:                                             $balancetext = &mt('offload to [_1]',$defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type});
18319:                                         }
18320:                                         $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- balancing for [_2] set to - "[_3]"',$balancer,$titles->{$type},$balancetext).'</li>';
18321:                                     }
18322:                                 }
18323:                             }
18324:                         }
18325:                         if ($changes{'curr'}{$balancer}{'cookie'}) {
18326:                             if ($currcookies{$balancer}) {
18327:                                 $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- cookie use disabled',
18328:                                                           $balancer).'</li>';
18329:                             } else {
18330:                                 $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- cookie use enabled',
18331:                                                           $balancer).'</li>';
18332:                             }
18333:                         }
18334:                     }
18335:                 }
18336:                 if (keys(%toupdate)) {
18337:                     my %thismachine;
18338:                     my $updatedhere;
18339:                     my $cachetime = 60*60*24;
18340:                     map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
18341:                     foreach my $lonhost (keys(%toupdate)) {
18342:                         if ($thismachine{$lonhost}) {
18343:                             unless ($updatedhere) {
18344:                                 &Apache::lonnet::do_cache_new('loadbalancing',$dom,
18345:                                                               $defaultshash{'loadbalancing'},
18346:                                                               $cachetime);
18347:                                 $updatedhere = 1;
18348:                             }
18349:                         } else {
18350:                             my $cachekey = &escape('loadbalancing').':'.&escape($dom);
18351:                             &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
18352:                         }
18353:                     }
18354:                 }
18355:                 if ($resulttext ne '') {
18356:                     $resulttext = &mt('Changes made:').'<ul>'.$resulttext.'</ul>';
18357:                 } else {
18358:                     $resulttext = $nochgmsg;
18359:                 }
18360:             } else {
18361:                 $resulttext = $nochgmsg;
18362:             }
18363:         } else {
18364:             $resulttext = '<span class="LC_error">'.
18365:                           &mt('An error occurred: [_1]',$putresult).'</span>';
18366:         }
18367:     } else {
18368:         $resulttext = $nochgmsg;
18369:     }
18370:     return $resulttext;
18371: }
18372: 
18373: sub recurse_check {
18374:     my ($chkcats,$categories,$depth,$name) = @_;
18375:     if (ref($chkcats->[$depth]{$name}) eq 'ARRAY') {
18376:         my $chg = 0;
18377:         for (my $j=0; $j<@{$chkcats->[$depth]{$name}}; $j++) {
18378:             my $category = $chkcats->[$depth]{$name}[$j];
18379:             my $item;
18380:             if ($category eq '') {
18381:                 $chg ++;
18382:             } else {
18383:                 my $deeper = $depth + 1;
18384:                 $item = &escape($category).':'.&escape($name).':'.$depth;
18385:                 if ($chg) {
18386:                     $categories->{$item} -= $chg;
18387:                 }
18388:                 &recurse_check($chkcats,$categories,$deeper,$category);
18389:                 $deeper --;
18390:             }
18391:         }
18392:     }
18393:     return;
18394: }
18395: 
18396: sub recurse_cat_deletes {
18397:     my ($item,$coursecategories,$deletions) = @_;
18398:     my ($deleted,$container,$depth) = map { &unescape($_); } split(/:/,$item);
18399:     my $subdepth = $depth + 1;
18400:     if (ref($coursecategories) eq 'HASH') {
18401:         foreach my $subitem (keys(%{$coursecategories})) {
18402:             my ($child,$parent,$itemdepth) = map { &unescape($_); } split(/:/,$subitem);
18403:             if (($parent eq $deleted) && ($itemdepth == $subdepth)) {
18404:                 delete($coursecategories->{$subitem});
18405:                 $deletions->{$subitem} = 1;
18406:                 &recurse_cat_deletes($subitem,$coursecategories,$deletions);
18407:             }
18408:         }
18409:     }
18410:     return;
18411: }
18412: 
18413: sub active_dc_picker {
18414:     my ($dom,$numinrow,$inputtype,$name,%currhash) = @_;
18415:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
18416:     my @domcoord = keys(%domcoords);
18417:     if (keys(%currhash)) {
18418:         foreach my $dc (keys(%currhash)) {
18419:             unless (exists($domcoords{$dc})) {
18420:                 push(@domcoord,$dc);
18421:             }
18422:         }
18423:     }
18424:     @domcoord = sort(@domcoord);
18425:     my $numdcs = scalar(@domcoord);
18426:     my $rows = 0;
18427:     my $table;
18428:     if ($numdcs > 1) {
18429:         $table = '<table>';
18430:         for (my $i=0; $i<@domcoord; $i++) {
18431:             my $rem = $i%($numinrow);
18432:             if ($rem == 0) {
18433:                 if ($i > 0) {
18434:                     $table .= '</tr>';
18435:                 }
18436:                 $table .= '<tr>';
18437:                 $rows ++;
18438:             }
18439:             my $check = '';
18440:             if ($inputtype eq 'radio') {
18441:                 if (keys(%currhash) == 0) {
18442:                     if (!$i) {
18443:                         $check = ' checked="checked"';
18444:                     }
18445:                 } elsif (exists($currhash{$domcoord[$i]})) {
18446:                     $check = ' checked="checked"';
18447:                 }
18448:             } else {
18449:                 if (exists($currhash{$domcoord[$i]})) {
18450:                     $check = ' checked="checked"';
18451:                 }
18452:             }
18453:             if ($i == @domcoord - 1) {
18454:                 my $colsleft = $numinrow - $rem;
18455:                 if ($colsleft > 1) {
18456:                     $table .= '<td class="LC_left_item" colspan="'.$colsleft.'">';
18457:                 } else {
18458:                     $table .= '<td class="LC_left_item">';
18459:                 }
18460:             } else {
18461:                 $table .= '<td class="LC_left_item">';
18462:             }
18463:             my ($dcname,$dcdom) = split(':',$domcoord[$i]);
18464:             my $user = &Apache::loncommon::plainname($dcname,$dcdom);
18465:             $table .= '<span class="LC_nobreak"><label>'.
18466:                       '<input type="'.$inputtype.'" name="'.$name.'"'.
18467:                       ' value="'.$domcoord[$i].'"'.$check.' />'.$user;
18468:             if ($user ne $dcname.':'.$dcdom) {
18469:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
18470:             }
18471:             $table .= '</label></span></td>';
18472:         }
18473:         $table .= '</tr></table>';
18474:     } elsif ($numdcs == 1) {
18475:         my ($dcname,$dcdom) = split(':',$domcoord[0]);
18476:         my $user = &Apache::loncommon::plainname($dcname,$dcdom);
18477:         if ($inputtype eq 'radio') {
18478:             $table = '<input type="hidden" name="'.$name.'" value="'.$domcoord[0].'" />'.$user;
18479:             if ($user ne $dcname.':'.$dcdom) {
18480:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
18481:             }
18482:         } else {
18483:             my $check;
18484:             if (exists($currhash{$domcoord[0]})) {
18485:                 $check = ' checked="checked"';
18486:             }
18487:             $table = '<span class="LC_nobreak"><label>'.
18488:                      '<input type="checkbox" name="'.$name.'" '.
18489:                      'value="'.$domcoord[0].'"'.$check.' />'.$user;
18490:             if ($user ne $dcname.':'.$dcdom) {
18491:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
18492:             }
18493:             $table .= '</label></span>';
18494:             $rows ++;
18495:         }
18496:     }
18497:     return ($numdcs,$table,$rows);
18498: }
18499: 
18500: sub usersession_titles {
18501:     return &Apache::lonlocal::texthash(
18502:                hosted => 'Hosting of sessions for users from other domains on servers in this domain',
18503:                remote => 'Hosting of sessions for users in this domain on servers in other domains',
18504:                spares => 'Servers offloaded to, when busy',
18505:                version => 'LON-CAPA version requirement',
18506:                excludedomain => 'Allow all, but exclude specific domains',
18507:                includedomain => 'Deny all, but include specific domains',
18508:                primary => 'Primary (checked first)',
18509:                default => 'Default',
18510:            );
18511: }
18512: 
18513: sub id_for_thisdom {
18514:     my (%servers) = @_;
18515:     my %altids;
18516:     foreach my $server (keys(%servers)) {
18517:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
18518:         if ($serverhome ne $server) {
18519:             $altids{$serverhome} = $server;
18520:         }
18521:     }
18522:     return %altids;
18523: }
18524: 
18525: sub count_servers {
18526:     my ($currbalancer,%servers) = @_;
18527:     my (@spares,$numspares);
18528:     foreach my $lonhost (sort(keys(%servers))) {
18529:         next if ($currbalancer eq $lonhost);
18530:         push(@spares,$lonhost);
18531:     }
18532:     if ($currbalancer) {
18533:         $numspares = scalar(@spares);
18534:     } else {
18535:         $numspares = scalar(@spares) - 1;
18536:     }
18537:     return ($numspares,@spares);
18538: }
18539: 
18540: sub lonbalance_targets_js {
18541:     my ($dom,$types,$servers,$settings) = @_;
18542:     my $select = &mt('Select');
18543:     my ($alltargets,$allishome,$allinsttypes,@alltypes);
18544:     if (ref($servers) eq 'HASH') {
18545:         $alltargets = join("','",sort(keys(%{$servers})));
18546:         my @homedoms;
18547:         foreach my $server (sort(keys(%{$servers}))) {
18548:             if (&Apache::lonnet::host_domain($server) eq $dom) {
18549:                 push(@homedoms,'1');
18550:             } else {
18551:                 push(@homedoms,'0');
18552:             }
18553:         }
18554:         $allishome = join("','",@homedoms);
18555:     }
18556:     if (ref($types) eq 'ARRAY') {
18557:         if (@{$types} > 0) {
18558:             @alltypes = @{$types};
18559:         }
18560:     }
18561:     push(@alltypes,'default','_LC_adv','_LC_author','_LC_internetdom','_LC_external');
18562:     $allinsttypes = join("','",@alltypes);
18563:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
18564:     if (ref($settings) eq 'HASH') {
18565:         %existing = %{$settings};
18566:     }
18567:     &get_loadbalancers_config($servers,\%existing,\%currbalancer,
18568:                               \%currtargets,\%currrules,\%currcookies);
18569:     my $balancers = join("','",sort(keys(%currbalancer)));
18570:     return <<"END";
18571: 
18572: <script type="text/javascript">
18573: // <![CDATA[
18574: 
18575: currBalancers = new Array('$balancers');
18576: 
18577: function toggleTargets(balnum) {
18578:     var lonhostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
18579:     var prevhostitem = document.getElementById('loadbalancing_prevlonhost_'+balnum);
18580:     var balancer = lonhostitem.options[lonhostitem.selectedIndex].value;
18581:     var prevbalancer = prevhostitem.value;
18582:     var baltotal = document.getElementById('loadbalancing_total').value;
18583:     prevhostitem.value = balancer;
18584:     if (prevbalancer != '') {
18585:         var prevIdx = currBalancers.indexOf(prevbalancer);
18586:         if (prevIdx != -1) {
18587:             currBalancers.splice(prevIdx,1);
18588:         }
18589:     }
18590:     if (balancer == '') {
18591:         hideSpares(balnum);
18592:     } else {
18593:         var currIdx = currBalancers.indexOf(balancer);
18594:         if (currIdx == -1) {
18595:             currBalancers.push(balancer);
18596:         }
18597:         var homedoms = new Array('$allishome');
18598:         var ishomedom = homedoms[lonhostitem.selectedIndex];
18599:         showSpares(balancer,ishomedom,balnum);
18600:     }
18601:     balancerChange(balnum,baltotal,'change',prevbalancer,balancer);
18602:     return;
18603: }
18604: 
18605: function showSpares(balancer,ishomedom,balnum) {
18606:     var alltargets = new Array('$alltargets');
18607:     var insttypes = new Array('$allinsttypes');
18608:     var offloadtypes = new Array('primary','default');
18609: 
18610:     document.getElementById('loadbalancing_targets_'+balnum).style.display='block';
18611:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='none';
18612:  
18613:     for (var i=0; i<offloadtypes.length; i++) {
18614:         var count = 0;
18615:         for (var j=0; j<alltargets.length; j++) {
18616:             if (alltargets[j] != balancer) {
18617:                 var item = document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+count);
18618:                 item.value = alltargets[j];
18619:                 item.style.textAlign='left';
18620:                 item.style.textFace='normal';
18621:                 document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+count).innerHTML = alltargets[j];
18622:                 if (currBalancers.indexOf(alltargets[j]) == -1) {
18623:                     item.disabled = '';
18624:                 } else {
18625:                     item.disabled = 'disabled';
18626:                     item.checked = false;
18627:                 }
18628:                 count ++;
18629:             }
18630:         }
18631:     }
18632:     for (var k=0; k<insttypes.length; k++) {
18633:         if ((insttypes[k] == '_LC_external') || (insttypes[k] == '_LC_internetdom')) {
18634:             if (ishomedom == 1) {
18635:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
18636:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
18637:             } else {
18638:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
18639:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
18640:             }
18641:         } else {
18642:             document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
18643:             document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
18644:         }
18645:         if ((insttypes[k] != '_LC_external') && 
18646:             ((insttypes[k] != '_LC_internetdom') ||
18647:              ((insttypes[k] == '_LC_internetdom') && (ishomedom == 1)))) {
18648:             var item = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]);
18649:             item.options.length = 0;
18650:             item.options[0] = new Option("","",true,true);
18651:             var idx = 0;
18652:             for (var m=0; m<alltargets.length; m++) {
18653:                 if ((currBalancers.indexOf(alltargets[m]) == -1) && (alltargets[m] != balancer)) {
18654:                     idx ++;
18655:                     item.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
18656:                 }
18657:             }
18658:         }
18659:     }
18660:     return;
18661: }
18662: 
18663: function hideSpares(balnum) {
18664:     var alltargets = new Array('$alltargets');
18665:     var insttypes = new Array('$allinsttypes');
18666:     var offloadtypes = new Array('primary','default');
18667: 
18668:     document.getElementById('loadbalancing_targets_'+balnum).style.display='none';
18669:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='block';
18670: 
18671:     var total = alltargets.length - 1;
18672:     for (var i=0; i<offloadtypes; i++) {
18673:         for (var j=0; j<total; j++) {
18674:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).checked = false;
18675:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).value = '';
18676:            document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+j).innerHTML = '';
18677:         }
18678:     }
18679:     for (var k=0; k<insttypes.length; k++) {
18680:         document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
18681:         document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
18682:         if (insttypes[k] != '_LC_external') {
18683:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).length = 0;
18684:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).options[0] = new Option("","",true,true);
18685:         }
18686:     }
18687:     return;
18688: }
18689: 
18690: function checkOffloads(item,balnum,type) {
18691:     var alltargets = new Array('$alltargets');
18692:     var offloadtypes = new Array('primary','default');
18693:     if (item.checked) {
18694:         var total = alltargets.length - 1;
18695:         var other;
18696:         if (type == offloadtypes[0]) {
18697:             other = offloadtypes[1];
18698:         } else {
18699:             other = offloadtypes[0];
18700:         }
18701:         for (var i=0; i<total; i++) {
18702:             var server = document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).value;
18703:             if (server == item.value) {
18704:                 if (document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked) {
18705:                     document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked = false;
18706:                 }
18707:             }
18708:         }
18709:     }
18710:     return;
18711: }
18712: 
18713: function singleServerToggle(balnum,type) {
18714:     var offloadtoSelIdx = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex;
18715:     if (offloadtoSelIdx == 0) {
18716:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_0').checked = true;
18717:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
18718: 
18719:     } else {
18720:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_2').checked = true;
18721:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
18722:     }
18723:     return;
18724: }
18725: 
18726: function balanceruleChange(formname,balnum,type) {
18727:     if (type == '_LC_external') {
18728:         return;
18729:     }
18730:     var typesRules = getIndicesByName(formname,'loadbalancing_rules_'+balnum+'_'+type);
18731:     for (var i=0; i<typesRules.length; i++) {
18732:         if (formname.elements[typesRules[i]].checked) {
18733:             if (formname.elements[typesRules[i]].value != 'specific') {
18734:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex = 0;
18735:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
18736:             } else {
18737:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
18738:             }
18739:         }
18740:     }
18741:     return;
18742: }
18743: 
18744: function balancerDeleteChange(balnum) {
18745:     var hostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
18746:     var baltotal = document.getElementById('loadbalancing_total').value;
18747:     var addtarget;
18748:     var removetarget;
18749:     var action = 'delete';
18750:     if (document.getElementById('loadbalancing_delete_'+balnum)) {
18751:         var lonhost = hostitem.value;
18752:         var currIdx = currBalancers.indexOf(lonhost);
18753:         if (document.getElementById('loadbalancing_delete_'+balnum).checked) {
18754:             if (currIdx != -1) {
18755:                 currBalancers.splice(currIdx,1);
18756:             }
18757:             addtarget = lonhost;
18758:         } else {
18759:             if (currIdx == -1) {
18760:                 currBalancers.push(lonhost);
18761:             }
18762:             removetarget = lonhost;
18763:             action = 'undelete';
18764:         }
18765:         balancerChange(balnum,baltotal,action,addtarget,removetarget);
18766:     }
18767:     return;
18768: }
18769: 
18770: function balancerChange(balnum,baltotal,action,addtarget,removetarget) {
18771:     if (baltotal > 1) {
18772:         var offloadtypes = new Array('primary','default');
18773:         var alltargets = new Array('$alltargets');
18774:         var insttypes = new Array('$allinsttypes');
18775:         for (var i=0; i<baltotal; i++) {
18776:             if (i != balnum) {
18777:                 for (var j=0; j<offloadtypes.length; j++) {
18778:                     var total = alltargets.length - 1;
18779:                     for (var k=0; k<total; k++) {
18780:                         var serveritem = document.getElementById('loadbalancing_target_'+i+'_'+offloadtypes[j]+'_'+k);
18781:                         var server = serveritem.value;
18782:                         if ((action == 'delete') || (action == 'change' && addtarget != ''))  {
18783:                             if (server == addtarget) {
18784:                                 serveritem.disabled = '';
18785:                             }
18786:                         }
18787:                         if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
18788:                             if (server == removetarget) {
18789:                                 serveritem.disabled = 'disabled';
18790:                                 serveritem.checked = false;
18791:                             }
18792:                         }
18793:                     }
18794:                 }
18795:                 for (var j=0; j<insttypes.length; j++) {
18796:                     if (insttypes[j] != '_LC_external') {
18797:                         if (document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j])) {
18798:                             var singleserver = document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j]);
18799:                             var currSel = singleserver.selectedIndex;
18800:                             var currVal = singleserver.options[currSel].value;
18801:                             if ((action == 'delete') || (action == 'change' && addtarget != '')) {
18802:                                 var numoptions = singleserver.options.length;
18803:                                 var needsnew = 1;
18804:                                 for (var k=0; k<numoptions; k++) {
18805:                                     if (singleserver.options[k] == addtarget) {
18806:                                         needsnew = 0;
18807:                                         break;
18808:                                     }
18809:                                 }
18810:                                 if (needsnew == 1) {
18811:                                     singleserver.options[numoptions] = new Option(addtarget,addtarget,false,false);
18812:                                 }
18813:                             }
18814:                             if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
18815:                                 singleserver.options.length = 0;
18816:                                 if ((currVal) && (currVal != removetarget)) {
18817:                                     singleserver.options[0] = new Option("","",false,false);
18818:                                 } else {
18819:                                     singleserver.options[0] = new Option("","",true,true);
18820:                                 }
18821:                                 var idx = 0;
18822:                                 for (var m=0; m<alltargets.length; m++) {
18823:                                     if (currBalancers.indexOf(alltargets[m]) == -1) {
18824:                                         idx ++;
18825:                                         if (currVal == alltargets[m]) {
18826:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],true,true);
18827:                                         } else {
18828:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
18829:                                         }
18830:                                     }
18831:                                 }
18832:                             }
18833:                         }
18834:                     }
18835:                 }
18836:             }
18837:         }
18838:     }
18839:     return;
18840: }
18841: 
18842: // ]]>
18843: </script>
18844: 
18845: END
18846: }
18847: 
18848: sub new_spares_js {
18849:     my @sparestypes = ('primary','default');
18850:     my $types = join("','",@sparestypes);
18851:     my $select = &mt('Select');
18852:     return <<"END";
18853: 
18854: <script type="text/javascript">
18855: // <![CDATA[
18856: 
18857: function updateNewSpares(formname,lonhost) {
18858:     var types = new Array('$types');
18859:     var include = new Array();
18860:     var exclude = new Array();
18861:     for (var i=0; i<types.length; i++) {
18862:         var spareboxes = getIndicesByName(formname,'spare_'+types[i]+'_'+lonhost);
18863:         for (var j=0; j<spareboxes.length; j++) {
18864:             if (formname.elements[spareboxes[j]].checked) {
18865:                 exclude.push(formname.elements[spareboxes[j]].value);
18866:             } else {
18867:                 include.push(formname.elements[spareboxes[j]].value);
18868:             }
18869:         }
18870:     }
18871:     for (var i=0; i<types.length; i++) {
18872:         var newSpare = document.getElementById('newspare_'+types[i]+'_'+lonhost);
18873:         var selIdx = newSpare.selectedIndex;
18874:         var currnew = newSpare.options[selIdx].value;
18875:         var okSpares = new Array();
18876:         for (var j=0; j<newSpare.options.length; j++) {
18877:             var possible = newSpare.options[j].value;
18878:             if (possible != '') {
18879:                 if (exclude.indexOf(possible) == -1) {
18880:                     okSpares.push(possible);
18881:                 } else {
18882:                     if (currnew == possible) {
18883:                         selIdx = 0;
18884:                     }
18885:                 }
18886:             }
18887:         }
18888:         for (var k=0; k<include.length; k++) {
18889:             if (okSpares.indexOf(include[k]) == -1) {
18890:                 okSpares.push(include[k]);
18891:             }
18892:         }
18893:         okSpares.sort();
18894:         newSpare.options.length = 0;
18895:         if (selIdx == 0) {
18896:             newSpare.options[0] = new Option("$select","",true,true);
18897:         } else {
18898:             newSpare.options[0] = new Option("$select","",false,false);
18899:         }
18900:         for (var m=0; m<okSpares.length; m++) {
18901:             var idx = m+1;
18902:             var selThis = 0;
18903:             if (selIdx != 0) {
18904:                 if (okSpares[m] == currnew) {
18905:                     selThis = 1;
18906:                 }
18907:             }
18908:             if (selThis == 1) {
18909:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],true,true);
18910:             } else {
18911:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],false,false);
18912:             }
18913:         }
18914:     }
18915:     return;
18916: }
18917: 
18918: function checkNewSpares(lonhost,type) {
18919:     var newSpare = document.getElementById('newspare_'+type+'_'+lonhost);
18920:     var chosen =  newSpare.options[newSpare.selectedIndex].value;
18921:     if (chosen != '') { 
18922:         var othertype;
18923:         var othernewSpare;
18924:         if (type == 'primary') {
18925:             othernewSpare = document.getElementById('newspare_default_'+lonhost);
18926:         }
18927:         if (type == 'default') {
18928:             othernewSpare = document.getElementById('newspare_primary_'+lonhost);
18929:         }
18930:         if (othernewSpare.options[othernewSpare.selectedIndex].value == chosen) {
18931:             othernewSpare.selectedIndex = 0;
18932:         }
18933:     }
18934:     return;
18935: }
18936: 
18937: // ]]>
18938: </script>
18939: 
18940: END
18941: 
18942: }
18943: 
18944: sub common_domprefs_js {
18945:     return <<"END";
18946: 
18947: <script type="text/javascript">
18948: // <![CDATA[
18949: 
18950: function getIndicesByName(formname,item) {
18951:     var group = new Array();
18952:     for (var i=0;i<formname.elements.length;i++) {
18953:         if (formname.elements[i].name == item) {
18954:             group.push(formname.elements[i].id);
18955:         }
18956:     }
18957:     return group;
18958: }
18959: 
18960: // ]]>
18961: </script>
18962: 
18963: END
18964: 
18965: }
18966: 
18967: sub recaptcha_js {
18968:     my %lt = &captcha_phrases();
18969:     return <<"END";
18970: 
18971: <script type="text/javascript">
18972: // <![CDATA[
18973: 
18974: function updateCaptcha(caller,context) {
18975:     var privitem;
18976:     var pubitem;
18977:     var privtext;
18978:     var pubtext;
18979:     var versionitem;
18980:     var versiontext;
18981:     if (document.getElementById(context+'_recaptchapub')) {
18982:         pubitem = document.getElementById(context+'_recaptchapub');
18983:     } else {
18984:         return;
18985:     }
18986:     if (document.getElementById(context+'_recaptchapriv')) {
18987:         privitem = document.getElementById(context+'_recaptchapriv');
18988:     } else {
18989:         return;
18990:     }
18991:     if (document.getElementById(context+'_recaptchapubtxt')) {
18992:         pubtext = document.getElementById(context+'_recaptchapubtxt');
18993:     } else {
18994:         return;
18995:     }
18996:     if (document.getElementById(context+'_recaptchaprivtxt')) {
18997:         privtext = document.getElementById(context+'_recaptchaprivtxt');
18998:     } else {
18999:         return;
19000:     }
19001:     if (document.getElementById(context+'_recaptchaversion')) {
19002:         versionitem = document.getElementById(context+'_recaptchaversion');
19003:     } else {
19004:         return;
19005:     }
19006:     if (document.getElementById(context+'_recaptchavertxt')) {
19007:         versiontext = document.getElementById(context+'_recaptchavertxt');
19008:     } else {
19009:         return;
19010:     }
19011:     if (caller.checked) {
19012:         if (caller.value == 'recaptcha') {
19013:             pubitem.type = 'text';
19014:             privitem.type = 'text';
19015:             pubitem.size = '40';
19016:             privitem.size = '40';
19017:             pubtext.innerHTML = "$lt{'pub'}";
19018:             privtext.innerHTML = "$lt{'priv'}";
19019:             versionitem.type = 'text';
19020:             versionitem.size = '3';
19021:             versiontext.innerHTML = "$lt{'ver'}";
19022:         } else {
19023:             pubitem.type = 'hidden';
19024:             privitem.type = 'hidden';
19025:             versionitem.type = 'hidden';
19026:             pubtext.innerHTML = '';
19027:             privtext.innerHTML = '';
19028:             versiontext.innerHTML = '';
19029:         }
19030:     }
19031:     return;
19032: }
19033: 
19034: // ]]>
19035: </script>
19036: 
19037: END
19038: 
19039: }
19040: 
19041: sub toggle_display_js {
19042:     return <<"END";
19043: 
19044: <script type="text/javascript">
19045: // <![CDATA[
19046: 
19047: function toggleDisplay(domForm,caller) {
19048:     if (document.getElementById(caller)) {
19049:         var divitem = document.getElementById(caller);
19050:         var optionsElement = domForm.coursecredits;
19051:         var checkval = 1;
19052:         var dispval = 'block';
19053:         var selfcreateRegExp = /^cancreate_emailverified/;
19054:         if (caller == 'emailoptions') {
19055:             optionsElement = domForm.cancreate_email; 
19056:         }
19057:         if (caller == 'studentsubmission') {
19058:             optionsElement = domForm.postsubmit;
19059:         }
19060:         if (caller == 'cloneinstcode') {
19061:             optionsElement = domForm.canclone;
19062:             checkval = 'instcode';
19063:         }
19064:         if (selfcreateRegExp.test(caller)) {
19065:             optionsElement = domForm.elements[caller];
19066:             checkval = 'other';
19067:             dispval = 'inline'
19068:         }
19069:         if (optionsElement.length) {
19070:             var currval;
19071:             for (var i=0; i<optionsElement.length; i++) {
19072:                 if (optionsElement[i].checked) {
19073:                    currval = optionsElement[i].value;
19074:                 }
19075:             }
19076:             if (currval == checkval) {
19077:                 divitem.style.display = dispval;
19078:             } else {
19079:                 divitem.style.display = 'none';
19080:             }
19081:         }
19082:     }
19083:     return;
19084: }
19085: 
19086: // ]]>
19087: </script>
19088: 
19089: END
19090: 
19091: }
19092: 
19093: sub captcha_phrases {
19094:     return &Apache::lonlocal::texthash (
19095:                  priv => 'Private key',
19096:                  pub  => 'Public key',
19097:                  original  => 'original (CAPTCHA)',
19098:                  recaptcha => 'successor (ReCAPTCHA)',
19099:                  notused   => 'unused',
19100:                  ver => 'ReCAPTCHA version (1 or 2)',
19101:     );
19102: }
19103: 
19104: sub devalidate_remote_domconfs {
19105:     my ($dom,$cachekeys) = @_;
19106:     return unless (ref($cachekeys) eq 'HASH');
19107:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
19108:     my %thismachine;
19109:     map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
19110:     my @posscached = ('domainconfig','domdefaults','ltitools','usersessions',
19111:                       'directorysrch','passwdconf','cats','proxyalias','proxysaml',
19112:                       'ipaccess');
19113:     my %cache_by_lonhost;
19114:     if (exists($cachekeys->{'samllanding'})) {
19115:         if (ref($cachekeys->{'samllanding'}) eq 'HASH') {
19116:             my %landing = %{$cachekeys->{'samllanding'}};
19117:             my %domservers = &Apache::lonnet::get_servers($dom);
19118:             if (keys(%domservers)) {
19119:                 foreach my $server (keys(%domservers)) {
19120:                     my @cached;
19121:                     next if ($thismachine{$server});
19122:                     if ($landing{$server}) {
19123:                         push(@cached,&escape('samllanding').':'.&escape($server));
19124:                     }
19125:                     if (@cached) {
19126:                         $cache_by_lonhost{$server} = \@cached;
19127:                     }
19128:                 }
19129:             }
19130:         }
19131:     }
19132:     if (keys(%servers)) {
19133:         foreach my $server (keys(%servers)) {
19134:             next if ($thismachine{$server});
19135:             my @cached;
19136:             foreach my $name (@posscached) {
19137:                 if ($cachekeys->{$name}) {
19138:                     if (($name eq 'proxyalias') || ($name eq 'proxysaml')) {
19139:                         if (ref($cachekeys->{$name}) eq 'HASH') {
19140:                             foreach my $key (keys(%{$cachekeys->{$name}})) {
19141:                                 push(@cached,&escape($name).':'.&escape($key));
19142:                             }
19143:                         }
19144:                     } else {
19145:                         push(@cached,&escape($name).':'.&escape($dom));
19146:                     }
19147:                 }
19148:             }
19149:             if ((exists($cache_by_lonhost{$server})) &&
19150:                 (ref($cache_by_lonhost{$server}) eq 'ARRAY')) {
19151:                 push(@cached,@{$cache_by_lonhost{$server}});
19152:             }
19153:             if (@cached) {
19154:                 &Apache::lonnet::remote_devalidate_cache($server,\@cached);
19155:             }
19156:         }
19157:     }
19158:     return;
19159: }
19160: 
19161: 1;

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