File:  [LON-CAPA] / loncom / interface / domainprefs.pm
Revision 1.419: download - view: text, annotated - select for diffs
Tue Feb 14 21:44:15 2023 UTC (15 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Eliminate javascript error when configuring link protection in a domain
  with no existing LTI configuration.

    1: # The LearningOnline Network with CAPA
    2: # Handler to set domain-wide configuration settings
    3: #
    4: # $Id: domainprefs.pm,v 1.419 2023/02/14 21:44:15 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: #
   29: ###############################################################
   30: ###############################################################
   31: 
   32: =pod
   33: 
   34: =head1 NAME
   35: 
   36: Apache::domainprefs.pm
   37: 
   38: =head1 SYNOPSIS
   39: 
   40: Handles configuration of a LON-CAPA domain.  
   41: 
   42: This is part of the LearningOnline Network with CAPA project
   43: described at http://www.lon-capa.org.
   44: 
   45: 
   46: =head1 OVERVIEW
   47: 
   48: Each institution using LON-CAPA will typically have a single domain designated 
   49: for use by individuals affiliated with the institution.  Accordingly, each domain
   50: may define a default set of logos and a color scheme which can be used to "brand"
   51: the LON-CAPA instance. In addition, an institution will typically have a language
   52: and timezone which are used for the majority of courses.
   53: 
   54: LON-CAPA provides a mechanism to display and modify these defaults, as well as a 
   55: host of other domain-wide settings which determine the types of functionality
   56: available to users and courses in the domain.
   57: 
   58: There is also a mechanism to configure cataloging of courses in the domain, and
   59: controls on the operation of automated processes which govern such things as
   60: roster updates, user directory updates and processing of course requests.
   61: 
   62: The domain coordination manual which is built dynamically on install/update of 
   63: LON-CAPA from the relevant help items provides more information about domain 
   64: configuration.
   65: 
   66: Most of the domain settings are stored in the configuration.db GDBM file which is
   67: housed on the primary library server for the domain in /home/httpd/lonUsers/$dom,
   68: where $dom is the domain.  The configuration.db stores settings in a number of 
   69: frozen hashes of hashes.  In a few cases, domain information must be uploaded to
   70: the domain as files (e.g., image files for logos etc., or plain text files for
   71: bubblesheet formats).  In this case the domainprefs.pm must be running in a user
   72: session hosted on the primary library server in the domain, as these files are 
   73: stored in author space belonging to a special $dom-domainconfig user.   
   74: 
   75: domainprefs.pm in combination with lonconfigsettings.pm will retrieve and display
   76: the current settings, and provides an interface to make modifications.
   77: 
   78: =head1 SUBROUTINES
   79: 
   80: =over
   81: 
   82: =item print_quotas()
   83: 
   84: Inputs: 4 
   85: 
   86: $dom,$settings,$rowtotal,$action.
   87: 
   88: $dom is the domain, $settings is a reference to a hash of current settings for
   89: the current context, $rowtotal is a reference to the scalar used to record the 
   90: number of rows displayed on the page, and $action is the context (quotas, 
   91: requestcourses or requestauthor).
   92: 
   93: The print_quotas routine was orginally created to display/store information
   94: about default quota sizes for portfolio spaces for the different types of 
   95: institutional affiliation in the domain (e.g., Faculty, Staff, Student etc.), 
   96: but is now also used to manage availability of user tools: 
   97: i.e., blogs, aboutme page, and portfolios, and the course request tool,
   98: used by course owners to request creation of a course, and to display/store
   99: default quota sizes for Authoring Spaces.
  100: 
  101: Outputs: 1
  102: 
  103: $datatable  - HTML containing form elements which allow settings to be changed. 
  104: 
  105: In the case of course requests, radio buttons are displayed for each institutional
  106: affiliate type (and also default, and _LC_adv) for each of the course types 
  107: (official, unofficial, community, textbook, placement, and lti).  
  108: In each case the radio buttons allow the selection of one of four values:  
  109: 
  110: 0, approval, validate, autolimit=N (where N is blank, or a positive integer).
  111: which have the following effects:
  112: 
  113: 0
  114: 
  115: =over
  116: 
  117: - course requests are not allowed for this course types/affiliation
  118: 
  119: =back
  120: 
  121: approval 
  122: 
  123: =over 
  124: 
  125: - course requests must be approved by a Doman Coordinator in the 
  126: course's domain
  127: 
  128: =back
  129: 
  130: validate 
  131: 
  132: =over
  133: 
  134: - an institutional validation (e.g., check requestor is instructor
  135: of record) needs to be passed before the course will be created.  The required
  136: validation is in localenroll.pm on the primary library server for the course 
  137: domain.
  138: 
  139: =back
  140: 
  141: autolimit 
  142: 
  143: =over
  144:  
  145: - course requests will be processed automatically up to a limit of
  146: N requests for the course type for the particular requestor.
  147: If N is undefined, there is no limit to the number of course requests
  148: which a course owner may submit and have processed automatically. 
  149: 
  150: =back
  151: 
  152: =item modify_quotas() 
  153: 
  154: =back
  155: 
  156: =cut
  157: 
  158: package Apache::domainprefs;
  159: 
  160: use strict;
  161: use Apache::Constants qw(:common :http);
  162: use Apache::lonnet;
  163: use Apache::loncommon();
  164: use Apache::lonhtmlcommon();
  165: use Apache::lonlocal;
  166: use Apache::lonmsg();
  167: use Apache::lonconfigsettings;
  168: use Apache::lonuserutils();
  169: use Apache::loncoursequeueadmin();
  170: use Apache::courseprefs();
  171: use LONCAPA qw(:DEFAULT :match);
  172: use LONCAPA::Enrollment;
  173: use LONCAPA::lonauthcgi();
  174: use LONCAPA::SSL;
  175: use File::Copy;
  176: use Locale::Language;
  177: use DateTime::TimeZone;
  178: use DateTime::Locale;
  179: use Time::HiRes qw( sleep );
  180: use Net::CIDR;
  181: 
  182: my $registered_cleanup;
  183: my $modified_urls;
  184: 
  185: sub handler {
  186:     my $r=shift;
  187:     if ($r->header_only) {
  188:         &Apache::loncommon::content_type($r,'text/html');
  189:         $r->send_http_header;
  190:         return OK;
  191:     }
  192: 
  193:     my $context = 'domain';
  194:     my $dom = $env{'request.role.domain'};
  195:     my $domdesc = &Apache::lonnet::domain($dom,'description');
  196:     if (&Apache::lonnet::allowed('mau',$dom)) {
  197:         &Apache::loncommon::content_type($r,'text/html');
  198:         $r->send_http_header;
  199:     } else {
  200:         $env{'user.error.msg'}=
  201:         "/adm/domainprefs:mau:0:0:Cannot modify domain settings";
  202:         return HTTP_NOT_ACCEPTABLE;
  203:     }
  204: 
  205:     $registered_cleanup=0;
  206:     @{$modified_urls}=();
  207: 
  208:     &Apache::lonhtmlcommon::clear_breadcrumbs();
  209:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
  210:                                             ['phase','actions']);
  211:     my $phase = 'pickactions';
  212:     if ( exists($env{'form.phase'}) ) {
  213:         $phase = $env{'form.phase'};
  214:     }
  215:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
  216:     my %domconfig =
  217:       &Apache::lonnet::get_dom('configuration',['login','rolecolors',
  218:                 'quotas','autoenroll','autoupdate','autocreate',
  219:                 'directorysrch','usercreation','usermodification',
  220:                 'contacts','defaults','scantron','coursecategories',
  221:                 'serverstatuses','requestcourses','helpsettings',
  222:                 'coursedefaults','usersessions','loadbalancing',
  223:                 'requestauthor','selfenrollment','inststatus',
  224:                 'ltitools','ssl','trust','lti','ltisec','privacy','passwords',
  225:                 'proctoring','wafproxy','ipaccess'],$dom);
  226:     my %encconfig =
  227:         &Apache::lonnet::get_dom('encconfig',['ltitools','lti','proctoring','linkprot'],$dom,undef,1);
  228:     if (ref($domconfig{'ltitools'}) eq 'HASH') {
  229:         if (ref($encconfig{'ltitools'}) eq 'HASH') {
  230:             foreach my $id (keys(%{$domconfig{'ltitools'}})) {
  231:                 if ((ref($domconfig{'ltitools'}{$id}) eq 'HASH') &&
  232:                     (ref($encconfig{'ltitools'}{$id}) eq 'HASH')) {
  233:                     foreach my $item ('key','secret') {
  234:                         $domconfig{'ltitools'}{$id}{$item} = $encconfig{'ltitools'}{$id}{$item};
  235:                     }
  236:                 }
  237:             }
  238:         }
  239:     }
  240:     if (ref($domconfig{'lti'}) eq 'HASH') {
  241:         if (ref($encconfig{'lti'}) eq 'HASH') {
  242:             foreach my $id (keys(%{$domconfig{'lti'}})) {
  243:                 if ((ref($domconfig{'lti'}{$id}) eq 'HASH') &&
  244:                     (ref($encconfig{'lti'}{$id}) eq 'HASH')) {
  245:                     foreach my $item ('key','secret') {
  246:                         $domconfig{'lti'}{$id}{$item} = $encconfig{'lti'}{$id}{$item};
  247:                     }
  248:                 }
  249:             }
  250:         }
  251:     }
  252:     if (ref($domconfig{'ltisec'}) eq 'HASH') {
  253:         if (ref($domconfig{'ltisec'}{'linkprot'}) eq 'HASH') {
  254:             if (ref($encconfig{'linkprot'}) eq 'HASH') {
  255:                 foreach my $id (keys(%{$domconfig{'ltisec'}{'linkprot'}})) {
  256:                     unless ($id =~ /^\d+$/) {
  257:                         delete($domconfig{'ltisec'}{'linkprot'}{$id});
  258:                     }
  259:                     if ((ref($domconfig{'ltisec'}{'linkprot'}{$id}) eq 'HASH') &&
  260:                         (ref($encconfig{'linkprot'}{$id}) eq 'HASH')) {
  261:                         foreach my $item ('key','secret') {
  262:                             $domconfig{'ltisec'}{'linkprot'}{$id}{$item} = $encconfig{'linkprot'}{$id}{$item};
  263:                         }
  264:                     }
  265:                 }
  266:             }
  267:         }
  268:     }
  269:     if (ref($domconfig{'proctoring'}) eq 'HASH') {
  270:         if (ref($encconfig{'proctoring'}) eq 'HASH') {
  271:             foreach my $provider (keys(%{$domconfig{'proctoring'}})) {
  272:                 if ((ref($domconfig{'proctoring'}{$provider}) eq 'HASH') &&
  273:                     (ref($encconfig{'proctoring'}{$provider}) eq 'HASH')) {
  274:                     foreach my $item ('key','secret') {
  275:                         $domconfig{'proctoring'}{$provider}{$item} = $encconfig{'proctoring'}{$provider}{$item};
  276:                     }
  277:                 }
  278:             }
  279:         }
  280:     }
  281:     my @prefs_order = ('rolecolors','login','ipaccess','defaults','wafproxy','passwords',
  282:                        'quotas','autoenroll','autoupdate','autocreate','directorysrch',
  283:                        'contacts','privacy','usercreation','selfcreation',
  284:                        'usermodification','scantron','requestcourses','requestauthor',
  285:                        'coursecategories','serverstatuses','helpsettings','coursedefaults',
  286:                        'ltitools','proctoring','selfenrollment','usersessions','ssl',
  287:                        'trust','lti');
  288:     my %existing;
  289:     if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
  290:         %existing = %{$domconfig{'loadbalancing'}};
  291:     }
  292:     if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
  293:         push(@prefs_order,'loadbalancing');
  294:     }
  295:     my %prefs = (
  296:         'rolecolors' =>
  297:                    { text => 'Default color schemes',
  298:                      help => 'Domain_Configuration_Color_Schemes',
  299:                      header => [{col1 => 'Student Settings',
  300:                                  col2 => '',},
  301:                                 {col1 => 'Coordinator Settings',
  302:                                  col2 => '',},
  303:                                 {col1 => 'Author Settings',
  304:                                  col2 => '',},
  305:                                 {col1 => 'Administrator Settings',
  306:                                  col2 => '',}],
  307:                       print => \&print_rolecolors,
  308:                       modify => \&modify_rolecolors,
  309:                     },
  310:         'login' =>
  311:                     { text => 'Log-in page options',
  312:                       help => 'Domain_Configuration_Login_Page',
  313:                       header => [{col1 => 'Log-in Page Items',
  314:                                   col2 => '',},
  315:                                  {col1 => 'Log-in Help',
  316:                                   col2 => 'Value'},
  317:                                  {col1 => 'Custom HTML in document head',
  318:                                   col2 => 'Value'},
  319:                                  {col1 => 'SSO',
  320:                                   col2 => 'Dual login: SSO and non-SSO options'},
  321:                                 ],
  322:                       print => \&print_login,
  323:                       modify => \&modify_login,
  324:                     },
  325:         'defaults' => 
  326:                     { text => 'Default authentication/language/timezone/portal/types',
  327:                       help => 'Domain_Configuration_LangTZAuth',
  328:                       header => [{col1 => 'Setting',
  329:                                   col2 => 'Value'},
  330:                                  {col1 => 'Institutional user types',
  331:                                   col2 => 'Name displayed'},
  332:                                  {col1 => 'Mapping for missing usernames via standard log-in',
  333:                                   col2 => 'Rules in use'}],
  334:                       print => \&print_defaults,
  335:                       modify => \&modify_defaults,
  336:                     },
  337:         'wafproxy' =>
  338:                     { text => 'Web Application Firewall/Reverse Proxy',
  339:                       help => 'Domain_Configuration_WAF_Proxy',
  340:                       header => [{col1 => 'Domain(s)',
  341:                                   col2 => 'Servers and WAF/Reverse Proxy alias(es)',
  342:                                  },
  343:                                  {col1 => 'Domain(s)',
  344:                                   col2 => 'WAF Configuration',}],
  345:                       print => \&print_wafproxy,
  346:                       modify => \&modify_wafproxy,
  347:                     },
  348:         'passwords' =>
  349:                     { text => 'Passwords (Internal authentication)',
  350:                       help => 'Domain_Configuration_Passwords',
  351:                       header => [{col1 => 'Resetting Forgotten Password',
  352:                                   col2 => 'Settings'},
  353:                                  {col1 => 'Encryption of Stored Passwords (Internal Auth)',
  354:                                   col2 => 'Settings'},
  355:                                  {col1 => 'Rules for LON-CAPA Passwords',
  356:                                   col2 => 'Settings'},
  357:                                  {col1 => 'Course Owner Changing Student Passwords',
  358:                                   col2 => 'Settings'}],
  359:                       print => \&print_passwords,
  360:                       modify => \&modify_passwords,
  361:                     },
  362:         'quotas' => 
  363:                     { text => 'Blogs, personal pages/timezones, webDAV/quotas, portfolio',
  364:                       help => 'Domain_Configuration_Quotas',
  365:                       header => [{col1 => 'User affiliation',
  366:                                   col2 => 'Available tools',
  367:                                   col3 => 'Quotas, MB; (Authoring requires role)',}],
  368:                       print => \&print_quotas,
  369:                       modify => \&modify_quotas,
  370:                     },
  371:         'autoenroll' =>
  372:                    { text => 'Auto-enrollment settings',
  373:                      help => 'Domain_Configuration_Auto_Enrollment',
  374:                      header => [{col1 => 'Configuration setting',
  375:                                  col2 => 'Value(s)'}],
  376:                      print => \&print_autoenroll,
  377:                      modify => \&modify_autoenroll,
  378:                    },
  379:         'autoupdate' => 
  380:                    { text => 'Auto-update settings',
  381:                      help => 'Domain_Configuration_Auto_Updates',
  382:                      header => [{col1 => 'Setting',
  383:                                  col2 => 'Value',},
  384:                                 {col1 => 'Setting',
  385:                                  col2 => 'Affiliation'},
  386:                                 {col1 => 'User population',
  387:                                  col2 => 'Updatable user data'}],
  388:                      print => \&print_autoupdate,
  389:                      modify => \&modify_autoupdate,
  390:                   },
  391:         'autocreate' => 
  392:                   { text => 'Auto-course creation settings',
  393:                      help => 'Domain_Configuration_Auto_Creation',
  394:                      header => [{col1 => 'Configuration Setting',
  395:                                  col2 => 'Value',}],
  396:                      print => \&print_autocreate,
  397:                      modify => \&modify_autocreate,
  398:                   },
  399:         'directorysrch' => 
  400:                   { text => 'Directory searches',
  401:                     help => 'Domain_Configuration_InstDirectory_Search',
  402:                     header => [{col1 => 'Institutional Directory Setting',
  403:                                 col2 => 'Value',},
  404:                                {col1 => 'LON-CAPA Directory Setting',
  405:                                 col2 => 'Value',}],
  406:                     print => \&print_directorysrch,
  407:                     modify => \&modify_directorysrch,
  408:                   },
  409:         'contacts' =>
  410:                   { text => 'E-mail addresses and helpform',
  411:                     help => 'Domain_Configuration_Contact_Info',
  412:                     header => [{col1 => 'Default e-mail addresses',
  413:                                 col2 => 'Value',},
  414:                                {col1 => 'Recipient(s) for notifications',
  415:                                 col2 => 'Value',},
  416:                                {col1 => 'Nightly status check e-mail',
  417:                                 col2 => 'Settings',},
  418:                                {col1 => 'Ask helpdesk form settings',
  419:                                 col2 => 'Value',},],
  420:                     print => \&print_contacts,
  421:                     modify => \&modify_contacts,
  422:                   },
  423:         'usercreation' => 
  424:                   { text => 'User creation',
  425:                     help => 'Domain_Configuration_User_Creation',
  426:                     header => [{col1 => 'Format rule type',
  427:                                 col2 => 'Format rules in force'},
  428:                                {col1 => 'User account creation',
  429:                                 col2 => 'Usernames which may be created',},
  430:                                {col1 => 'Context',
  431:                                 col2 => 'Assignable authentication types'}],
  432:                     print => \&print_usercreation,
  433:                     modify => \&modify_usercreation,
  434:                   },
  435:         'selfcreation' => 
  436:                   { text => 'Users self-creating accounts',
  437:                     help => 'Domain_Configuration_Self_Creation', 
  438:                     header => [{col1 => 'Self-creation with institutional username',
  439:                                 col2 => 'Enabled?'},
  440:                                {col1 => 'Institutional user type (login/SSO self-creation)',
  441:                                 col2 => 'Information user can enter'},
  442:                                {col1 => 'Self-creation with e-mail verification',
  443:                                 col2 => 'Settings'}],
  444:                     print => \&print_selfcreation,
  445:                     modify => \&modify_selfcreation,
  446:                   },
  447:         'usermodification' =>
  448:                   { text => 'User modification',
  449:                     help => 'Domain_Configuration_User_Modification',
  450:                     header => [{col1 => 'Target user has role',
  451:                                 col2 => 'User information updatable in author context'},
  452:                                {col1 => 'Target user has role',
  453:                                 col2 => 'User information updatable in course context'}],
  454:                     print => \&print_usermodification,
  455:                     modify => \&modify_usermodification,
  456:                   },
  457:         'scantron' =>
  458:                   { text => 'Bubblesheet format',
  459:                     help => 'Domain_Configuration_Scantron_Format',
  460:                     header => [ {col1 => 'Bubblesheet format file',
  461:                                  col2 => ''},
  462:                                 {col1 => 'Bubblesheet data upload formats',
  463:                                  col2 => 'Settings'}],
  464:                     print => \&print_scantron,
  465:                     modify => \&modify_scantron,
  466:                   },
  467:         'requestcourses' => 
  468:                  {text => 'Request creation of courses',
  469:                   help => 'Domain_Configuration_Request_Courses',
  470:                   header => [{col1 => 'User affiliation',
  471:                               col2 => 'Availability/Processing of requests',},
  472:                              {col1 => 'Setting',
  473:                               col2 => 'Value'},
  474:                              {col1 => 'Available textbooks',
  475:                               col2 => ''},
  476:                              {col1 => 'Available templates',
  477:                               col2 => ''},
  478:                              {col1 => 'Validation (not official courses)',
  479:                               col2 => 'Value'},],
  480:                   print => \&print_quotas,
  481:                   modify => \&modify_quotas,
  482:                  },
  483:         'requestauthor' =>
  484:                  {text => 'Request Authoring Space',
  485:                   help => 'Domain_Configuration_Request_Author',
  486:                   header => [{col1 => 'User affiliation',
  487:                               col2 => 'Availability/Processing of requests',},
  488:                              {col1 => 'Setting',
  489:                               col2 => 'Value'}],
  490:                   print => \&print_quotas,
  491:                   modify => \&modify_quotas,
  492:                  },
  493:         'coursecategories' =>
  494:                   { text => 'Cataloging of courses/communities',
  495:                     help => 'Domain_Configuration_Cataloging_Courses',
  496:                     header => [{col1 => 'Catalog type/availability',
  497:                                 col2 => '',},
  498:                                {col1 => 'Category settings for standard catalog',
  499:                                 col2 => '',},
  500:                                {col1 => 'Categories',
  501:                                 col2 => '',
  502:                                }],
  503:                     print => \&print_coursecategories,
  504:                     modify => \&modify_coursecategories,
  505:                   },
  506:         'serverstatuses' =>
  507:                  {text   => 'Access to server status pages',
  508:                   help   => 'Domain_Configuration_Server_Status',
  509:                   header => [{col1 => 'Status Page',
  510:                               col2 => 'Other named users',
  511:                               col3 => 'Specific IPs',
  512:                             }],
  513:                   print => \&print_serverstatuses,
  514:                   modify => \&modify_serverstatuses,
  515:                  },
  516:         'helpsettings' =>
  517:                  {text   => 'Support settings',
  518:                   help   => 'Domain_Configuration_Help_Settings',
  519:                   header => [{col1 => 'Help Page Settings (logged-in users)',
  520:                               col2 => 'Value'},
  521:                              {col1 => 'Helpdesk Roles',
  522:                               col2 => 'Settings'},],
  523:                   print  => \&print_helpsettings,
  524:                   modify => \&modify_helpsettings,
  525:                  },
  526:         'coursedefaults' => 
  527:                  {text => 'Course/Community defaults',
  528:                   help => 'Domain_Configuration_Course_Defaults',
  529:                   header => [{col1 => 'Defaults which can be overridden in each course by a CC',
  530:                               col2 => 'Value',},
  531:                              {col1 => 'Defaults which can be overridden for each course by a DC',
  532:                               col2 => 'Value',},],
  533:                   print => \&print_coursedefaults,
  534:                   modify => \&modify_coursedefaults,
  535:                  },
  536:         'selfenrollment' => 
  537:                  {text   => 'Self-enrollment in Course/Community',
  538:                   help   => 'Domain_Configuration_Selfenrollment',
  539:                   header => [{col1 => 'Configuration Rights',
  540:                               col2 => 'Configured by Course Personnel or Domain Coordinator?'},
  541:                              {col1 => 'Defaults',
  542:                               col2 => 'Value'},
  543:                              {col1 => 'Self-enrollment validation (optional)',
  544:                               col2 => 'Value'},],
  545:                   print => \&print_selfenrollment,
  546:                   modify => \&modify_selfenrollment,
  547:                  },
  548:         'privacy' => 
  549:                  {text   => 'Availability of User Information',
  550:                   help   => 'Domain_Configuration_User_Privacy',
  551:                   header => [{col1 => 'Role assigned in different domain',
  552:                               col2 => 'Approval options'},
  553:                              {col1 => 'Role assigned in different domain to user of type',
  554:                               col2 => 'User information available in that domain'},
  555:                              {col1 => "Role assigned in user's domain",
  556:                               col2 => 'Information viewable by privileged user'},
  557:                              {col1 => "Role assigned in user's domain",
  558:                               col2 => 'Information viewable by unprivileged user'}],
  559:                   print => \&print_privacy,
  560:                   modify => \&modify_privacy,
  561:                  },
  562:         'usersessions' =>
  563:                  {text  => 'User session hosting/offloading',
  564:                   help  => 'Domain_Configuration_User_Sessions',
  565:                   header => [{col1 => 'Domain server',
  566:                               col2 => 'Servers to offload sessions to when busy'},
  567:                              {col1 => 'Hosting of users from other domains',
  568:                               col2 => 'Rules'},
  569:                              {col1 => "Hosting domain's own users elsewhere",
  570:                               col2 => 'Rules'}],
  571:                   print => \&print_usersessions,
  572:                   modify => \&modify_usersessions,
  573:                  },
  574:         'loadbalancing' =>
  575:                  {text  => 'Dedicated Load Balancer(s)',
  576:                   help  => 'Domain_Configuration_Load_Balancing',
  577:                   header => [{col1 => 'Balancers',
  578:                               col2 => 'Default destinations',
  579:                               col3 => 'User affiliation',
  580:                               col4 => 'Overrides'},
  581:                             ],
  582:                   print => \&print_loadbalancing,
  583:                   modify => \&modify_loadbalancing,
  584:                  },
  585:         'ltitools' => 
  586:                  {text => 'External Tools (LTI)',
  587:                   help => 'Domain_Configuration_LTI_Tools',
  588:                   header => [{col1 => 'Setting',
  589:                               col2 => 'Value',}],
  590:                   print => \&print_ltitools,
  591:                   modify => \&modify_ltitools,
  592:                  },
  593:         'proctoring' =>
  594:                  {text => 'Remote Proctoring Integration',
  595:                   help => 'Domain_Configuration_Proctoring',
  596:                   header => [{col1 => 'Name',
  597:                               col2 => 'Configuration'}],
  598:                   print => \&print_proctoring,
  599:                   modify => \&modify_proctoring,
  600:                  },
  601:         'ssl' =>
  602:                  {text  => 'LON-CAPA Network (SSL)',
  603:                   help  => 'Domain_Configuration_Network_SSL',
  604:                   header => [{col1 => 'Server',
  605:                               col2 => 'Certificate Status'},
  606:                              {col1 => 'Connections to other servers',
  607:                               col2 => 'Rules'},
  608:                              {col1 => 'Connections from other servers',
  609:                               col2 => 'Rules'},
  610:                              {col1 => "Replicating domain's published content",
  611:                               col2 => 'Rules'}],
  612:                   print => \&print_ssl,
  613:                   modify => \&modify_ssl,
  614:                  },
  615:         'trust' =>
  616:                  {text   => 'Trust Settings',
  617:                   help   => 'Domain_Configuration_Trust',
  618:                   header => [{col1 => "Access to this domain's content by others",
  619:                               col2 => 'Rules'},
  620:                              {col1 => "Access to other domain's content by this domain",
  621:                               col2 => 'Rules'},
  622:                              {col1 => "Enrollment in this domain's courses by others",
  623:                               col2 => 'Rules',},
  624:                              {col1 => "Co-author roles in this domain for others",
  625:                               col2 => 'Rules',},
  626:                              {col1 => "Co-author roles for this domain's users elsewhere",
  627:                               col2 => 'Rules',},
  628:                              {col1 => "Domain roles in this domain assignable to others",
  629:                               col2 => 'Rules'},
  630:                              {col1 => "Course catalog for this domain displayed elsewhere",
  631:                               col2 => 'Rules'},
  632:                              {col1 => "Requests for creation of courses in this domain by others",
  633:                               col2 => 'Rules'},
  634:                              {col1 => "Users in other domains can send messages to this domain",
  635:                               col2 => 'Rules'},],
  636:                   print => \&print_trust,
  637:                   modify => \&modify_trust,
  638:                  },
  639:           'lti' =>
  640:                  {text => 'LTI Link Protection and LTI Consumers',
  641:                   help => 'Domain_Configuration_LTI_Provider',
  642:                   header => [{col1 => 'Encryption of shared secrets',
  643:                               col2 => 'Settings'},
  644:                              {col1 => 'Rules for shared secrets', 
  645:                               col2 => 'Settings'},
  646:                              {col1 => 'Link Protectors',
  647:                               col2 => 'Settings'},
  648:                              {col1 => 'Consumers',
  649:                               col2 => 'Settings'},],
  650:                   print => \&print_lti,
  651:                   modify => \&modify_lti,
  652:                  },
  653:            'ipaccess' =>
  654:                        {text => 'IP-based access control',
  655:                         help => 'Domain_Configuration_IP_Access',
  656:                         header => [{col1 => 'Setting',
  657:                                     col2 => 'Value'},],
  658:                         print  => \&print_ipaccess,
  659:                         modify => \&modify_ipaccess,
  660:                        },
  661:     );
  662:     if (keys(%servers) > 1) {
  663:         $prefs{'login'}  = { text   => 'Log-in page options',
  664:                              help   => 'Domain_Configuration_Login_Page',
  665:                             header => [{col1 => 'Log-in Service',
  666:                                         col2 => 'Server Setting',},
  667:                                        {col1 => 'Log-in Page Items',
  668:                                         col2 => 'Settings'},
  669:                                        {col1 => 'Log-in Help',
  670:                                         col2 => 'Value'},
  671:                                        {col1 => 'Custom HTML in document head',
  672:                                         col2 => 'Value'},
  673:                                        {col1 => 'SSO',
  674:                                         col2 => 'Dual login: SSO and non-SSO options'},
  675:                                       ],
  676:                             print => \&print_login,
  677:                             modify => \&modify_login,
  678:                            };
  679:     }
  680: 
  681:     my @roles = ('student','coordinator','author','admin');
  682:     my @actions = &Apache::loncommon::get_env_multiple('form.actions');
  683:     &Apache::lonhtmlcommon::add_breadcrumb
  684:     ({href=>"javascript:changePage(document.$phase,'pickactions')",
  685:       text=>"Settings to display/modify"});
  686:     my $confname = $dom.'-domainconfig';
  687: 
  688:     if ($phase eq 'process') {
  689:         my $result = &Apache::lonconfigsettings::make_changes($r,$dom,$phase,$context,\@prefs_order,
  690:                                                               \%prefs,\%domconfig,$confname,\@roles);
  691:         if ((ref($result) eq 'HASH') && (keys(%{$result}))) {
  692:             $r->rflush();
  693:             &devalidate_remote_domconfs($dom,$result);
  694:         }
  695:     } elsif ($phase eq 'display') {
  696:         my $js = &recaptcha_js().
  697:                  &toggle_display_js();
  698:         if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
  699:             my ($othertitle,$usertypes,$types) =
  700:                 &Apache::loncommon::sorted_inst_types($dom);
  701:             $js .= &lonbalance_targets_js($dom,$types,\%servers,
  702:                                           $domconfig{'loadbalancing'}).
  703:                    &new_spares_js().
  704:                    &common_domprefs_js().
  705:                    &Apache::loncommon::javascript_array_indexof();
  706:         }
  707:         if (grep(/^requestcourses$/,@actions)) {
  708:             my $javascript_validations;
  709:             my $coursebrowserjs=&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}); 
  710:             $js .= <<END;
  711: <script type="text/javascript">
  712: $javascript_validations
  713: </script>
  714: $coursebrowserjs
  715: END
  716:         } elsif (grep(/^ipaccess$/,@actions)) {
  717:             $js .= &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
  718:         }
  719:         if (grep(/^selfcreation$/,@actions)) {
  720:             $js .= &selfcreate_javascript();
  721:         }
  722:         if (grep(/^contacts$/,@actions)) {
  723:             $js .= &contacts_javascript();
  724:         }
  725:         if (grep(/^scantron$/,@actions)) {
  726:             $js .= &scantron_javascript();
  727:         }
  728:         &Apache::lonconfigsettings::display_settings($r,$dom,$phase,$context,\@prefs_order,\%prefs,\%domconfig,$confname,$js);
  729:     } else {
  730: # check if domconfig user exists for the domain.
  731:         my $servadm = $r->dir_config('lonAdmEMail');
  732:         my ($configuserok,$author_ok,$switchserver) =
  733:             &config_check($dom,$confname,$servadm);
  734:         unless ($configuserok eq 'ok') {
  735:             &Apache::lonconfigsettings::print_header($r,$phase,$context);
  736:             $r->print(&mt('The domain configuration user "[_1]" has yet to be created.',
  737:                           $confname).
  738:                       '<br />'
  739:             );
  740:             if ($switchserver) {
  741:                 $r->print(&mt('Ordinarily, that domain configuration user is created when the ./UPDATE script is run to install LON-CAPA for the first time.').
  742:                           '<br />'.
  743:                           &mt('However, that does not apply when new domains are added to a multi-domain server, and ./UPDATE has not been run recently.').
  744:                           '<br />'.
  745:                           &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).
  746:                           '<br />'.
  747:                           &mt('To do that now, use the following link: [_1]',$switchserver)
  748:                 );
  749:             } else {
  750:                 $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.').
  751:                           '<br />'.
  752:                           &mt('Once that is done, you will be able to use the web-based "Set domain configuration" to configure the domain')
  753:                 );
  754:             }
  755:             $r->print(&Apache::loncommon::end_page());
  756:             return OK;
  757:         }
  758:         if (keys(%domconfig) == 0) {
  759:             my $primarylibserv = &Apache::lonnet::domain($dom,'primary');
  760:             my @ids=&Apache::lonnet::current_machine_ids();
  761:             if (!grep(/^\Q$primarylibserv\E$/,@ids)) {
  762:                 my %designhash = &Apache::loncommon::get_domainconf($dom);
  763:                 my @loginimages = ('img','logo','domlogo','login');
  764:                 my $custom_img_count = 0;
  765:                 foreach my $img (@loginimages) {
  766:                     if ($designhash{$dom.'.login.'.$img} ne '') {
  767:                         $custom_img_count ++;
  768:                     }
  769:                 }
  770:                 foreach my $role (@roles) {
  771:                     if ($designhash{$dom.'.'.$role.'.img'} ne '') {
  772:                         $custom_img_count ++;
  773:                     }
  774:                 }
  775:                 if ($custom_img_count > 0) {
  776:                     &Apache::lonconfigsettings::print_header($r,$phase,$context);
  777:                     my $switch_server = &check_switchserver($dom,$confname);
  778:                     $r->print(
  779:     &mt('Domain configuration settings have yet to be saved for this domain via the web-based domain preferences interface.').'<br />'.
  780:     &mt("While this remains so, you must switch to the domain's primary library server in order to update settings.").'<br /><br />'.
  781:     &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 />'.
  782:     &mt("However, you will still need to switch to the domain's primary library server to upload new images or logos.").'<br /><br />');
  783:                     if ($switch_server) {
  784:                         $r->print($switch_server.' '.&mt('to primary library server for domain: [_1]',$dom));
  785:                     }
  786:                     $r->print(&Apache::loncommon::end_page());
  787:                     return OK;
  788:                 }
  789:             }
  790:         }
  791:         &Apache::lonconfigsettings::display_choices($r,$phase,$context,\@prefs_order,\%prefs);
  792:     }
  793:     return OK;
  794: }
  795: 
  796: sub process_changes {
  797:     my ($r,$dom,$confname,$action,$roles,$values,$lastactref) = @_;
  798:     my %domconfig;
  799:     if (ref($values) eq 'HASH') {
  800:         %domconfig = %{$values};
  801:     }
  802:     my $output;
  803:     if ($action eq 'login') {
  804:         $output = &modify_login($r,$dom,$confname,$lastactref,%domconfig);
  805:     } elsif ($action eq 'rolecolors') {
  806:         $output = &modify_rolecolors($r,$dom,$confname,$roles,
  807:                                      $lastactref,%domconfig);
  808:     } elsif ($action eq 'quotas') {
  809:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  810:     } elsif ($action eq 'autoenroll') {
  811:         $output = &modify_autoenroll($dom,$lastactref,%domconfig);
  812:     } elsif ($action eq 'autoupdate') {
  813:         $output = &modify_autoupdate($dom,%domconfig);
  814:     } elsif ($action eq 'autocreate') {
  815:         $output = &modify_autocreate($dom,%domconfig);
  816:     } elsif ($action eq 'directorysrch') {
  817:         $output = &modify_directorysrch($dom,$lastactref,%domconfig);
  818:     } elsif ($action eq 'usercreation') {
  819:         $output = &modify_usercreation($dom,%domconfig);
  820:     } elsif ($action eq 'selfcreation') {
  821:         $output = &modify_selfcreation($dom,$lastactref,%domconfig);
  822:     } elsif ($action eq 'usermodification') {
  823:         $output = &modify_usermodification($dom,%domconfig);
  824:     } elsif ($action eq 'contacts') {
  825:         $output = &modify_contacts($dom,$lastactref,%domconfig);
  826:     } elsif ($action eq 'defaults') {
  827:         $output = &modify_defaults($dom,$lastactref,%domconfig);
  828:     } elsif ($action eq 'scantron') {
  829:         $output = &modify_scantron($r,$dom,$confname,$lastactref,%domconfig);
  830:     } elsif ($action eq 'coursecategories') {
  831:         $output = &modify_coursecategories($dom,$lastactref,%domconfig);
  832:     } elsif ($action eq 'serverstatuses') {
  833:         $output = &modify_serverstatuses($dom,%domconfig);
  834:     } elsif ($action eq 'requestcourses') {
  835:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  836:     } elsif ($action eq 'requestauthor') {
  837:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  838:     } elsif ($action eq 'helpsettings') {
  839:         $output = &modify_helpsettings($r,$dom,$confname,$lastactref,%domconfig);
  840:     } elsif ($action eq 'coursedefaults') {
  841:         $output = &modify_coursedefaults($dom,$lastactref,%domconfig);
  842:     } elsif ($action eq 'selfenrollment') {
  843:         $output = &modify_selfenrollment($dom,$lastactref,%domconfig)
  844:     } elsif ($action eq 'usersessions') {
  845:         $output = &modify_usersessions($dom,$lastactref,%domconfig);
  846:     } elsif ($action eq 'loadbalancing') {
  847:         $output = &modify_loadbalancing($dom,%domconfig);
  848:     } elsif ($action eq 'ltitools') {
  849:         $output = &modify_ltitools($r,$dom,$action,$lastactref,%domconfig);
  850:     } elsif ($action eq 'proctoring') {
  851:         $output = &modify_proctoring($r,$dom,$action,$lastactref,%domconfig);
  852:     } elsif ($action eq 'ssl') {
  853:         $output = &modify_ssl($dom,$lastactref,%domconfig);
  854:     } elsif ($action eq 'trust') {
  855:         $output = &modify_trust($dom,$lastactref,%domconfig);
  856:     } elsif ($action eq 'lti') {
  857:         $output = &modify_lti($r,$dom,$action,$lastactref,%domconfig);
  858:     } elsif ($action eq 'privacy') {
  859:         $output = &modify_privacy($dom,%domconfig);
  860:     } elsif ($action eq 'passwords') {
  861:         $output = &modify_passwords($r,$dom,$confname,$lastactref,%domconfig);
  862:     } elsif ($action eq 'wafproxy') {
  863:         $output = &modify_wafproxy($dom,$action,$lastactref,%domconfig);
  864:     } elsif ($action eq 'ipaccess') {
  865:         $output = &modify_ipaccess($dom,$lastactref,%domconfig);
  866:     }
  867:     return $output;
  868: }
  869: 
  870: sub print_config_box {
  871:     my ($r,$dom,$confname,$phase,$action,$item,$settings) = @_;
  872:     my $rowtotal = 0;
  873:     my $output;
  874:     if ($action eq 'coursecategories') {
  875:         $output = &coursecategories_javascript($settings);
  876:     } elsif ($action eq 'defaults') {
  877:         $output = &defaults_javascript($settings); 
  878:     } elsif ($action eq 'passwords') {
  879:         $output = &passwords_javascript($action);
  880:     } elsif ($action eq 'helpsettings') {
  881:         my (%privs,%levelscurrent);
  882:         my %full=();
  883:         my %levels=(
  884:                      course => {},
  885:                      domain => {},
  886:                      system => {},
  887:                    );
  888:         my $context = 'domain';
  889:         my $crstype = 'Course';
  890:         my $formname = 'display';
  891:         &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
  892:         my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
  893:         $output =
  894:             &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,\%full, 
  895:                                                       \@templateroles);
  896:     } elsif ($action eq 'ltitools') {
  897:         $output .= &ltitools_javascript($settings);
  898:     } elsif ($action eq 'lti') {
  899:         $output .= &passwords_javascript('secrets')."\n".
  900:                    &lti_javascript($dom,$settings);
  901:     } elsif ($action eq 'proctoring') {
  902:         $output .= &proctoring_javascript($settings);
  903:     } elsif ($action eq 'wafproxy') {
  904:         $output .= &wafproxy_javascript($dom);
  905:     } elsif ($action eq 'autoupdate') {
  906:         $output .= &autoupdate_javascript();
  907:     } elsif ($action eq 'autoenroll') {
  908:         $output .= &autoenroll_javascript();
  909:     } elsif ($action eq 'login') {
  910:         $output .= &saml_javascript();
  911:     } elsif ($action eq 'ipaccess') {
  912:         $output .= &ipaccess_javascript($settings);
  913:     }
  914:     $output .=
  915:          '<table class="LC_nested_outer">
  916:           <tr>
  917:            <th class="LC_left_item LC_middle"><span class="LC_nobreak">'.
  918:            &mt($item->{text}).'&nbsp;'.
  919:            &Apache::loncommon::help_open_topic($item->{'help'}).'</span></th>'."\n".
  920:           '</tr>';
  921:     $rowtotal ++;
  922:     my $numheaders = 1;
  923:     if (ref($item->{'header'}) eq 'ARRAY') {
  924:         $numheaders = scalar(@{$item->{'header'}});
  925:     }
  926:     if ($numheaders > 1) {
  927:         my $colspan = '';
  928:         my $rightcolspan = '';
  929:         my $leftnobr = '';
  930:         if (($action eq 'rolecolors') || ($action eq 'defaults') ||
  931:             ($action eq 'directorysrch') ||
  932:             (($action eq 'login') && ($numheaders < 5))) {
  933:             $colspan = ' colspan="2"';
  934:         }
  935:         if ($action eq 'usersessions') {
  936:             $rightcolspan = ' colspan="3"'; 
  937:         }
  938:         if ($action eq 'passwords') {
  939:             $leftnobr = ' LC_nobreak';
  940:         }
  941:         $output .= '
  942:           <tr>
  943:            <td>
  944:             <table class="LC_nested">
  945:              <tr class="LC_info_row">
  946:               <td class="LC_left_item'.$leftnobr.'"'.$colspan.'>'.&mt($item->{'header'}->[0]->{'col1'}).'</td>
  947:               <td class="LC_right_item"'.$rightcolspan.'>'.&mt($item->{'header'}->[0]->{'col2'}).'</td>
  948:              </tr>';
  949:         $rowtotal ++;
  950:         if (($action eq 'autoupdate') || ($action eq 'usercreation') || ($action eq 'selfcreation') ||
  951:             ($action eq 'usermodification') || ($action eq 'defaults') || ($action eq 'coursedefaults') ||
  952:             ($action eq 'selfenrollment') || ($action eq 'usersessions') || ($action eq 'ssl') ||
  953:             ($action eq 'directorysrch') || ($action eq 'trust') || ($action eq 'helpsettings') ||
  954:             ($action eq 'contacts') || ($action eq 'privacy') || ($action eq 'wafproxy') || ($action eq 'lti')) {
  955:             $output .= $item->{'print'}->('top',$dom,$settings,\$rowtotal);
  956:         } elsif ($action eq 'passwords') {
  957:             $output .= $item->{'print'}->('top',$dom,$confname,$settings,\$rowtotal);
  958:         } elsif ($action eq 'coursecategories') {
  959:             $output .= $item->{'print'}->('top',$dom,$item,$settings,\$rowtotal);
  960:         } elsif ($action eq 'scantron') {
  961:             $output .= $item->{'print'}->($r,'top',$dom,$confname,$settings,\$rowtotal);
  962:         } elsif ($action eq 'login') {
  963:             if ($numheaders == 5) {
  964:                 $colspan = ' colspan="2"';
  965:                 $output .= &print_login('service',$dom,$confname,$phase,$settings,\$rowtotal);
  966:             } else {
  967:                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal);
  968:             }
  969:         } elsif (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
  970:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
  971:         } elsif ($action eq 'rolecolors') {
  972:             $output .= &print_rolecolors($phase,'student',$dom,$confname,$settings,\$rowtotal);
  973:         }
  974:         $output .= '
  975:            </table>
  976:           </td>
  977:          </tr>
  978:          <tr>
  979:            <td>
  980:             <table class="LC_nested">
  981:              <tr class="LC_info_row">
  982:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col1'}).'</td>
  983:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col2'}).'</td>
  984:              </tr>';
  985:             $rowtotal ++;
  986:         if (($action eq 'autoupdate') || ($action eq 'usercreation') ||
  987:             ($action eq 'selfcreation') || ($action eq 'selfenrollment') ||
  988:             ($action eq 'usersessions') || ($action eq 'coursecategories') || 
  989:             ($action eq 'trust') || ($action eq 'contacts') || ($action eq 'defaults') ||
  990:             ($action eq 'privacy') || ($action eq 'passwords') || ($action eq 'lti')) {
  991:             if ($action eq 'coursecategories') {
  992:                 $output .= &print_coursecategories('middle',$dom,$item,$settings,\$rowtotal);
  993:                 $colspan = ' colspan="2"';
  994:             } elsif ($action eq 'trust') {
  995:                 $output .= $item->{'print'}->('shared',$dom,$settings,\$rowtotal);
  996:             } elsif ($action eq 'passwords') {
  997:                 $output .= $item->{'print'}->('middle',$dom,$confname,$settings,\$rowtotal);
  998:             } else {
  999:                 $output .= $item->{'print'}->('middle',$dom,$settings,\$rowtotal);
 1000:             }
 1001:             if ($action eq 'trust') {
 1002:                 $output .= '
 1003:             </table>
 1004:           </td>
 1005:          </tr>';
 1006:                 my @trusthdrs = qw(2 3 4 5 6 7);
 1007:                 my @prefixes = qw(enroll othcoau coaurem domroles catalog reqcrs);
 1008:                 for (my $i=0; $i<@trusthdrs; $i++) {
 1009:                     $output .= '
 1010:          <tr>
 1011:            <td>
 1012:             <table class="LC_nested">
 1013:              <tr class="LC_info_row">
 1014:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[$trusthdrs[$i]]->{'col1'}).'</td>
 1015:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[$trusthdrs[$i]]->{'col2'}).'</td></tr>'.
 1016:                            $item->{'print'}->($prefixes[$i],$dom,$settings,\$rowtotal).'
 1017:             </table>
 1018:           </td>
 1019:          </tr>';
 1020:                 }
 1021:                 $output .= '
 1022:          <tr>
 1023:            <td>
 1024:             <table class="LC_nested">
 1025:              <tr class="LC_info_row">
 1026:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[8]->{'col1'}).'</td>
 1027:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[8]->{'col2'}).'</td></tr>'.
 1028:                            $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1029:             } else {
 1030:                 $output .= '
 1031:            </table>
 1032:           </td>
 1033:          </tr>
 1034:          <tr>
 1035:            <td>
 1036:             <table class="LC_nested">
 1037:              <tr class="LC_info_row">
 1038:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1039:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
 1040:              </tr>'."\n";
 1041:                 if ($action eq 'coursecategories') {
 1042:                     $output .= &print_coursecategories('bottom',$dom,$item,$settings,\$rowtotal);
 1043:                 } elsif (($action eq 'contacts') || ($action eq 'privacy') || 
 1044:                          ($action eq 'passwords') || ($action eq 'lti')) {
 1045:                     if ($action eq 'passwords') {
 1046:                         $output .= $item->{'print'}->('lower',$dom,$confname,$settings,\$rowtotal);
 1047:                     } else {
 1048:                         $output .= $item->{'print'}->('lower',$dom,$settings,\$rowtotal);
 1049:                     }
 1050:                     $output .= '
 1051:              </tr>
 1052:             </table>
 1053:            </td>
 1054:           </tr>
 1055:           <tr>
 1056:            <td>
 1057:             <table class="LC_nested">
 1058:              <tr class="LC_info_row">
 1059:               <td class="LC_left_item'.$leftnobr.'"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1060:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td></tr>'."\n";
 1061:                     if ($action eq 'passwords') {
 1062:                         $output .= $item->{'print'}->('bottom',$dom,$confname,$settings,\$rowtotal);
 1063:                     } else {
 1064:                         $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1065:                     }
 1066:                     $output .= '
 1067:             </table>
 1068:           </td>
 1069:          </tr>
 1070:          <tr>';
 1071:                 } else {
 1072:                     $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1073:                 }
 1074:             }
 1075:             $rowtotal ++;
 1076:         } elsif (($action eq 'usermodification') || ($action eq 'coursedefaults') ||
 1077:                  ($action eq 'directorysrch') || ($action eq 'helpsettings') ||
 1078:                  ($action eq 'wafproxy')) {
 1079:             $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1080:         } elsif ($action eq 'scantron') {
 1081:             $output .= $item->{'print'}->($r,'bottom',$dom,$confname,$settings,\$rowtotal);
 1082:         } elsif ($action eq 'ssl') {
 1083:             $output .= $item->{'print'}->('connto',$dom,$settings,\$rowtotal).'
 1084:             </table>
 1085:           </td>
 1086:          </tr>
 1087:          <tr>
 1088:            <td>
 1089:             <table class="LC_nested">
 1090:              <tr class="LC_info_row">
 1091:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1092:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td></tr>'.
 1093:                            $item->{'print'}->('connfrom',$dom,$settings,\$rowtotal).'
 1094:             </table>
 1095:           </td>
 1096:          </tr>
 1097:          <tr>
 1098:            <td>
 1099:             <table class="LC_nested">
 1100:              <tr class="LC_info_row">
 1101:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1102:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td></tr>'.
 1103:                            $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1104:         } elsif ($action eq 'login') {
 1105:             if ($numheaders == 5) {
 1106:                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal).'
 1107:            </table>
 1108:           </td>
 1109:          </tr>
 1110:          <tr>
 1111:            <td>
 1112:             <table class="LC_nested">
 1113:              <tr class="LC_info_row">
 1114:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1115:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td></tr>'.
 1116:                        &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
 1117:                 $rowtotal ++;
 1118:             } else {
 1119:                 $output .= &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
 1120:             }
 1121:             $output .= '
 1122:            </table>
 1123:           </td>
 1124:          </tr>
 1125:          <tr>
 1126:            <td>
 1127:             <table class="LC_nested">
 1128:              <tr class="LC_info_row">';
 1129:             if ($numheaders == 5) {
 1130:                 $output .= '
 1131:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1132:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
 1133:              </tr>';
 1134:             } else {
 1135:                 $output .= '
 1136:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1137:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
 1138:              </tr>';
 1139:             }
 1140:             $rowtotal ++;
 1141:             $output .= &print_login('headtag',$dom,$confname,$phase,$settings,\$rowtotal).'
 1142:            </table>
 1143:           </td>
 1144:          </tr>
 1145:          <tr>
 1146:            <td>
 1147:             <table class="LC_nested">
 1148:              <tr class="LC_info_row">';
 1149:             if ($numheaders == 5) {
 1150:                 $output .= '
 1151:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[4]->{'col1'}).'</td>
 1152:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[4]->{'col2'}).'</td>
 1153:              </tr>';
 1154:             } else {
 1155:                 $output .= '
 1156:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1157:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
 1158:              </tr>';
 1159:             }
 1160:             $rowtotal ++;
 1161:             $output .= &print_login('saml',$dom,$confname,$phase,$settings,\$rowtotal);
 1162:         } elsif ($action eq 'requestcourses') {
 1163:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
 1164:             $rowtotal ++;
 1165:             $output .= &print_studentcode($settings,\$rowtotal).'
 1166:            </table>
 1167:           </td>
 1168:          </tr>
 1169:          <tr>
 1170:            <td>
 1171:             <table class="LC_nested">
 1172:              <tr class="LC_info_row">
 1173:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1174:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td> </tr>'.
 1175:                        &textbookcourses_javascript($settings).
 1176:                        &print_textbookcourses($dom,'textbooks',$settings,\$rowtotal).'
 1177:             </table>
 1178:            </td>
 1179:           </tr>
 1180:          <tr>
 1181:            <td>
 1182:             <table class="LC_nested">
 1183:              <tr class="LC_info_row">
 1184:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1185:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td> </tr>'.
 1186:                        &print_textbookcourses($dom,'templates',$settings,\$rowtotal).'
 1187:             </table>
 1188:            </td>
 1189:           </tr>
 1190:           <tr>
 1191:            <td>
 1192:             <table class="LC_nested">
 1193:              <tr class="LC_info_row">
 1194:               <td class="LC_left_item"'.$colspan.' style="vertical-align: top">'.&mt($item->{'header'}->[4]->{'col1'}).'</td>
 1195:               <td class="LC_right_item" style="vertical-align: top">'.&mt($item->{'header'}->[4]->{'col2'}).'</td>
 1196:              </tr>'.
 1197:             &print_validation_rows('requestcourses',$dom,$settings,\$rowtotal);
 1198:         } elsif ($action eq 'requestauthor') {
 1199:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
 1200:             $rowtotal ++;
 1201:         } elsif ($action eq 'rolecolors') {
 1202:             $output .= &print_rolecolors($phase,'coordinator',$dom,$confname,$settings,\$rowtotal).'
 1203:            </table>
 1204:           </td>
 1205:          </tr>
 1206:          <tr>
 1207:            <td>
 1208:             <table class="LC_nested">
 1209:              <tr class="LC_info_row">
 1210:               <td class="LC_left_item"'.$colspan.' style="vertical-align: top">'.
 1211:                &mt($item->{'header'}->[2]->{'col1'}).'</td>
 1212:               <td class="LC_right_item" style="vertical-align: top">'.
 1213:                &mt($item->{'header'}->[2]->{'col2'}).'</td>
 1214:              </tr>'.
 1215:             &print_rolecolors($phase,'author',$dom,$confname,$settings,\$rowtotal).'
 1216:            </table>
 1217:           </td>
 1218:          </tr>
 1219:          <tr>
 1220:            <td>
 1221:             <table class="LC_nested">
 1222:              <tr class="LC_info_row">
 1223:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1224:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
 1225:              </tr>'.
 1226:             &print_rolecolors($phase,'admin',$dom,$confname,$settings,\$rowtotal);
 1227:             $rowtotal += 2;
 1228:         }
 1229:     } else {
 1230:         $output .= '
 1231:           <tr>
 1232:            <td>
 1233:             <table class="LC_nested">
 1234:              <tr class="LC_info_row">';
 1235:         if ($action eq 'login') {
 1236:             $output .= '  
 1237:               <td class="LC_left_item" colspan="2">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
 1238:         } elsif ($action eq 'serverstatuses') {
 1239:             $output .= '
 1240:               <td class="LC_left_item" style="vertical-align: top">'.&mt($item->{'header'}->[0]->{'col1'}).
 1241:               '<br />('.&mt('Automatic access for Dom. Coords.').')</td>';
 1242: 
 1243:         } else {
 1244:             $output .= '
 1245:               <td class="LC_left_item" style="vertical-align: top">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
 1246:         }
 1247:         if (defined($item->{'header'}->[0]->{'col3'})) {
 1248:             $output .= '<td class="LC_left_item" style="vertical-align: top">'.
 1249:                        &mt($item->{'header'}->[0]->{'col2'});
 1250:             if ($action eq 'serverstatuses') {
 1251:                 $output .= '<br />(<tt>'.&mt('user1:domain1,user2:domain2 etc.').'</tt>)';
 1252:             } 
 1253:         } else {
 1254:             $output .= '<td class="LC_right_item" style="vertical-align: top">'.
 1255:                        &mt($item->{'header'}->[0]->{'col2'});
 1256:         }
 1257:         $output .= '</td>';
 1258:         if ($item->{'header'}->[0]->{'col3'}) {
 1259:             if (defined($item->{'header'}->[0]->{'col4'})) {
 1260:                 $output .= '<td class="LC_left_item" style="vertical-align: top">'.
 1261:                             &mt($item->{'header'}->[0]->{'col3'});
 1262:             } else {
 1263:                 $output .= '<td class="LC_right_item" style="vertical-align: top">'.
 1264:                            &mt($item->{'header'}->[0]->{'col3'});
 1265:             }
 1266:             if ($action eq 'serverstatuses') {
 1267:                 $output .= '<br />(<tt>'.&mt('IP1,IP2 etc.').'</tt>)';
 1268:             }
 1269:             $output .= '</td>';
 1270:         }
 1271:         if ($item->{'header'}->[0]->{'col4'}) {
 1272:             $output .= '<td class="LC_right_item" style="vertical-align: top">'.
 1273:                        &mt($item->{'header'}->[0]->{'col4'});
 1274:         }
 1275:         $output .= '</tr>';
 1276:         $rowtotal ++;
 1277:         if ($action eq 'quotas') {
 1278:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
 1279:         } elsif (($action eq 'autoenroll') || ($action eq 'autocreate') || 
 1280:                  ($action eq 'serverstatuses') || ($action eq 'loadbalancing') || 
 1281:                  ($action eq 'ltitools') || ($action eq 'proctoring') ||
 1282:                  ($action eq 'ipaccess')) {
 1283:             $output .= $item->{'print'}->($dom,$settings,\$rowtotal);
 1284:         }
 1285:     }
 1286:     $output .= '
 1287:    </table>
 1288:   </td>
 1289:  </tr>
 1290: </table><br />';
 1291:     return ($output,$rowtotal);
 1292: }
 1293: 
 1294: sub print_login {
 1295:     my ($caller,$dom,$confname,$phase,$settings,$rowtotal) = @_;
 1296:     my ($css_class,$datatable,$switchserver,%lt);
 1297:     my %choices = &login_choices();
 1298:     if (($caller eq 'help') || ($caller eq 'headtag') || ($caller eq 'saml')) {
 1299:         %lt = &login_file_options();
 1300:         $switchserver = &check_switchserver($dom,$confname);
 1301:     }
 1302:     if ($caller eq 'service') {
 1303:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 1304:         my $choice = $choices{'disallowlogin'};
 1305:         $css_class = ' class="LC_odd_row"';
 1306:         $datatable .= '<tr'.$css_class.'><td>'.$choice.'</td>'.
 1307:                       '<td style="text-align: right"><table><tr><th>'.$choices{'hostid'}.'</th>'.
 1308:                       '<th>'.$choices{'server'}.'</th>'.
 1309:                       '<th>'.$choices{'serverpath'}.'</th>'.
 1310:                       '<th>'.$choices{'custompath'}.'</th>'.
 1311:                       '<th><span class="LC_nobreak">'.$choices{'exempt'}.'</span></th></tr>'."\n";
 1312:         my %disallowed;
 1313:         if (ref($settings) eq 'HASH') {
 1314:             if (ref($settings->{'loginvia'}) eq 'HASH') {
 1315:                %disallowed = %{$settings->{'loginvia'}};
 1316:             }
 1317:         }
 1318:         foreach my $lonhost (sort(keys(%servers))) {
 1319:             my $direct = 'selected="selected"';
 1320:             if (ref($disallowed{$lonhost}) eq 'HASH') {
 1321:                 if ($disallowed{$lonhost}{'server'} ne '') {
 1322:                     $direct = '';
 1323:                 }
 1324:             }
 1325:             $datatable .= '<tr><td>'.$servers{$lonhost}.'</td>'.
 1326:                           '<td><select name="'.$lonhost.'_server">'.
 1327:                           '<option value=""'.$direct.'>'.$choices{'directlogin'}.
 1328:                           '</option>';
 1329:             foreach my $hostid (sort(keys(%servers))) {
 1330:                 next if ($servers{$hostid} eq $servers{$lonhost});
 1331:                 my $selected = '';
 1332:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
 1333:                     if ($hostid eq $disallowed{$lonhost}{'server'}) {
 1334:                         $selected = 'selected="selected"';
 1335:                     }
 1336:                 }
 1337:                 $datatable .= '<option value="'.$hostid.'"'.$selected.'>'.
 1338:                               $servers{$hostid}.'</option>';
 1339:             }
 1340:             $datatable .= '</select></td>'.
 1341:                           '<td><select name="'.$lonhost.'_serverpath">';
 1342:             foreach my $path ('','/','/adm/login','/adm/roles','custom') {
 1343:                 my $pathname = $path;
 1344:                 if ($path eq 'custom') {
 1345:                     $pathname = &mt('Custom Path').' ->';
 1346:                 }
 1347:                 my $selected = '';
 1348:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
 1349:                     if ($path eq $disallowed{$lonhost}{'serverpath'}) {
 1350:                         $selected = 'selected="selected"';
 1351:                     }
 1352:                 } elsif ($path eq '') {
 1353:                     $selected = 'selected="selected"';
 1354:                 }
 1355:                 $datatable .= '<option value="'.$path.'"'.$selected.'>'.$pathname.'</option>';
 1356:             }
 1357:             $datatable .= '</select></td>';
 1358:             my ($custom,$exempt);
 1359:             if (ref($disallowed{$lonhost}) eq 'HASH') {
 1360:                 $custom = $disallowed{$lonhost}{'custompath'};
 1361:                 $exempt = $disallowed{$lonhost}{'exempt'};
 1362:             }
 1363:             $datatable .= '<td><input type="text" name="'.$lonhost.'_custompath" size="6" value="'.$custom.'" /></td>'.
 1364:                           '<td><input type="text" name="'.$lonhost.'_exempt" size="8" value="'.$exempt.'" /></td>'.
 1365:                           '</tr>';
 1366:         }
 1367:         $datatable .= '</table></td></tr>';
 1368:         return $datatable;
 1369:     } elsif ($caller eq 'page') {
 1370:         my %defaultchecked = ( 
 1371:                                'coursecatalog' => 'on',
 1372:                                'helpdesk'      => 'on',
 1373:                                'adminmail'     => 'off',
 1374:                                'newuser'       => 'off',
 1375:                              );
 1376:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
 1377:         my (%checkedon,%checkedoff);
 1378:         foreach my $item (@toggles) {
 1379:             if ($defaultchecked{$item} eq 'on') { 
 1380:                 $checkedon{$item} = ' checked="checked" ';
 1381:                 $checkedoff{$item} = ' ';
 1382:             } elsif ($defaultchecked{$item} eq 'off') {
 1383:                 $checkedoff{$item} = ' checked="checked" ';
 1384:                 $checkedon{$item} = ' ';
 1385:             }
 1386:         }
 1387:         my @images = ('img','logo','domlogo','login');
 1388:         my @alttext = ('img','logo','domlogo');
 1389:         my @logintext = ('textcol','bgcol');
 1390:         my @bgs = ('pgbg','mainbg','sidebg');
 1391:         my @links = ('link','alink','vlink');
 1392:         my %designhash = &Apache::loncommon::get_domainconf($dom);
 1393:         my %defaultdesign = %Apache::loncommon::defaultdesign;
 1394:         my (%is_custom,%designs);
 1395:         my %defaults = (
 1396:                        font => $defaultdesign{'login.font'},
 1397:                        );
 1398:         foreach my $item (@images) {
 1399:             $defaults{$item} = $defaultdesign{'login.'.$item};
 1400:             $defaults{'showlogo'}{$item} = 1;
 1401:         }
 1402:         foreach my $item (@bgs) {
 1403:             $defaults{'bgs'}{$item} = $defaultdesign{'login.'.$item};
 1404:         }
 1405:         foreach my $item (@logintext) {
 1406:             $defaults{'logintext'}{$item} = $defaultdesign{'login.'.$item};
 1407:         }
 1408:         foreach my $item (@links) {
 1409:             $defaults{'links'}{$item} = $defaultdesign{'login.'.$item};
 1410:         }
 1411:         if (ref($settings) eq 'HASH') {
 1412:             foreach my $item (@toggles) {
 1413:                 if ($settings->{$item} eq '1') {
 1414:                     $checkedon{$item} =  ' checked="checked" ';
 1415:                     $checkedoff{$item} = ' ';
 1416:                 } elsif ($settings->{$item} eq '0') {
 1417:                     $checkedoff{$item} =  ' checked="checked" ';
 1418:                     $checkedon{$item} = ' ';
 1419:                 }
 1420:             }
 1421:             foreach my $item (@images) {
 1422:                 if (defined($settings->{$item})) {
 1423:                     $designs{$item} = $settings->{$item};
 1424:                     $is_custom{$item} = 1;
 1425:                 }
 1426:                 if (defined($settings->{'showlogo'}{$item})) {
 1427:                     $designs{'showlogo'}{$item} = $settings->{'showlogo'}{$item};
 1428:                 }
 1429:             }
 1430:             foreach my $item (@alttext) {
 1431:                 if (ref($settings->{'alttext'}) eq 'HASH') {
 1432:                     if ($settings->{'alttext'}->{$item} ne '') {
 1433:                         $designs{'alttext'}{$item} = $settings->{'alttext'}{$item};
 1434:                     }
 1435:                 }
 1436:             }
 1437:             foreach my $item (@logintext) {
 1438:                 if ($settings->{$item} ne '') {
 1439:                     $designs{'logintext'}{$item} = $settings->{$item};
 1440:                     $is_custom{$item} = 1;
 1441:                 }
 1442:             }
 1443:             if ($settings->{'font'} ne '') {
 1444:                 $designs{'font'} = $settings->{'font'};
 1445:                 $is_custom{'font'} = 1;
 1446:             }
 1447:             foreach my $item (@bgs) {
 1448:                 if ($settings->{$item} ne '') {
 1449:                     $designs{'bgs'}{$item} = $settings->{$item};
 1450:                     $is_custom{$item} = 1;
 1451:                 }
 1452:             }
 1453:             foreach my $item (@links) {
 1454:                 if ($settings->{$item} ne '') {
 1455:                     $designs{'links'}{$item} = $settings->{$item};
 1456:                     $is_custom{$item} = 1;
 1457:                 }
 1458:             }
 1459:         } else {
 1460:             if ($designhash{$dom.'.login.font'} ne '') {
 1461:                 $designs{'font'} = $designhash{$dom.'.login.font'};
 1462:                 $is_custom{'font'} = 1;
 1463:             }
 1464:             foreach my $item (@images) {
 1465:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1466:                     $designs{$item} = $designhash{$dom.'.login.'.$item};
 1467:                     $is_custom{$item} = 1;
 1468:                 }
 1469:             }
 1470:             foreach my $item (@bgs) {
 1471:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1472:                     $designs{'bgs'}{$item} = $designhash{$dom.'.login.'.$item};
 1473:                     $is_custom{$item} = 1;
 1474:                 }
 1475:             }
 1476:             foreach my $item (@links) {
 1477:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1478:                     $designs{'links'}{$item} = $designhash{$dom.'.login.'.$item};
 1479:                     $is_custom{$item} = 1;
 1480:                 }
 1481:             }
 1482:         }
 1483:         my %alt_text = &Apache::lonlocal::texthash  ( img => 'Log-in banner',
 1484:                                                       logo => 'Institution Logo',
 1485:                                                       domlogo => 'Domain Logo',
 1486:                                                       login => 'Login box');
 1487:         my $itemcount = 1;
 1488:         foreach my $item (@toggles) {
 1489:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1490:             $datatable .=  
 1491:                 '<tr'.$css_class.'><td colspan="2">'.$choices{$item}.
 1492:                 '</td><td>'.
 1493:                 '<span class="LC_nobreak"><label><input type="radio" name="'.
 1494:                 $item.'"'.$checkedon{$item}.' value="1" />'.&mt('Yes').
 1495:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'"'.
 1496:                 $checkedoff{$item}.' value="0" />'.&mt('No').'</label></span></td>'.
 1497:                 '</tr>';
 1498:             $itemcount ++;
 1499:         }
 1500:         $datatable .= &display_color_options($dom,$confname,$phase,'login',$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal,\@logintext);
 1501:         $datatable .= '</tr></table></td></tr>';
 1502:     } elsif ($caller eq 'help') {
 1503:         my ($defaulturl,$defaulttype,%url,%type,%langchoices);
 1504:         my $itemcount = 1;
 1505:         $defaulturl = '/adm/loginproblems.html';
 1506:         $defaulttype = 'default';
 1507:         %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
 1508:         my @currlangs;
 1509:         if (ref($settings) eq 'HASH') {
 1510:             if (ref($settings->{'helpurl'}) eq 'HASH') {
 1511:                 foreach my $key (sort(keys(%{$settings->{'helpurl'}}))) {
 1512:                     next if ($settings->{'helpurl'}{$key} eq '');
 1513:                     $url{$key} = $settings->{'helpurl'}{$key}.'?inhibitmenu=yes';
 1514:                     $type{$key} = 'custom';
 1515:                     unless ($key eq 'nolang') {
 1516:                         push(@currlangs,$key);
 1517:                     }
 1518:                 }
 1519:             } elsif ($settings->{'helpurl'} ne '') {
 1520:                 $type{'nolang'} = 'custom';
 1521:                 $url{'nolang'} = $settings->{'helpurl'}.'?inhibitmenu=yes';
 1522:             }
 1523:         }
 1524:         foreach my $lang ('nolang',sort(@currlangs)) {
 1525:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1526:             $datatable .= '<tr'.$css_class.'>';
 1527:             if ($url{$lang} eq '') {
 1528:                 $url{$lang} = $defaulturl;
 1529:             }
 1530:             if ($type{$lang} eq '') {
 1531:                 $type{$lang} = $defaulttype;
 1532:             }
 1533:             $datatable .= '<td colspan="2"><span class="LC_nobreak">';
 1534:             if ($lang eq 'nolang') {
 1535:                 $datatable .= &mt('Log-in help page if no specific language file: [_1]',
 1536:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1537:             } else {
 1538:                 $datatable .= &mt('Log-in help page for language: [_1] is [_2]',
 1539:                                   $langchoices{$lang},
 1540:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1541:             }
 1542:             $datatable .= '</span></td>'."\n".
 1543:                           '<td class="LC_left_item">';
 1544:             if ($type{$lang} eq 'custom') {
 1545:                 $datatable .= '<span class="LC_nobreak"><label>'.
 1546:                               '<input type="checkbox" name="loginhelpurl_del" value="'.$lang.'" />'.
 1547:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1548:             } else {
 1549:                 $datatable .= $lt{'upl'};
 1550:             }
 1551:             $datatable .='<br />';
 1552:             if ($switchserver) {
 1553:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1554:             } else {
 1555:                 $datatable .= '<input type="file" name="loginhelpurl_'.$lang.'" />';
 1556:             }
 1557:             $datatable .= '</td></tr>';
 1558:             $itemcount ++;
 1559:         }
 1560:         my @addlangs;
 1561:         foreach my $lang (sort(keys(%langchoices))) {
 1562:             next if ((grep(/^\Q$lang\E$/,@currlangs)) || ($lang eq 'x_chef'));
 1563:             push(@addlangs,$lang);
 1564:         }
 1565:         if (@addlangs > 0) {
 1566:             my %toadd;
 1567:             map { $toadd{$_} = $langchoices{$_} ; } @addlangs;
 1568:             $toadd{''} = &mt('Select');
 1569:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1570:             $datatable .= '<tr'.$css_class.'><td class="LC_left_item" colspan="2">'.
 1571:                           &mt('Add log-in help page for a specific language:').'&nbsp;'.
 1572:                           &Apache::loncommon::select_form('','loginhelpurl_add_lang',\%toadd).
 1573:                           '</td><td class="LC_left_item">'.$lt{'upl'}.'<br />';
 1574:             if ($switchserver) {
 1575:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1576:             } else {
 1577:                 $datatable .= '<input type="file" name="loginhelpurl_add_file" />';
 1578:             }
 1579:             $datatable .= '</td></tr>';
 1580:             $itemcount ++;
 1581:         }
 1582:         $datatable .= &captcha_choice('login',$settings,$itemcount);
 1583:     } elsif ($caller eq 'headtag') {
 1584:         my %domservers = &Apache::lonnet::get_servers($dom);
 1585:         my $choice = $choices{'headtag'};
 1586:         $css_class = ' class="LC_odd_row"';
 1587:         $datatable .= '<tr'.$css_class.'><td colspan="2">'.$choice.'</td>'.
 1588:                       '<td style="text-align: left"><table><tr><th>'.$choices{'hostid'}.'</th>'.
 1589:                       '<th>'.$choices{'current'}.'</th>'.
 1590:                       '<th>'.$choices{'action'}.'</th>'.
 1591:                       '<th>'.$choices{'exempt'}.'</th></tr>'."\n";
 1592:         my (%currurls,%currexempt);
 1593:         if (ref($settings) eq 'HASH') {
 1594:             if (ref($settings->{'headtag'}) eq 'HASH') {
 1595:                 foreach my $lonhost (keys(%{$settings->{'headtag'}})) {
 1596:                     if (ref($settings->{'headtag'}{$lonhost}) eq 'HASH') {
 1597:                         $currurls{$lonhost} = $settings->{'headtag'}{$lonhost}{'url'};
 1598:                         $currexempt{$lonhost} = $settings->{'headtag'}{$lonhost}{'exempt'};
 1599:                     }
 1600:                 }
 1601:             }
 1602:         }
 1603:         foreach my $lonhost (sort(keys(%domservers))) {
 1604:             my $exempt = &check_exempt_addresses($currexempt{$lonhost});
 1605:             $datatable .= '<tr><td>'.$domservers{$lonhost}.'</td>';
 1606:             if ($currurls{$lonhost}) {
 1607:                 $datatable .= '<td class="LC_right_item"><a href="'.
 1608:                               "javascript:void(open('$currurls{$lonhost}?inhibitmenu=yes','Custom_HeadTag',
 1609:                               'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
 1610:                               '">'.$lt{'curr'}.'</a></td>'.
 1611:                               '<td><span class="LC_nobreak"><label>'.
 1612:                               '<input type="checkbox" name="loginheadtag_del" value="'.$lonhost.'" />'.
 1613:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1614:             } else {
 1615:                 $datatable .= '<td class="LC_right_item">'.$lt{'none'}.'</td><td>'.$lt{'upl'};
 1616:             }
 1617:             $datatable .='<br />';
 1618:             if ($switchserver) {
 1619:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1620:             } else {
 1621:                 $datatable .= '<input type="file" name="loginheadtag_'.$lonhost.'" />';
 1622:             }
 1623:             $datatable .= '</td><td><input type="text" name="loginheadtagexempt_'.$lonhost.'" value="'.$exempt.'" /></td></tr>';
 1624:         }
 1625:         $datatable .= '</table></td></tr>';
 1626:     } elsif ($caller eq 'saml') {
 1627:         my %domservers = &Apache::lonnet::get_servers($dom);
 1628:         $datatable .= '<tr><td colspan="3" style="text-align: left">'.
 1629:                       '<table><tr><th>'.$choices{'hostid'}.'</th>'.
 1630:                       '<th>'.$choices{'samllanding'}.'</th>'.
 1631:                       '<th>'.$choices{'samloptions'}.'</th></tr>'."\n";
 1632:         my (%saml,%samltext,%samlimg,%samlalt,%samlurl,%samltitle,%samlwindow,%samlnotsso,%styleon,%styleoff);
 1633:         foreach my $lonhost (keys(%domservers)) {
 1634:             $samlurl{$lonhost} = '/adm/sso';
 1635:             $styleon{$lonhost} = 'display:none';
 1636:             $styleoff{$lonhost} = '';
 1637:         }
 1638:         if ((ref($settings) eq 'HASH') && (ref($settings->{'saml'}) eq 'HASH')) {
 1639:             foreach my $lonhost (keys(%{$settings->{'saml'}})) {
 1640:                 if (ref($settings->{'saml'}{$lonhost}) eq 'HASH') {
 1641:                     $saml{$lonhost} = 1;
 1642:                     $samltext{$lonhost} = $settings->{'saml'}{$lonhost}{'text'};
 1643:                     $samlimg{$lonhost} = $settings->{'saml'}{$lonhost}{'img'};
 1644:                     $samlalt{$lonhost} = $settings->{'saml'}{$lonhost}{'alt'};
 1645:                     $samlurl{$lonhost} = $settings->{'saml'}{$lonhost}{'url'};
 1646:                     $samltitle{$lonhost} = $settings->{'saml'}{$lonhost}{'title'};
 1647:                     $samlwindow{$lonhost} = $settings->{'saml'}{$lonhost}{'window'};
 1648:                     $samlnotsso{$lonhost} = $settings->{'saml'}{$lonhost}{'notsso'};
 1649:                     $styleon{$lonhost} = '';
 1650:                     $styleoff{$lonhost} = 'display:none';
 1651:                 } else {
 1652:                     $styleon{$lonhost} = 'display:none';
 1653:                     $styleoff{$lonhost} = '';
 1654:                 }
 1655:             }
 1656:         }
 1657:         my $itemcount = 1;
 1658:         foreach my $lonhost (sort(keys(%domservers))) {
 1659:             my $samlon = ' ';
 1660:             my $samloff = ' checked="checked" ';
 1661:             if ($saml{$lonhost}) {
 1662:                 $samlon = $samloff;
 1663:                 $samloff = ' ';
 1664:             }
 1665:             my $samlwinon = '';
 1666:             my $samlwinoff = ' checked="checked"';
 1667:             if ($samlwindow{$lonhost}) {
 1668:                 $samlwinon = $samlwinoff;
 1669:                 $samlwinoff = '';
 1670:             }
 1671:             my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1672:             $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.$domservers{$lonhost}.'</span></td>'.
 1673:                           '<td><span class="LC_nobreak"><label><input type="radio" name="saml_'.$lonhost.'"'.$samloff.
 1674:                           'onclick="toggleSamlOptions(this.form,'."'$lonhost'".');" value="0" />'.
 1675:                           &mt('No').'</label>'.('&nbsp;'x2).
 1676:                           '<label><input type="radio" name="saml_'.$lonhost.'"'.$samlon.
 1677:                           'onclick="toggleSamlOptions(this.form,'."'$lonhost'".');" value="1" />'.
 1678:                           &mt('Yes').'</label></span></td>'.
 1679:                           '<td id="samloptionson_'.$lonhost.'" style="'.$styleon{$lonhost}.'" width="100%">'.
 1680:                           '<table width="100%"><tr><th colspan="3" align="center">'.&mt('SSO').'</th></tr>'.
 1681:                           '<tr><th>'.&mt('Text').'</th><th>'.&mt('Image').'</th>'.
 1682:                           '<th>'.&mt('Alt Text').'</th></tr>'.
 1683:                           '<tr'.$css_class.'><td><input type="text" name="saml_text_'.$lonhost.'" size="20" value="'.
 1684:                           $samltext{$lonhost}.'" /></td><td>';
 1685:             if ($samlimg{$lonhost}) {
 1686:                 $datatable .= '<img src="'.$samlimg{$lonhost}.'" /><br />'.
 1687:                               '<span class="LC_nobreak"><label>'.
 1688:                               '<input type="checkbox" name="saml_img_del" value="'.$lonhost.'" />'.
 1689:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1690:             } else {
 1691:                 $datatable .= $lt{'upl'};
 1692:             }
 1693:             $datatable .='<br />';
 1694:             if ($switchserver) {
 1695:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1696:             } else {
 1697:                 $datatable .= '<input type="file" name="saml_img_'.$lonhost.'" />';
 1698:             }
 1699:             $datatable .= '</td>'.
 1700:                           '<td><input type="text" name="saml_alt_'.$lonhost.'" size="25" '.
 1701:                           'value="'.$samlalt{$lonhost}.'" /></td></tr></table><br />'.
 1702:                           '<table width="100%"><tr><th colspan="3" align="center">'.&mt('SSO').'</th><th align="center">'.
 1703:                           '<span class="LC_nobreak">'.&mt('Non-SSO').'</span></th></tr>'.
 1704:                           '<tr><th>'.&mt('URL').'</th><th>'.&mt('Tool Tip').'</th>'.
 1705:                           '<th>'.&mt('Pop-up if iframe').'</th><th>'.&mt('Text').'</th></tr>'.
 1706:                           '<tr'.$css_class.'>'.
 1707:                           '<td><input type="text" name="saml_url_'.$lonhost.'" size="30" '.
 1708:                           'value="'.$samlurl{$lonhost}.'" /></td>'.
 1709:                           '<td><textarea name="saml_title_'.$lonhost.'" rows="3" cols="20">'.
 1710:                           $samltitle{$lonhost}.'</textarea></td>'.
 1711:                           '<td><label><input type="radio" name="saml_window_'.$lonhost.'" value=""'.$samlwinoff.'>'.
 1712:                           &mt('No').'</label>'.('&nbsp;'x2).'<label><input type="radio" '.
 1713:                           'name="saml_window_'.$lonhost.'" value="1"'.$samlwinon.'>'.&mt('Yes').'</label></td>'.
 1714:                           '<td><input type="text" name="saml_notsso_'.$lonhost.'" size="12" '.
 1715:                           'value="'.$samlnotsso{$lonhost}.'" /></td></tr>'.
 1716:                           '</table></td>'.
 1717:                           '<td id="samloptionsoff_'.$lonhost.'" style="'.$styleoff{$lonhost}.'" width="100%">&nbsp;</td></tr>';
 1718:            $itemcount ++;
 1719:         }
 1720:         $datatable .= '</table></td></tr>';
 1721:     }
 1722:     return $datatable;
 1723: }
 1724: 
 1725: sub login_choices {
 1726:     my %choices =
 1727:         &Apache::lonlocal::texthash (
 1728:             coursecatalog => 'Display Course/Community Catalog link?',
 1729:             adminmail     => "Display Administrator's E-mail Address?",
 1730:             helpdesk      => 'Display "Contact Helpdesk" link',
 1731:             disallowlogin => "Login page requests redirected",
 1732:             hostid        => "Server",
 1733:             server        => "Redirect to:",
 1734:             serverpath    => "Path",
 1735:             custompath    => "Custom", 
 1736:             exempt        => "Exempt IP(s)",
 1737:             directlogin   => "No redirect",
 1738:             newuser       => "Link to create a user account",
 1739:             img           => "Header",
 1740:             logo          => "Main Logo",
 1741:             domlogo       => "Domain Logo",
 1742:             login         => "Log-in Header", 
 1743:             textcol       => "Text color",
 1744:             bgcol         => "Box color",
 1745:             bgs           => "Background colors",
 1746:             links         => "Link colors",
 1747:             font          => "Font color",
 1748:             pgbg          => "Header",
 1749:             mainbg        => "Page",
 1750:             sidebg        => "Login box",
 1751:             link          => "Link",
 1752:             alink         => "Active link",
 1753:             vlink         => "Visited link",
 1754:             headtag       => "Custom markup",
 1755:             action        => "Action",
 1756:             current       => "Current",
 1757:             samllanding   => "Dual login?",
 1758:             samloptions   => "Options",
 1759:             alttext       => "Alt text",
 1760:         );
 1761:     return %choices;
 1762: }
 1763: 
 1764: sub login_file_options {
 1765:       return &Apache::lonlocal::texthash(
 1766:                                            del     => 'Delete?',
 1767:                                            rep     => 'Replace:',
 1768:                                            upl     => 'Upload:',
 1769:                                            curr    => 'View contents',
 1770:                                            default => 'Default',
 1771:                                            custom  => 'Custom',
 1772:                                            none    => 'None',
 1773:       );
 1774: }
 1775: 
 1776: sub print_ipaccess {
 1777:     my ($dom,$settings,$rowtotal) = @_;
 1778:     my $css_class;
 1779:     my $itemcount = 0;
 1780:     my $datatable;
 1781:     my %ordered;
 1782:     if (ref($settings) eq 'HASH') {
 1783:         foreach my $item (keys(%{$settings})) {
 1784:             if (ref($settings->{$item}) eq 'HASH') {
 1785:                 my $num = $settings->{$item}{'order'};
 1786:                 if ($num eq '') {
 1787:                     $num = scalar(keys(%{$settings}));
 1788:                 }
 1789:                 $ordered{$num} = $item;
 1790:             }
 1791:         }
 1792:     }
 1793:     my $maxnum = scalar(keys(%ordered));
 1794:     if (keys(%ordered)) {
 1795:         my @items = sort { $a <=> $b } keys(%ordered);
 1796:         for (my $i=0; $i<@items; $i++) {
 1797:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1798:             my $item = $ordered{$items[$i]};
 1799:             my ($name,$ipranges,%commblocks,%courses);
 1800:             if (ref($settings->{$item}) eq 'HASH') {
 1801:                 $name = $settings->{$item}->{'name'};
 1802:                 $ipranges = $settings->{$item}->{'ip'};
 1803:                 if (ref($settings->{$item}->{'commblocks'}) eq 'HASH') {
 1804:                     %commblocks = %{$settings->{$item}->{'commblocks'}};
 1805:                 }
 1806:                 if (ref($settings->{$item}->{'courses'}) eq 'HASH') {
 1807:                     %courses = %{$settings->{$item}->{'courses'}};
 1808:                 }
 1809:             }
 1810:             my $chgstr = ' onchange="javascript:reorderIPaccess(this.form,'."'ipaccess_pos_".$item."'".');"';
 1811:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 1812:                          .'<select name="ipaccess_pos_'.$item.'"'.$chgstr.'>';
 1813:             for (my $k=0; $k<=$maxnum; $k++) {
 1814:                 my $vpos = $k+1;
 1815:                 my $selstr;
 1816:                 if ($k == $i) {
 1817:                     $selstr = ' selected="selected" ';
 1818:                 }
 1819:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 1820:             }
 1821:             $datatable .= '</select>'.('&nbsp;'x2).
 1822:                 '<label><input type="checkbox" name="ipaccess_del" value="'.$item.'" />'.
 1823:                 &mt('Delete?').'</label></span></td>'.
 1824:                 '<td colspan="2"><input type="hidden" name="ipaccess_id_'.$i.'" value="'.$item.'" />'.
 1825:                 &ipaccess_options($i,$itemcount,$dom,$name,$ipranges,\%commblocks,\%courses).
 1826:                 '</td></tr>';
 1827:             $itemcount ++;
 1828:         }
 1829:     }
 1830:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1831:     my $chgstr = ' onchange="javascript:reorderIPaccess(this.form,'."'ipaccess_pos_add'".');"';
 1832:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 1833:                   '<input type="hidden" name="ipaccess_maxnum" value="'.$maxnum.'" />'."\n".
 1834:                   '<select name="ipaccess_pos_add"'.$chgstr.'>';
 1835:     for (my $k=0; $k<$maxnum+1; $k++) {
 1836:         my $vpos = $k+1;
 1837:         my $selstr;
 1838:         if ($k == $maxnum) {
 1839:             $selstr = ' selected="selected" ';
 1840:         }
 1841:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 1842:     }
 1843:     $datatable .= '</select>&nbsp;'."\n".
 1844:                   '<input type="checkbox" name="ipaccess_add" value="1" />'.&mt('Add').'</span></td>'."\n".
 1845:                   '<td colspan="2">'.
 1846:                   &ipaccess_options('add',$itemcount,$dom).
 1847:                   '</td>'."\n".
 1848:                   '</tr>'."\n";
 1849:     $$rowtotal ++;
 1850:     return $datatable;
 1851: }
 1852: 
 1853: sub ipaccess_options {
 1854:     my ($num,$itemcount,$dom,$name,$ipranges,$blocksref,$coursesref) = @_;
 1855:     my (%currblocks,%currcourses,$output);
 1856:     if (ref($blocksref) eq 'HASH') {
 1857:         %currblocks = %{$blocksref};
 1858:     }
 1859:     if (ref($coursesref) eq 'HASH') {
 1860:         %currcourses = %{$coursesref};
 1861:     }
 1862:     $output = '<fieldset><legend>'.&mt('Location(s)').'</legend>'.
 1863:               '<span class="LC_nobreak">'.&mt('Name').':&nbsp;'.
 1864:               '<input type="text" name="ipaccess_name_'.$num.'" value="'.$name.'" />'.
 1865:               '</span></fieldset>'.
 1866:               '<fieldset><legend>'.&mt('IP Range(s)').'</legend>'.
 1867:               &mt('Format for each IP range').': '.&mt('A.B.C.D/N or A.B.C.D-E.F.G.H').'<br />'.
 1868:               &mt('Range(s) will be stored as IP netblock(s) in CIDR notation (comma separated)').'<br />'.
 1869:               '<textarea name="ipaccess_range_'.$num.'" rows="3" cols="80">'.
 1870:               $ipranges.'</textarea></fieldset>'.
 1871:               '<fieldset><legend>'.&mt('Functionality Blocked?').'</legend>'.
 1872:               &blocker_checkboxes($num,$blocksref).'</fieldset>'.
 1873:               '<fieldset><legend>'.&mt('Courses/Communities allowed').'</legend>'.
 1874:               '<table>';
 1875:     foreach my $cid (sort(keys(%currcourses))) {
 1876:         my %courseinfo = &Apache::lonnet::coursedescription($cid,{'one_time' => 1});
 1877:         $output .= '<tr><td><span class="LC_nobreak">'.
 1878:                    '<label><input type="checkbox" name="ipaccess_course_delete_'.$num.'" value="'.$cid.'" />'.
 1879:                    &mt('Delete?').'&nbsp;<span class="LC_cusr_emph">'.$courseinfo{'description'}.'</span></label></span>'.
 1880:                    ' <span class="LC_fontsize_medium">('.$cid.')</span></td></tr>';
 1881:     }
 1882:     $output .= '<tr><td><span class="LC_nobreak">'.&mt('Add').':&nbsp;'.
 1883:                '<input type="text" name="ipaccess_cdesc_'.$num.'" value="" onfocus="this.blur();opencrsbrowser('."'display','ipaccess_cnum_$num','ipaccess_cdom_$num','ipaccess_cdesc_$num'".');" />'.
 1884:                 &Apache::loncommon::selectcourse_link('display','ipaccess_cnum_'.$num,'ipaccess_cdom_'.$num,'ipaccess_cdesc_'.$num,$dom,undef,'Course/Community').
 1885:                '<input type="hidden" name="ipaccess_cnum_'.$num.'" value="" />'.
 1886:                '<input type="hidden" name="ipaccess_cdom_'.$num.'" value="" />'.
 1887:                '</span></td></tr></table>'."\n".
 1888:                '</fieldset>';
 1889:     return $output;
 1890: }
 1891: 
 1892: sub blocker_checkboxes {
 1893:     my ($num,$blocks) = @_;
 1894:     my ($typeorder,$types) = &commblocktype_text();
 1895:     my $numinrow = 6;
 1896:     my $output = '<table>';
 1897:     for (my $i=0; $i<@{$typeorder}; $i++) {
 1898:         my $block = $typeorder->[$i];
 1899:         my $blockstatus;
 1900:         if (ref($blocks) eq 'HASH') {
 1901:             if ($blocks->{$block} eq 'on') {
 1902:                 $blockstatus = 'checked="checked"';
 1903:             }
 1904:         }
 1905:         my $rem = $i%($numinrow);
 1906:         if ($rem == 0) {
 1907:             if ($i > 0) {
 1908:                 $output .= '</tr>';
 1909:             }
 1910:             $output .= '<tr>';
 1911:         }
 1912:         if ($i == scalar(@{$typeorder})-1) {
 1913:             my $colsleft = $numinrow-$rem;
 1914:             if ($colsleft > 1) {
 1915:                 $output .= '<td colspan="'.$colsleft.'">';
 1916:             } else {
 1917:                 $output .= '<td>';
 1918:             }
 1919:         } else {
 1920:             $output .= '<td>';
 1921:         }
 1922:         my $item = 'ipaccess_block_'.$num;
 1923:         if ($blockstatus) {
 1924:             $blockstatus = ' '.$blockstatus;
 1925:         }
 1926:         $output .= '<span class="LC_nobreak"><label>'."\n".
 1927:                    '<input type="checkbox" name="'.$item.'"'.
 1928:                    $blockstatus.' value="'.$block.'"'.' />'.
 1929:                    $types->{$block}.'</label></span>'."\n".
 1930:                    '<br /></td>';
 1931:     }
 1932:     $output .= '</tr></table>';
 1933:     return $output;
 1934: }
 1935: 
 1936: sub commblocktype_text {
 1937:     my %types = &Apache::lonlocal::texthash(
 1938:         'com' => 'Messaging',
 1939:         'chat' => 'Chat Room',
 1940:         'boards' => 'Discussion',
 1941:         'port' => 'Portfolio',
 1942:         'groups' => 'Groups',
 1943:         'blogs' => 'Blogs',
 1944:         'about' => 'User Information',
 1945:         'printout' => 'Printouts',
 1946:         'passwd' => 'Change Password',
 1947:         'grades' => 'Gradebook',
 1948:         'search' => 'Course search',
 1949:         'wishlist' => 'Stored links',
 1950:         'annotate' => 'Annotations',
 1951:     );
 1952:     my $typeorder = ['com','chat','boards','port','groups','blogs','about','wishlist','printout','grades','search','annotate','passwd'];
 1953:     return ($typeorder,\%types);
 1954: }
 1955: 
 1956: sub print_rolecolors {
 1957:     my ($phase,$role,$dom,$confname,$settings,$rowtotal) = @_;
 1958:     my %choices = &color_font_choices();
 1959:     my @bgs = ('pgbg','tabbg','sidebg');
 1960:     my @links = ('link','alink','vlink');
 1961:     my @images = ('img');
 1962:     my %alt_text = &Apache::lonlocal::texthash(img => "Banner for $role role");
 1963:     my %designhash = &Apache::loncommon::get_domainconf($dom);
 1964:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 1965:     my (%is_custom,%designs);
 1966:     my %defaults = &role_defaults($role,\@bgs,\@links,\@images);
 1967:     if (ref($settings) eq 'HASH') {
 1968:         if (ref($settings->{$role}) eq 'HASH') {
 1969:             if ($settings->{$role}->{'img'} ne '') {
 1970:                 $designs{'img'} = $settings->{$role}->{'img'};
 1971:                 $is_custom{'img'} = 1;
 1972:             }
 1973:             if ($settings->{$role}->{'font'} ne '') {
 1974:                 $designs{'font'} = $settings->{$role}->{'font'};
 1975:                 $is_custom{'font'} = 1;
 1976:             }
 1977:             if ($settings->{$role}->{'fontmenu'} ne '') {
 1978:                 $designs{'fontmenu'} = $settings->{$role}->{'fontmenu'};
 1979:                 $is_custom{'fontmenu'} = 1;
 1980:             }
 1981:             foreach my $item (@bgs) {
 1982:                 if ($settings->{$role}->{$item} ne '') {
 1983:                     $designs{'bgs'}{$item} = $settings->{$role}->{$item};
 1984:                     $is_custom{$item} = 1;
 1985:                 }
 1986:             }
 1987:             foreach my $item (@links) {
 1988:                 if ($settings->{$role}->{$item} ne '') {
 1989:                     $designs{'links'}{$item} = $settings->{$role}->{$item};
 1990:                     $is_custom{$item} = 1;
 1991:                 }
 1992:             }
 1993:         }
 1994:     } else {
 1995:         if ($designhash{$dom.'.'.$role.'.img'} ne '') {
 1996:             $designs{img} = $designhash{$dom.'.'.$role.'.img'};
 1997:             $is_custom{'img'} = 1;
 1998:         }
 1999:         if ($designhash{$dom.'.'.$role.'.fontmenu'} ne '') {
 2000:             $designs{fontmenu} = $designhash{$dom.'.'.$role.'.fontmenu'};
 2001:             $is_custom{'fontmenu'} = 1; 
 2002:         }
 2003:         if ($designhash{$dom.'.'.$role.'.font'} ne '') {
 2004:             $designs{font} = $designhash{$dom.'.'.$role.'.font'};
 2005:             $is_custom{'font'} = 1;
 2006:         }
 2007:         foreach my $item (@bgs) {
 2008:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 2009:                 $designs{'bgs'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 2010:                 $is_custom{$item} = 1;
 2011:             
 2012:             }
 2013:         }
 2014:         foreach my $item (@links) {
 2015:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 2016:                 $designs{'links'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 2017:                 $is_custom{$item} = 1;
 2018:             }
 2019:         }
 2020:     }
 2021:     my $itemcount = 1;
 2022:     my $datatable = &display_color_options($dom,$confname,$phase,$role,$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal);
 2023:     $datatable .= '</tr></table></td></tr>';
 2024:     return $datatable;
 2025: }
 2026: 
 2027: sub role_defaults {
 2028:     my ($role,$bgs,$links,$images,$logintext) = @_;
 2029:     my %defaults;
 2030:     unless ((ref($bgs) eq 'ARRAY') && (ref($links) eq 'ARRAY') && (ref($images) eq 'ARRAY')) {
 2031:         return %defaults;
 2032:     }
 2033:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 2034:     if ($role eq 'login') {
 2035:         %defaults = (
 2036:                        font => $defaultdesign{$role.'.font'},
 2037:                     );
 2038:         if (ref($logintext) eq 'ARRAY') {
 2039:             foreach my $item (@{$logintext}) {
 2040:                 $defaults{'logintext'}{$item} = $defaultdesign{$role.'.'.$item};
 2041:             }
 2042:         }
 2043:         foreach my $item (@{$images}) {
 2044:             $defaults{'showlogo'}{$item} = 1;
 2045:         }
 2046:     } else {
 2047:         %defaults = (
 2048:                        img => $defaultdesign{$role.'.img'},
 2049:                        font => $defaultdesign{$role.'.font'},
 2050:                        fontmenu => $defaultdesign{$role.'.fontmenu'},
 2051:                     );
 2052:     }
 2053:     foreach my $item (@{$bgs}) {
 2054:         $defaults{'bgs'}{$item} = $defaultdesign{$role.'.'.$item};
 2055:     }
 2056:     foreach my $item (@{$links}) {
 2057:         $defaults{'links'}{$item} = $defaultdesign{$role.'.'.$item};
 2058:     }
 2059:     foreach my $item (@{$images}) {
 2060:         $defaults{$item} = $defaultdesign{$role.'.'.$item};
 2061:     }
 2062:     return %defaults;
 2063: }
 2064: 
 2065: sub display_color_options {
 2066:     my ($dom,$confname,$phase,$role,$itemcount,$choices,$is_custom,$defaults,$designs,
 2067:         $images,$bgs,$links,$alt_text,$rowtotal,$logintext) = @_;
 2068:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 2069:     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2070:     my $datatable = '<tr'.$css_class.'>'.
 2071:         '<td>'.$choices->{'font'}.'</td>';
 2072:     if (!$is_custom->{'font'}) {
 2073:         $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span class="css_default_'.$role.'_font" style="color: '.$defaults->{'font'}.';">'.$defaults->{'font'}.'</span></td>';
 2074:     } else {
 2075:         $datatable .= '<td>&nbsp;</td>';
 2076:     }
 2077:     my $current_color = $designs->{'font'} ? $designs->{'font'} : $defaults->{'font'};
 2078: 
 2079:     $datatable .= '<td><span class="LC_nobreak">'.
 2080:                   '<input type="text" class="colorchooser" size="10" name="'.$role.'_font"'.
 2081:                   ' value="'.$current_color.'" />&nbsp;'.
 2082:                   '&nbsp;</span></td></tr>';
 2083:     unless ($role eq 'login') { 
 2084:         $datatable .= '<tr'.$css_class.'>'.
 2085:                       '<td>'.$choices->{'fontmenu'}.'</td>';
 2086:         if (!$is_custom->{'fontmenu'}) {
 2087:             $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span class="css_default_'.$role.'_font" style="color: '.$defaults->{'fontmenu'}.';">'.$defaults->{'fontmenu'}.'</span></td>';
 2088:         } else {
 2089:             $datatable .= '<td>&nbsp;</td>';
 2090:         }
 2091: 	$current_color = $designs->{'fontmenu'} ?
 2092: 	    $designs->{'fontmenu'} : $defaults->{'fontmenu'};
 2093:         $datatable .= '<td><span class="LC_nobreak">'.
 2094:                       '<input class="colorchooser" type="text" size="10" name="'
 2095: 		      .$role.'_fontmenu"'.
 2096:                       ' value="'.$current_color.'" />&nbsp;'.
 2097:                       '&nbsp;</span></td></tr>';
 2098:     }
 2099:     my $switchserver = &check_switchserver($dom,$confname);
 2100:     foreach my $img (@{$images}) {
 2101: 	$itemcount ++;
 2102:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2103:         $datatable .= '<tr'.$css_class.'>'.
 2104:                       '<td>'.$choices->{$img};
 2105:         my ($imgfile,$img_import,$login_hdr_pick,$logincolors,$alttext);
 2106:         if ($role eq 'login') {
 2107:             if ($img eq 'login') {
 2108:                 $login_hdr_pick =
 2109:                     &login_header_options($img,$role,$defaults,$is_custom,$choices);
 2110:                 $logincolors =
 2111:                     &login_text_colors($img,$role,$logintext,$phase,$choices,
 2112:                                        $designs,$defaults);
 2113:             } else {
 2114:                 if ($img ne 'domlogo') {
 2115:                     $datatable.= &logo_display_options($img,$defaults,$designs);
 2116:                 }
 2117:                 if (ref($designs->{'alttext'}) eq 'HASH') {
 2118:                     $alttext = $designs->{'alttext'}{$img};
 2119:                 }
 2120:             }
 2121:         }
 2122:         $datatable .= '</td>';
 2123:         if ($designs->{$img} ne '') {
 2124:             $imgfile = $designs->{$img};
 2125: 	    $img_import = ($imgfile =~ m{^/adm/});
 2126:         } else {
 2127:             $imgfile = $defaults->{$img};
 2128:         }
 2129:         if ($imgfile) {
 2130:             my ($showfile,$fullsize);
 2131:             if ($imgfile =~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
 2132:                 my $urldir = $1;
 2133:                 my $filename = $2;
 2134:                 my @info = &Apache::lonnet::stat_file($designs->{$img});
 2135:                 if (@info) {
 2136:                     my $thumbfile = 'tn-'.$filename;
 2137:                     my @thumb=&Apache::lonnet::stat_file($urldir.'/'.$thumbfile);
 2138:                     if (@thumb) {
 2139:                         $showfile = $urldir.'/'.$thumbfile;
 2140:                     } else {
 2141:                         $showfile = $imgfile;
 2142:                     }
 2143:                 } else {
 2144:                     $showfile = '';
 2145:                 }
 2146:             } elsif ($imgfile =~ m-^/(adm/[^/]+)/([^/]+)$-) {
 2147:                 $showfile = $imgfile;
 2148:                 my $imgdir = $1;
 2149:                 my $filename = $2;
 2150:                 if (-e "$londocroot/$imgdir/tn-".$filename) {
 2151:                     $showfile = "/$imgdir/tn-".$filename;
 2152:                 } else {
 2153:                     my $input = $londocroot.$imgfile;
 2154:                     my $output = "$londocroot/$imgdir/tn-".$filename;
 2155:                     if (!-e $output) {
 2156:                         my ($width,$height) = &thumb_dimensions();
 2157:                         my ($fullwidth,$fullheight) = &check_dimensions($input);
 2158:                         if ($fullwidth ne '' && $fullheight ne '') {
 2159:                             if ($fullwidth > $width && $fullheight > $height) { 
 2160:                                 my $size = $width.'x'.$height;
 2161:                                 my @args = ('convert','-sample',$size,$input,$output);
 2162:                                 system({$args[0]} @args);
 2163:                                 $showfile = "/$imgdir/tn-".$filename;
 2164:                             }
 2165:                         }
 2166:                     }
 2167:                 }
 2168:             }
 2169:             if ($showfile) {
 2170:                 if ($showfile =~ m{^/(adm|res)/}) {
 2171:                     if ($showfile =~ m{^/res/}) {
 2172:                         my $local_showfile =
 2173:                             &Apache::lonnet::filelocation('',$showfile);
 2174:                         &Apache::lonnet::repcopy($local_showfile);
 2175:                     }
 2176:                     $showfile = &Apache::loncommon::lonhttpdurl($showfile);
 2177:                 }
 2178:                 if ($imgfile) {
 2179:                     if ($imgfile  =~ m{^/(adm|res)/}) {
 2180:                         if ($imgfile =~ m{^/res/}) {
 2181:                             my $local_imgfile =
 2182:                                 &Apache::lonnet::filelocation('',$imgfile);
 2183:                             &Apache::lonnet::repcopy($local_imgfile);
 2184:                         }
 2185:                         $fullsize = &Apache::loncommon::lonhttpdurl($imgfile);
 2186:                     } else {
 2187:                         $fullsize = $imgfile;
 2188:                     }
 2189:                 }
 2190:                 $datatable .= '<td>';
 2191:                 if ($img eq 'login') {
 2192:                     $datatable .= $login_hdr_pick;
 2193:                 } 
 2194:                 $datatable .= &image_changes($is_custom->{$img},$alt_text->{$img},$img_import,
 2195:                                              $showfile,$fullsize,$role,$img,$imgfile,$logincolors);
 2196:             } else {
 2197:                 $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 2198:                               &mt('Upload:').'<br />';
 2199:             }
 2200:         } else {
 2201:             $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 2202:                           &mt('Upload:').'<br />';
 2203:         }
 2204:         if ($switchserver) {
 2205:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2206:         } else {
 2207:             if ($img ne 'login') { # suppress file selection for Log-in header
 2208:                 $datatable .='&nbsp;<input type="file" name="'.$role.'_'.$img.'" />';
 2209:             }
 2210:         }
 2211:         if (($role eq 'login') && ($img ne 'login')) {
 2212:             $datatable .= ('&nbsp;' x2).' <span class="LC_nobreak"><label>'.$choices->{'alttext'}.':'.
 2213:                           '<input type="text" name="'.$role.'_alt_'.$img.'" size="10" value="'.$alttext.'" />'.
 2214:                           '</label></span>';
 2215:         }
 2216:         $datatable .= '</td></tr>';
 2217:     }
 2218:     $itemcount ++;
 2219:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2220:     $datatable .= '<tr'.$css_class.'>'.
 2221:                   '<td>'.$choices->{'bgs'}.'</td>';
 2222:     my $bgs_def;
 2223:     foreach my $item (@{$bgs}) {
 2224:         if (!$is_custom->{$item}) {
 2225:             $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>';
 2226:         }
 2227:     }
 2228:     if ($bgs_def) {
 2229:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$bgs_def.'</tr></table></td>';
 2230:     } else {
 2231:         $datatable .= '<td>&nbsp;</td>';
 2232:     }
 2233:     $datatable .= '<td class="LC_right_item">'.
 2234:                   '<table border="0"><tr>';
 2235: 
 2236:     foreach my $item (@{$bgs}) {
 2237:         $datatable .= '<td style="text-align: center">'.$choices->{$item};
 2238: 	my $color = $designs->{'bgs'}{$item} ? $designs->{'bgs'}{$item} : $defaults->{'bgs'}{$item};
 2239:         if ($designs->{'bgs'}{$item}) {
 2240:             $datatable .= '&nbsp;';
 2241:         }
 2242:         $datatable .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 2243:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 2244:     }
 2245:     $datatable .= '</tr></table></td></tr>';
 2246:     $itemcount ++;
 2247:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2248:     $datatable .= '<tr'.$css_class.'>'.
 2249:                   '<td>'.$choices->{'links'}.'</td>';
 2250:     my $links_def;
 2251:     foreach my $item (@{$links}) {
 2252:         if (!$is_custom->{$item}) {
 2253:             $links_def .= '<td>'.$choices->{$item}.'<br /><span class="css_default_'.$role.'_'.$item.'" style="color: '.$defaults->{'links'}{$item}.';">'.$defaults->{'links'}{$item}.'</span></td>';
 2254:         }
 2255:     }
 2256:     if ($links_def) {
 2257:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$links_def.'</tr></table></td>';
 2258:     } else {
 2259:         $datatable .= '<td>&nbsp;</td>';
 2260:     }
 2261:     $datatable .= '<td class="LC_right_item">'.
 2262:                   '<table border="0"><tr>';
 2263:     foreach my $item (@{$links}) {
 2264: 	my $color = $designs->{'links'}{$item} ? $designs->{'links'}{$item} : $defaults->{'links'}{$item};
 2265:         $datatable .= '<td style="text-align: center">'.$choices->{$item}."\n";
 2266:         if ($designs->{'links'}{$item}) {
 2267:             $datatable.='&nbsp;';
 2268:         }
 2269:         $datatable .= '<br /><input type="text" size="8" class="colorchooser" name="'.$role.'_'.$item.'" value="'.$color.
 2270:                       '" /></td>';
 2271:     }
 2272:     $$rowtotal += $itemcount;
 2273:     return $datatable;
 2274: }
 2275: 
 2276: sub logo_display_options {
 2277:     my ($img,$defaults,$designs) = @_;
 2278:     my $checkedon;
 2279:     if (ref($defaults) eq 'HASH') {
 2280:         if (ref($defaults->{'showlogo'}) eq 'HASH') {
 2281:             if ($defaults->{'showlogo'}{$img}) {
 2282:                 $checkedon = 'checked="checked" ';     
 2283:             }
 2284:         } 
 2285:     }
 2286:     if (ref($designs) eq 'HASH') {
 2287:         if (ref($designs->{'showlogo'}) eq 'HASH') {
 2288:             if (defined($designs->{'showlogo'}{$img})) {
 2289:                 if ($designs->{'showlogo'}{$img} == 0) {
 2290:                     $checkedon = '';
 2291:                 } elsif ($designs->{'showlogo'}{$img} == 1) {
 2292:                     $checkedon = 'checked="checked" ';
 2293:                 }
 2294:             }
 2295:         }
 2296:     }
 2297:     return '<br /><label>&nbsp;&nbsp;<input type="checkbox" name="'.
 2298:            'login_showlogo_'.$img.'" value="1" '.$checkedon.'/>'.
 2299:            &mt('show').'</label>'."\n";
 2300: }
 2301: 
 2302: sub login_header_options  {
 2303:     my ($img,$role,$defaults,$is_custom,$choices) = @_;
 2304:     my $output = '';
 2305:     if ((!$is_custom->{'textcol'}) || (!$is_custom->{'bgcol'})) {
 2306:         $output .= &mt('Text default(s):').'<br />';
 2307:         if (!$is_custom->{'textcol'}) {
 2308:             $output .= $choices->{'textcol'}.':&nbsp;'.$defaults->{'logintext'}{'textcol'}.
 2309:                        '&nbsp;&nbsp;&nbsp;';
 2310:         }
 2311:         if (!$is_custom->{'bgcol'}) {
 2312:             $output .= $choices->{'bgcol'}.':&nbsp;'.
 2313:                        '<span id="css_'.$role.'_font" style="background-color: '.
 2314:                        $defaults->{'logintext'}{'bgcol'}.';">&nbsp;&nbsp;&nbsp;</span>';
 2315:         }
 2316:         $output .= '<br />';
 2317:     }
 2318:     $output .='<br />';
 2319:     return $output;
 2320: }
 2321: 
 2322: sub login_text_colors {
 2323:     my ($img,$role,$logintext,$phase,$choices,$designs,$defaults) = @_;
 2324:     my $color_menu = '<table border="0"><tr>';
 2325:     foreach my $item (@{$logintext}) {
 2326:         $color_menu .= '<td style="text-align: center">'.$choices->{$item};
 2327:         my $color = $designs->{'logintext'}{$item} ? $designs->{'logintext'}{$item} : $defaults->{'logintext'}{$item};
 2328:         $color_menu .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 2329:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 2330:     }
 2331:     $color_menu .= '</tr></table><br />';
 2332:     return $color_menu;
 2333: }
 2334: 
 2335: sub image_changes {
 2336:     my ($is_custom,$alt_text,$img_import,$showfile,$fullsize,$role,$img,$imgfile,$logincolors) = @_;
 2337:     my $output;
 2338:     if ($img eq 'login') {
 2339:         $output = '</td><td>'.$logincolors; # suppress image for Log-in header
 2340:     } elsif (!$is_custom) {
 2341:         if ($img ne 'domlogo') {
 2342:             $output = &mt('Default image:').'<br />';
 2343:         } else {
 2344:             $output = &mt('Default in use:').'<br />';
 2345:         }
 2346:     }
 2347:     if ($img ne 'login') {
 2348:         if ($img_import) {
 2349:             $output .= '<input type="hidden" name="'.$role.'_import_'.$img.'" value="'.$imgfile.'" />';
 2350:         }
 2351:         $output .= '<a href="'.$fullsize.'" target="_blank"><img src="'.
 2352:                    $showfile.'" alt="'.$alt_text.'" border="0" /></a></td>';
 2353:         if ($is_custom) {
 2354:             $output .= '<td>'.$logincolors.'<span class="LC_nobreak"><label>'.
 2355:                        '<input type="checkbox" name="'.
 2356:                        $role.'_del_'.$img.'" value="1" />'.&mt('Delete?').
 2357:                        '</label>&nbsp;'.&mt('Replace:').'</span><br />';
 2358:         } else {
 2359:             $output .= '<td class="LC_middle">'.$logincolors.&mt('Upload:').'<br />';
 2360:         }
 2361:     }
 2362:     return $output;
 2363: }
 2364: 
 2365: sub print_quotas {
 2366:     my ($dom,$settings,$rowtotal,$action) = @_;
 2367:     my $context;
 2368:     if ($action eq 'quotas') {
 2369:         $context = 'tools';
 2370:     } else {
 2371:         $context = $action;
 2372:     }
 2373:     my ($datatable,$defaultquota,$authorquota,@usertools,@options,%validations);
 2374:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 2375:     my $typecount = 0;
 2376:     my ($css_class,%titles);
 2377:     if ($context eq 'requestcourses') {
 2378:         @usertools = ('official','unofficial','community','textbook','placement','lti');
 2379:         @options =('norequest','approval','validate','autolimit');
 2380:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
 2381:         %titles = &courserequest_titles();
 2382:     } elsif ($context eq 'requestauthor') {
 2383:         @usertools = ('author');
 2384:         @options = ('norequest','approval','automatic');
 2385:         %titles = &authorrequest_titles();
 2386:     } else {
 2387:         @usertools = ('aboutme','blog','webdav','portfolio','timezone');
 2388:         %titles = &tool_titles();
 2389:     }
 2390:     if (ref($types) eq 'ARRAY') {
 2391:         foreach my $type (@{$types}) {
 2392:             my ($currdefquota,$currauthorquota);
 2393:             unless (($context eq 'requestcourses') ||
 2394:                     ($context eq 'requestauthor')) {
 2395:                 if (ref($settings) eq 'HASH') {
 2396:                     if (ref($settings->{defaultquota}) eq 'HASH') {
 2397:                         $currdefquota = $settings->{defaultquota}->{$type};
 2398:                     } else {
 2399:                         $currdefquota = $settings->{$type};
 2400:                     }
 2401:                     if (ref($settings->{authorquota}) eq 'HASH') {
 2402:                         $currauthorquota = $settings->{authorquota}->{$type};
 2403:                     }
 2404:                 }
 2405:             }
 2406:             if (defined($usertypes->{$type})) {
 2407:                 $typecount ++;
 2408:                 $css_class = $typecount%2?' class="LC_odd_row"':'';
 2409:                 $datatable .= '<tr'.$css_class.'>'.
 2410:                               '<td>'.$usertypes->{$type}.'</td>'.
 2411:                               '<td class="LC_left_item">';
 2412:                 if ($context eq 'requestcourses') {
 2413:                     $datatable .= '<table><tr>';
 2414:                 }
 2415:                 my %cell;  
 2416:                 foreach my $item (@usertools) {
 2417:                     if ($context eq 'requestcourses') {
 2418:                         my ($curroption,$currlimit);
 2419:                         if (ref($settings) eq 'HASH') {
 2420:                             if (ref($settings->{$item}) eq 'HASH') {
 2421:                                 $curroption = $settings->{$item}->{$type};
 2422:                                 if ($curroption =~ /^autolimit=(\d*)$/) {
 2423:                                     $currlimit = $1; 
 2424:                                 }
 2425:                             }
 2426:                         }
 2427:                         if (!$curroption) {
 2428:                             $curroption = 'norequest';
 2429:                         }
 2430:                         $datatable .= '<th>'.$titles{$item}.'</th>';
 2431:                         foreach my $option (@options) {
 2432:                             my $val = $option;
 2433:                             if ($option eq 'norequest') {
 2434:                                 $val = 0;  
 2435:                             }
 2436:                             if ($option eq 'validate') {
 2437:                                 my $canvalidate = 0;
 2438:                                 if (ref($validations{$item}) eq 'HASH') { 
 2439:                                     if ($validations{$item}{$type}) {
 2440:                                         $canvalidate = 1;
 2441:                                     }
 2442:                                 }
 2443:                                 next if (!$canvalidate);
 2444:                             }
 2445:                             my $checked = '';
 2446:                             if ($option eq $curroption) {
 2447:                                 $checked = ' checked="checked"';
 2448:                             } elsif ($option eq 'autolimit') {
 2449:                                 if ($curroption =~ /^autolimit/) {
 2450:                                     $checked = ' checked="checked"';
 2451:                                 }                       
 2452:                             } 
 2453:                             $cell{$item} .= '<span class="LC_nobreak"><label>'.
 2454:                                   '<input type="radio" name="crsreq_'.$item.
 2455:                                   '_'.$type.'" value="'.$val.'"'.$checked.' />'.
 2456:                                   $titles{$option}.'</label>';
 2457:                             if ($option eq 'autolimit') {
 2458:                                 $cell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2459:                                                 $item.'_limit_'.$type.'" size="1" '.
 2460:                                                 'value="'.$currlimit.'" />';
 2461:                             }
 2462:                             $cell{$item} .= '</span> ';
 2463:                             if ($option eq 'autolimit') {
 2464:                                 $cell{$item} .= $titles{'unlimited'};
 2465:                             }
 2466:                         }
 2467:                     } elsif ($context eq 'requestauthor') {
 2468:                         my $curroption;
 2469:                         if (ref($settings) eq 'HASH') {
 2470:                             $curroption = $settings->{$type};
 2471:                         }
 2472:                         if (!$curroption) {
 2473:                             $curroption = 'norequest';
 2474:                         }
 2475:                         foreach my $option (@options) {
 2476:                             my $val = $option;
 2477:                             if ($option eq 'norequest') {
 2478:                                 $val = 0;
 2479:                             }
 2480:                             my $checked = '';
 2481:                             if ($option eq $curroption) {
 2482:                                 $checked = ' checked="checked"';
 2483:                             }
 2484:                             $datatable .= '<span class="LC_nobreak"><label>'.
 2485:                                   '<input type="radio" name="authorreq_'.$type.
 2486:                                   '" value="'.$val.'"'.$checked.' />'.
 2487:                                   $titles{$option}.'</label></span>&nbsp; ';
 2488:                         }
 2489:                     } else {
 2490:                         my $checked = 'checked="checked" ';
 2491:                         if ($item eq 'timezone') {
 2492:                             $checked = '';
 2493:                         }
 2494:                         if (ref($settings) eq 'HASH') {
 2495:                             if (ref($settings->{$item}) eq 'HASH') {
 2496:                                 if (!$settings->{$item}->{$type}) {
 2497:                                     $checked = '';
 2498:                                 } elsif ($settings->{$item}->{$type} == 1) {
 2499:                                     $checked =  'checked="checked" ';
 2500:                                 }
 2501:                             }
 2502:                         }
 2503:                         $datatable .= '<span class="LC_nobreak"><label>'.
 2504:                                       '<input type="checkbox" name="'.$context.'_'.$item.
 2505:                                       '" value="'.$type.'" '.$checked.'/>'.$titles{$item}.
 2506:                                       '</label></span>&nbsp; ';
 2507:                     }
 2508:                 }
 2509:                 if ($context eq 'requestcourses') {
 2510:                     $datatable .= '</tr><tr>';
 2511:                     foreach my $item (@usertools) {
 2512:                         $datatable .= '<td style="vertical-align: top">'.$cell{$item}.'</td>';  
 2513:                     }
 2514:                     $datatable .= '</tr></table>';
 2515:                 }
 2516:                 $datatable .= '</td>';
 2517:                 unless (($context eq 'requestcourses') ||
 2518:                         ($context eq 'requestauthor')) {
 2519:                     $datatable .= 
 2520:                               '<td class="LC_right_item">'.
 2521:                               '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 2522:                               '<input type="text" name="quota_'.$type.
 2523:                               '" value="'.$currdefquota.
 2524:                               '" size="5" /></span>'.('&nbsp;' x 2).
 2525:                               '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 2526:                               '<input type="text" name="authorquota_'.$type.
 2527:                               '" value="'.$currauthorquota.
 2528:                               '" size="5" /></span></td>';
 2529:                 }
 2530:                 $datatable .= '</tr>';
 2531:             }
 2532:         }
 2533:     }
 2534:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 2535:         $defaultquota = '20';
 2536:         $authorquota = '500';
 2537:         if (ref($settings) eq 'HASH') {
 2538:             if (ref($settings->{'defaultquota'}) eq 'HASH') {
 2539:                 $defaultquota = $settings->{'defaultquota'}->{'default'};
 2540:             } elsif (defined($settings->{'default'})) {
 2541:                 $defaultquota = $settings->{'default'};
 2542:             }
 2543:             if (ref($settings->{'authorquota'}) eq 'HASH') {
 2544:                 $authorquota = $settings->{'authorquota'}->{'default'};
 2545:             }
 2546:         }
 2547:     }
 2548:     $typecount ++;
 2549:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 2550:     $datatable .= '<tr'.$css_class.'>'.
 2551:                   '<td>'.$othertitle.'</td>'.
 2552:                   '<td class="LC_left_item">';
 2553:     if ($context eq 'requestcourses') {
 2554:         $datatable .= '<table><tr>';
 2555:     }
 2556:     my %defcell;
 2557:     foreach my $item (@usertools) {
 2558:         if ($context eq 'requestcourses') {
 2559:             my ($curroption,$currlimit);
 2560:             if (ref($settings) eq 'HASH') {
 2561:                 if (ref($settings->{$item}) eq 'HASH') {
 2562:                     $curroption = $settings->{$item}->{'default'};
 2563:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 2564:                         $currlimit = $1;
 2565:                     }
 2566:                 }
 2567:             }
 2568:             if (!$curroption) {
 2569:                 $curroption = 'norequest';
 2570:             }
 2571:             $datatable .= '<th>'.$titles{$item}.'</th>';
 2572:             foreach my $option (@options) {
 2573:                 my $val = $option;
 2574:                 if ($option eq 'norequest') {
 2575:                     $val = 0;
 2576:                 }
 2577:                 if ($option eq 'validate') {
 2578:                     my $canvalidate = 0;
 2579:                     if (ref($validations{$item}) eq 'HASH') {
 2580:                         if ($validations{$item}{'default'}) {
 2581:                             $canvalidate = 1;
 2582:                         }
 2583:                     }
 2584:                     next if (!$canvalidate);
 2585:                 }
 2586:                 my $checked = '';
 2587:                 if ($option eq $curroption) {
 2588:                     $checked = ' checked="checked"';
 2589:                 } elsif ($option eq 'autolimit') {
 2590:                     if ($curroption =~ /^autolimit/) {
 2591:                         $checked = ' checked="checked"';
 2592:                     }
 2593:                 }
 2594:                 $defcell{$item} .= '<span class="LC_nobreak"><label>'.
 2595:                                   '<input type="radio" name="crsreq_'.$item.
 2596:                                   '_default" value="'.$val.'"'.$checked.' />'.
 2597:                                   $titles{$option}.'</label>';
 2598:                 if ($option eq 'autolimit') {
 2599:                     $defcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2600:                                        $item.'_limit_default" size="1" '.
 2601:                                        'value="'.$currlimit.'" />';
 2602:                 }
 2603:                 $defcell{$item} .= '</span> ';
 2604:                 if ($option eq 'autolimit') {
 2605:                     $defcell{$item} .= $titles{'unlimited'};
 2606:                 }
 2607:             }
 2608:         } elsif ($context eq 'requestauthor') {
 2609:             my $curroption;
 2610:             if (ref($settings) eq 'HASH') {
 2611:                 $curroption = $settings->{'default'};
 2612:             }
 2613:             if (!$curroption) {
 2614:                 $curroption = 'norequest';
 2615:             }
 2616:             foreach my $option (@options) {
 2617:                 my $val = $option;
 2618:                 if ($option eq 'norequest') {
 2619:                     $val = 0;
 2620:                 }
 2621:                 my $checked = '';
 2622:                 if ($option eq $curroption) {
 2623:                     $checked = ' checked="checked"';
 2624:                 }
 2625:                 $datatable .= '<span class="LC_nobreak"><label>'.
 2626:                               '<input type="radio" name="authorreq_default"'.
 2627:                               ' value="'.$val.'"'.$checked.' />'.
 2628:                               $titles{$option}.'</label></span>&nbsp; ';
 2629:             }
 2630:         } else {
 2631:             my $checked = 'checked="checked" ';
 2632:             if (ref($settings) eq 'HASH') {
 2633:                 if (ref($settings->{$item}) eq 'HASH') {
 2634:                     if ($settings->{$item}->{'default'} == 0) {
 2635:                         $checked = '';
 2636:                     } elsif ($settings->{$item}->{'default'} == 1) {
 2637:                         $checked = 'checked="checked" ';
 2638:                     }
 2639:                 }
 2640:             }
 2641:             $datatable .= '<span class="LC_nobreak"><label>'.
 2642:                           '<input type="checkbox" name="'.$context.'_'.$item.
 2643:                           '" value="default" '.$checked.'/>'.$titles{$item}.
 2644:                           '</label></span>&nbsp; ';
 2645:         }
 2646:     }
 2647:     if ($context eq 'requestcourses') {
 2648:         $datatable .= '</tr><tr>';
 2649:         foreach my $item (@usertools) {
 2650:             $datatable .= '<td style="vertical-align: top">'.$defcell{$item}.'</td>';
 2651:         }
 2652:         $datatable .= '</tr></table>';
 2653:     }
 2654:     $datatable .= '</td>';
 2655:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 2656:         $datatable .= '<td class="LC_right_item">'.
 2657:                       '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 2658:                       '<input type="text" name="defaultquota" value="'.
 2659:                       $defaultquota.'" size="5" /></span>'.('&nbsp;' x2).
 2660:                       '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 2661:                       '<input type="text" name="authorquota" value="'.
 2662:                       $authorquota.'" size="5" /></span></td>';
 2663:     }
 2664:     $datatable .= '</tr>';
 2665:     $typecount ++;
 2666:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 2667:     $datatable .= '<tr'.$css_class.'>'.
 2668:                   '<td>'.&mt('LON-CAPA Advanced Users').'<br />';
 2669:     if ($context eq 'requestcourses') {
 2670:         $datatable .= &mt('(overrides affiliation, if set)').
 2671:                       '</td>'.
 2672:                       '<td class="LC_left_item">'.
 2673:                       '<table><tr>';
 2674:     } else {
 2675:         $datatable .= &mt('(overrides affiliation, if checked)').
 2676:                       '</td>'.
 2677:                       '<td class="LC_left_item" colspan="2">'.
 2678:                       '<br />';
 2679:     }
 2680:     my %advcell;
 2681:     foreach my $item (@usertools) {
 2682:         if ($context eq 'requestcourses') {
 2683:             my ($curroption,$currlimit);
 2684:             if (ref($settings) eq 'HASH') {
 2685:                 if (ref($settings->{$item}) eq 'HASH') {
 2686:                     $curroption = $settings->{$item}->{'_LC_adv'};
 2687:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 2688:                         $currlimit = $1;
 2689:                     }
 2690:                 }
 2691:             }
 2692:             $datatable .= '<th>'.$titles{$item}.'</th>';
 2693:             my $checked = '';
 2694:             if ($curroption eq '') {
 2695:                 $checked = ' checked="checked"';
 2696:             }
 2697:             $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2698:                                '<input type="radio" name="crsreq_'.$item.
 2699:                                '__LC_adv" value=""'.$checked.' />'.
 2700:                                &mt('No override set').'</label></span>&nbsp; ';
 2701:             foreach my $option (@options) {
 2702:                 my $val = $option;
 2703:                 if ($option eq 'norequest') {
 2704:                     $val = 0;
 2705:                 }
 2706:                 if ($option eq 'validate') {
 2707:                     my $canvalidate = 0;
 2708:                     if (ref($validations{$item}) eq 'HASH') {
 2709:                         if ($validations{$item}{'_LC_adv'}) {
 2710:                             $canvalidate = 1;
 2711:                         }
 2712:                     }
 2713:                     next if (!$canvalidate);
 2714:                 }
 2715:                 my $checked = '';
 2716:                 if ($val eq $curroption) {
 2717:                     $checked = ' checked="checked"';
 2718:                 } elsif ($option eq 'autolimit') {
 2719:                     if ($curroption =~ /^autolimit/) {
 2720:                         $checked = ' checked="checked"';
 2721:                     }
 2722:                 }
 2723:                 $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2724:                                   '<input type="radio" name="crsreq_'.$item.
 2725:                                   '__LC_adv" value="'.$val.'"'.$checked.' />'.
 2726:                                   $titles{$option}.'</label>';
 2727:                 if ($option eq 'autolimit') {
 2728:                     $advcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2729:                                        $item.'_limit__LC_adv" size="1" '.
 2730:                                        'value="'.$currlimit.'" />';
 2731:                 }
 2732:                 $advcell{$item} .= '</span> ';
 2733:                 if ($option eq 'autolimit') {
 2734:                     $advcell{$item} .= $titles{'unlimited'};
 2735:                 }
 2736:             }
 2737:         } elsif ($context eq 'requestauthor') {
 2738:             my $curroption;
 2739:             if (ref($settings) eq 'HASH') {
 2740:                 $curroption = $settings->{'_LC_adv'};
 2741:             }
 2742:             my $checked = '';
 2743:             if ($curroption eq '') {
 2744:                 $checked = ' checked="checked"';
 2745:             }
 2746:             $datatable .= '<span class="LC_nobreak"><label>'.
 2747:                           '<input type="radio" name="authorreq__LC_adv"'.
 2748:                           ' value=""'.$checked.' />'.
 2749:                           &mt('No override set').'</label></span>&nbsp; ';
 2750:             foreach my $option (@options) {
 2751:                 my $val = $option;
 2752:                 if ($option eq 'norequest') {
 2753:                     $val = 0;
 2754:                 }
 2755:                 my $checked = '';
 2756:                 if ($val eq $curroption) {
 2757:                     $checked = ' checked="checked"';
 2758:                 }
 2759:                 $datatable .= '<span class="LC_nobreak"><label>'.
 2760:                               '<input type="radio" name="authorreq__LC_adv"'.
 2761:                               ' value="'.$val.'"'.$checked.' />'.
 2762:                               $titles{$option}.'</label></span>&nbsp; ';
 2763:             }
 2764:         } else {
 2765:             my $checked = 'checked="checked" ';
 2766:             if (ref($settings) eq 'HASH') {
 2767:                 if (ref($settings->{$item}) eq 'HASH') {
 2768:                     if ($settings->{$item}->{'_LC_adv'} == 0) {
 2769:                         $checked = '';
 2770:                     } elsif ($settings->{$item}->{'_LC_adv'} == 1) {
 2771:                         $checked = 'checked="checked" ';
 2772:                     }
 2773:                 }
 2774:             }
 2775:             $datatable .= '<span class="LC_nobreak"><label>'.
 2776:                           '<input type="checkbox" name="'.$context.'_'.$item.
 2777:                           '" value="_LC_adv" '.$checked.'/>'.$titles{$item}.
 2778:                           '</label></span>&nbsp; ';
 2779:         }
 2780:     }
 2781:     if ($context eq 'requestcourses') {
 2782:         $datatable .= '</tr><tr>';
 2783:         foreach my $item (@usertools) {
 2784:             $datatable .= '<td style="vertical-align: top">'.$advcell{$item}.'</td>';
 2785:         }
 2786:         $datatable .= '</tr></table>';
 2787:     }
 2788:     $datatable .= '</td></tr>';
 2789:     $$rowtotal += $typecount;
 2790:     return $datatable;
 2791: }
 2792: 
 2793: sub print_requestmail {
 2794:     my ($dom,$action,$settings,$rowtotal,$customcss,$rowstyle) = @_;
 2795:     my ($now,$datatable,%currapp);
 2796:     $now = time;
 2797:     if (ref($settings) eq 'HASH') {
 2798:         if (ref($settings->{'notify'}) eq 'HASH') {
 2799:             if ($settings->{'notify'}{'approval'} ne '') {
 2800:                 map {$currapp{$_}=1;} split(/,/,$settings->{'notify'}{'approval'});
 2801:             }
 2802:         }
 2803:     }
 2804:     my $numinrow = 2;
 2805:     my $css_class;
 2806:     if ($$rowtotal%2) {
 2807:         $css_class = 'LC_odd_row';
 2808:     }
 2809:     if ($customcss) {
 2810:         $css_class .= " $customcss";
 2811:     }
 2812:     $css_class =~ s/^\s+//;
 2813:     if ($css_class) {
 2814:         $css_class = ' class="'.$css_class.'"';
 2815:     }
 2816:     if ($rowstyle) {
 2817:         $css_class .= ' style="'.$rowstyle.'"';
 2818:     }
 2819:     my $text;
 2820:     if ($action eq 'requestcourses') {
 2821:         $text = &mt('Receive notification of course requests requiring approval');
 2822:     } elsif ($action eq 'requestauthor') {
 2823:         $text = &mt('Receive notification of Authoring Space requests requiring approval');
 2824:     } else {
 2825:        $text = &mt('Receive notification of queued requests for self-created user accounts requiring approval');
 2826:     }
 2827:     $datatable = '<tr'.$css_class.'>'.
 2828:                  ' <td>'.$text.'</td>'.
 2829:                  ' <td class="LC_left_item">';
 2830:     my ($numdc,$table,$rows) = &active_dc_picker($dom,$numinrow,'checkbox',
 2831:                                                  $action.'notifyapproval',%currapp);
 2832:     if ($numdc > 0) {
 2833:         $datatable .= $table;
 2834:     } else {
 2835:         $datatable .= &mt('There are no active Domain Coordinators');
 2836:     }
 2837:     $datatable .='</td></tr>';
 2838:     return $datatable;
 2839: }
 2840: 
 2841: sub print_studentcode {
 2842:     my ($settings,$rowtotal) = @_;
 2843:     my $rownum = 0; 
 2844:     my ($output,%current);
 2845:     my @crstypes = ('official','unofficial','community','textbook','placement','lti');
 2846:     if (ref($settings) eq 'HASH') {
 2847:         if (ref($settings->{'uniquecode'}) eq 'HASH') {
 2848:             foreach my $type (@crstypes) {
 2849:                 $current{$type} = $settings->{'uniquecode'}{$type};
 2850:             }
 2851:         }
 2852:     }
 2853:     $output .= '<tr>'.
 2854:                '<td class="LC_left_item">'.&mt('Generate unique six character code as course identifier?').'</td>'.
 2855:                '<td class="LC_left_item">';
 2856:     foreach my $type (@crstypes) {
 2857:         my $check = ' ';
 2858:         if ($current{$type}) {
 2859:             $check = ' checked="checked" ';
 2860:         }
 2861:         $output .= '<span class="LC_nobreak"><label>'.
 2862:                    '<input type="checkbox" name="uniquecode" value="'.$type.'"'.$check.'/>'.
 2863:                    &mt($type).'</label></span>'.('&nbsp;'x2).' ';
 2864:     }
 2865:     $output .= '</td></tr>';
 2866:     $$rowtotal ++;
 2867:     return $output;
 2868: }
 2869: 
 2870: sub print_textbookcourses {
 2871:     my ($dom,$type,$settings,$rowtotal) = @_;
 2872:     my $rownum = 0;
 2873:     my $css_class;
 2874:     my $itemcount = 1;
 2875:     my $maxnum = 0;
 2876:     my $bookshash;
 2877:     if (ref($settings) eq 'HASH') {
 2878:         $bookshash = $settings->{$type};
 2879:     }
 2880:     my %ordered;
 2881:     if (ref($bookshash) eq 'HASH') {
 2882:         foreach my $item (keys(%{$bookshash})) {
 2883:             if (ref($bookshash->{$item}) eq 'HASH') {
 2884:                 my $num = $bookshash->{$item}{'order'};
 2885:                 $ordered{$num} = $item;
 2886:             }
 2887:         }
 2888:     }
 2889:     my $confname = $dom.'-domainconfig';
 2890:     my $switchserver = &check_switchserver($dom,$confname);
 2891:     my $maxnum = scalar(keys(%ordered));
 2892:     my $datatable;
 2893:     if (keys(%ordered)) {
 2894:         my @items = sort { $a <=> $b } keys(%ordered);
 2895:         for (my $i=0; $i<@items; $i++) {
 2896:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2897:             my $key = $ordered{$items[$i]};
 2898:             my %coursehash=&Apache::lonnet::coursedescription($key);
 2899:             my $coursetitle = $coursehash{'description'};
 2900:             my ($subject,$title,$author,$publisher,$image,$imgsrc,$cdom,$cnum);
 2901:             if (ref($bookshash->{$key}) eq 'HASH') {
 2902:                 $subject = $bookshash->{$key}->{'subject'};
 2903:                 $title = $bookshash->{$key}->{'title'};
 2904:                 if ($type eq 'textbooks') {
 2905:                     $publisher = $bookshash->{$key}->{'publisher'};
 2906:                     $author = $bookshash->{$key}->{'author'};
 2907:                     $image = $bookshash->{$key}->{'image'};
 2908:                     if ($image ne '') {
 2909:                         my ($path,$imagefile) = ($image =~ m{^(.+)/([^/]+)$});
 2910:                         my $imagethumb = "$path/tn-".$imagefile;
 2911:                         $imgsrc = '<img src="'.$imagethumb.'" alt="'.&mt('Textbook image').'" />';
 2912:                     }
 2913:                 }
 2914:             }
 2915:             my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type".'_'."$key','$type'".');"';
 2916:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 2917:                          .'<select name="'.$type.'_'.$key.'"'.$chgstr.'>';
 2918:             for (my $k=0; $k<=$maxnum; $k++) {
 2919:                 my $vpos = $k+1;
 2920:                 my $selstr;
 2921:                 if ($k == $i) {
 2922:                     $selstr = ' selected="selected" ';
 2923:                 }
 2924:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2925:             }
 2926:             $datatable .= '</select>'.('&nbsp;'x2).
 2927:                 '<label><input type="checkbox" name="'.$type.'_del" value="'.$key.'" />'.
 2928:                 &mt('Delete?').'</label></span></td>'.
 2929:                 '<td colspan="2">'.
 2930:                 '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_subject_'.$i.'" value="'.$subject.'" /></span> '.
 2931:                 ('&nbsp;'x2).
 2932:                 '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_title_'.$i.'" value="'.$title.'" /></span> ';
 2933:             if ($type eq 'textbooks') {
 2934:                 $datatable .= ('&nbsp;'x2).
 2935:                               '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_publisher_'.$i.'" value="'.$publisher.'" /></span> '.
 2936:                               ('&nbsp;'x2).
 2937:                               '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_author_'.$i.'" value="'.$author.'" /></span> '.
 2938:                               ('&nbsp;'x2).
 2939:                               '<span class="LC_nobreak">'.&mt('Thumbnail:');
 2940:                 if ($image) {
 2941:                     $datatable .= $imgsrc.
 2942:                                   '<label><input type="checkbox" name="'.$type.'_image_del"'.
 2943:                                   ' value="'.$key.'" />'.&mt('Delete?').'</label></span> '.
 2944:                                   '<span class="LC_nobreak">&nbsp;'.&mt('Replace:').'&nbsp;';
 2945:                 }
 2946:                 if ($switchserver) {
 2947:                     $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2948:                 } else {
 2949:                     $datatable .= '<input type="file" name="'.$type.'_image_'.$i.'" value="" />';
 2950:                 }
 2951:             }
 2952:             $datatable .= '<input type="hidden" name="'.$type.'_id_'.$i.'" value="'.$type.'_'.$key.'" /></span> '.
 2953:                           '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 2954:                           $coursetitle.'</span></td></tr>'."\n";
 2955:             $itemcount ++;
 2956:         }
 2957:     }
 2958:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2959:     my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type"."_addbook_pos','$type'".');"';
 2960:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 2961:                   '<input type="hidden" name="'.$type.'_maxnum" value="'.$maxnum.'" />'."\n".
 2962:                   '<select name="'.$type.'_addbook_pos"'.$chgstr.'>';
 2963:     for (my $k=0; $k<$maxnum+1; $k++) {
 2964:         my $vpos = $k+1;
 2965:         my $selstr;
 2966:         if ($k == $maxnum) {
 2967:             $selstr = ' selected="selected" ';
 2968:         }
 2969:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2970:     }
 2971:     $datatable .= '</select>&nbsp;'."\n".
 2972:                   '<input type="checkbox" name="'.$type.'_addbook" value="1" />'.&mt('Add').'</span></td>'."\n".
 2973:                   '<td colspan="2">'.
 2974:                   '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_addbook_subject" value="" /></span> '."\n".
 2975:                   ('&nbsp;'x2).
 2976:                   '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_addbook_title" value="" /></span> '."\n".
 2977:                   ('&nbsp;'x2);
 2978:     if ($type eq 'textbooks') {
 2979:         $datatable .= '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_addbook_publisher" value="" /></span> '."\n".
 2980:                       ('&nbsp;'x2).
 2981:                       '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_addbook_author" value="" /></span> '."\n".
 2982:                       ('&nbsp;'x2).
 2983:                       '<span class="LC_nobreak">'.&mt('Image:').'&nbsp;';
 2984:         if ($switchserver) {
 2985:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2986:         } else {
 2987:             $datatable .= '<input type="file" name="'.$type.'_addbook_image" value="" />';
 2988:         }
 2989:         $datatable .= '</span>'."\n";
 2990:     }
 2991:     $datatable .= '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 2992:                   &Apache::loncommon::select_dom_form($env{'request.role.domain'},$type.'_addbook_cdom').
 2993:                   '<input type="text" size="25" name="'.$type.'_addbook_cnum" value="" />'.
 2994:                   &Apache::loncommon::selectcourse_link
 2995:                       ('display',$type.'_addbook_cnum',$type.'_addbook_cdom',undef,undef,undef,'Course').
 2996:                   '</span></td>'."\n".
 2997:                   '</tr>'."\n";
 2998:     $itemcount ++;
 2999:     return $datatable;
 3000: }
 3001: 
 3002: sub textbookcourses_javascript {
 3003:     my ($settings) = @_;
 3004:     return unless(ref($settings) eq 'HASH');
 3005:     my (%ordered,%total,%jstext);
 3006:     foreach my $type ('textbooks','templates') {
 3007:         $total{$type} = 0;
 3008:         if (ref($settings->{$type}) eq 'HASH') {
 3009:             foreach my $item (keys(%{$settings->{$type}})) {
 3010:                 if (ref($settings->{$type}->{$item}) eq 'HASH') {
 3011:                     my $num = $settings->{$type}->{$item}{'order'};
 3012:                     $ordered{$type}{$num} = $item;
 3013:                 }
 3014:             }
 3015:             $total{$type} = scalar(keys(%{$settings->{$type}}));
 3016:         }
 3017:         my @jsarray = ();
 3018:         foreach my $item (sort {$a <=> $b } (keys(%{$ordered{$type}}))) {
 3019:             push(@jsarray,$ordered{$type}{$item});
 3020:         }
 3021:         $jstext{$type} = '    var '.$type.' = Array('."'".join("','",@jsarray)."'".');'."\n";
 3022:     }
 3023:     return <<"ENDSCRIPT";
 3024: <script type="text/javascript">
 3025: // <![CDATA[
 3026: function reorderBooks(form,item,caller) {
 3027:     var changedVal;
 3028: $jstext{'textbooks'};
 3029: $jstext{'templates'};
 3030:     var newpos;
 3031:     var maxh;
 3032:     if (caller == 'textbooks') {  
 3033:         newpos = 'textbooks_addbook_pos';
 3034:         maxh = 1 + $total{'textbooks'};
 3035:     } else {
 3036:         newpos = 'templates_addbook_pos';
 3037:         maxh = 1 + $total{'templates'};
 3038:     }
 3039:     var current = new Array;
 3040:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 3041:     if (item == newpos) {
 3042:         changedVal = newitemVal;
 3043:     } else {
 3044:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3045:         current[newitemVal] = newpos;
 3046:     }
 3047:     if (caller == 'textbooks') {
 3048:         for (var i=0; i<textbooks.length; i++) {
 3049:             var elementName = 'textbooks_'+textbooks[i];
 3050:             if (elementName != item) {
 3051:                 if (form.elements[elementName]) {
 3052:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3053:                     current[currVal] = elementName;
 3054:                 }
 3055:             }
 3056:         }
 3057:     }
 3058:     if (caller == 'templates') {
 3059:         for (var i=0; i<templates.length; i++) {
 3060:             var elementName = 'templates_'+templates[i];
 3061:             if (elementName != item) {
 3062:                 if (form.elements[elementName]) {
 3063:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3064:                     current[currVal] = elementName;
 3065:                 }
 3066:             }
 3067:         }
 3068:     }
 3069:     var oldVal;
 3070:     for (var j=0; j<maxh; j++) {
 3071:         if (current[j] == undefined) {
 3072:             oldVal = j;
 3073:         }
 3074:     }
 3075:     if (oldVal < changedVal) {
 3076:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3077:            var elementName = current[k];
 3078:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3079:         }
 3080:     } else {
 3081:         for (var k=changedVal; k<oldVal; k++) {
 3082:             var elementName = current[k];
 3083:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3084:         }
 3085:     }
 3086:     return;
 3087: }
 3088: 
 3089: // ]]>
 3090: </script>
 3091: 
 3092: ENDSCRIPT
 3093: }
 3094: 
 3095: sub ltitools_javascript {
 3096:     my ($settings) = @_;
 3097:     my $togglejs = &ltitools_toggle_js();
 3098:     unless (ref($settings) eq 'HASH') {
 3099:         return $togglejs;
 3100:     }
 3101:     my (%ordered,$total,%jstext);
 3102:     $total = 0;
 3103:     foreach my $item (keys(%{$settings})) {
 3104:         if (ref($settings->{$item}) eq 'HASH') {
 3105:             my $num = $settings->{$item}{'order'};
 3106:             $ordered{$num} = $item;
 3107:         }
 3108:     }
 3109:     $total = scalar(keys(%{$settings}));
 3110:     my @jsarray = ();
 3111:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3112:         push(@jsarray,$ordered{$item});
 3113:     }
 3114:     my $jstext = '    var ltitools = Array('."'".join("','",@jsarray)."'".');'."\n";
 3115:     return <<"ENDSCRIPT";
 3116: <script type="text/javascript">
 3117: // <![CDATA[
 3118: function reorderLTITools(form,item) {
 3119:     var changedVal;
 3120: $jstext
 3121:     var newpos = 'ltitools_add_pos';
 3122:     var maxh = 1 + $total;
 3123:     var current = new Array;
 3124:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 3125:     if (item == newpos) {
 3126:         changedVal = newitemVal;
 3127:     } else {
 3128:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3129:         current[newitemVal] = newpos;
 3130:     }
 3131:     for (var i=0; i<ltitools.length; i++) {
 3132:         var elementName = 'ltitools_'+ltitools[i];
 3133:         if (elementName != item) {
 3134:             if (form.elements[elementName]) {
 3135:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3136:                 current[currVal] = elementName;
 3137:             }
 3138:         }
 3139:     }
 3140:     var oldVal;
 3141:     for (var j=0; j<maxh; j++) {
 3142:         if (current[j] == undefined) {
 3143:             oldVal = j;
 3144:         }
 3145:     }
 3146:     if (oldVal < changedVal) {
 3147:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3148:            var elementName = current[k];
 3149:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3150:         }
 3151:     } else {
 3152:         for (var k=changedVal; k<oldVal; k++) {
 3153:             var elementName = current[k];
 3154:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3155:         }
 3156:     }
 3157:     return;
 3158: }
 3159: 
 3160: // ]]>
 3161: </script>
 3162: 
 3163: $togglejs
 3164: 
 3165: ENDSCRIPT
 3166: }
 3167: 
 3168: sub ltitools_toggle_js {
 3169:     return <<"ENDSCRIPT";
 3170: <script type="text/javascript">
 3171: // <![CDATA[
 3172: 
 3173: function toggleLTITools(form,setting,item) {
 3174:     var radioname = '';
 3175:     var divid = '';
 3176:     if ((setting == 'passback') || (setting == 'roster')) {
 3177:         radioname = 'ltitools_'+setting+'_'+item;
 3178:         divid = 'ltitools_'+setting+'time_'+item;
 3179:         var num = form.elements[radioname].length;
 3180:         if (num) {
 3181:             var setvis = '';
 3182:             for (var i=0; i<num; i++) {
 3183:                 if (form.elements[radioname][i].checked) {
 3184:                     if (form.elements[radioname][i].value == '1') {
 3185:                         if (document.getElementById(divid)) {
 3186:                             document.getElementById(divid).style.display = 'inline-block';
 3187:                         }
 3188:                         setvis = 1;
 3189:                     }
 3190:                     break;
 3191:                 }
 3192:             }
 3193:         }
 3194:         if (!setvis) {
 3195:             if (document.getElementById(divid)) {
 3196:                 document.getElementById(divid).style.display = 'none';
 3197:             }
 3198:         }
 3199:     }
 3200:     if (setting == 'user') {
 3201:         divid = 'ltitools_'+setting+'_div_'+item;
 3202:         var checkid = 'ltitools_'+setting+'_field_'+item;
 3203:         if (document.getElementById(divid)) {
 3204:             if (document.getElementById(checkid)) {
 3205:                 if (document.getElementById(checkid).checked) {
 3206:                     document.getElementById(divid).style.display = 'inline-block';
 3207:                 } else {
 3208:                     document.getElementById(divid).style.display = 'none';
 3209:                 }
 3210:             }
 3211:         }
 3212:     }
 3213:     return;
 3214: }
 3215: // ]]>
 3216: </script>
 3217: 
 3218: ENDSCRIPT
 3219: }
 3220: 
 3221: sub wafproxy_javascript {
 3222:     my ($dom) = @_;
 3223:     return <<"ENDSCRIPT";
 3224: <script type="text/javascript">
 3225: // <![CDATA[
 3226: function updateWAF() {
 3227:     if (document.getElementById('wafproxy_remoteip')) {
 3228:         var wafremote = 0;
 3229:         if (document.display.wafproxy_remoteip.options[document.display.wafproxy_remoteip.selectedIndex].value == 'h') {
 3230:             wafremote = 1;
 3231:         }
 3232:         var fields = new Array('header','trust');
 3233:         for (var i=0; i<fields.length; i++) {
 3234:             if (document.getElementById('wafproxy_'+fields[i])) {
 3235:                 if (wafremote == 1) {
 3236:                     document.getElementById('wafproxy_'+fields[i]).style.display = 'table-row';
 3237:                 }
 3238:                 else {
 3239:                     document.getElementById('wafproxy_'+fields[i]).style.display = 'none';
 3240:                 }
 3241:             }
 3242:         }
 3243:         if (document.getElementById('wafproxyranges_$dom')) {
 3244:             if (wafremote == 1) {
 3245:                 document.getElementById('wafproxyranges_$dom').style.display = 'inline-block';
 3246:             } else {
 3247:                 for (var i=0; i<document.display.wafproxy_vpnaccess.length; i++) {
 3248:                     if (document.display.wafproxy_vpnaccess[i].checked) {
 3249:                         if (document.display.wafproxy_vpnaccess[i].value == 0) {
 3250:                             document.getElementById('wafproxyranges_$dom').style.display = 'none';
 3251:                         }
 3252:                     }
 3253:                 }
 3254:             }
 3255:         }
 3256:     }
 3257:     return;
 3258: }
 3259: 
 3260: function checkWAF() {
 3261:     if (document.getElementById('wafproxy_remoteip')) {
 3262:         var wafvpn = 0;
 3263:         for (var i=0; i<document.display.wafproxy_vpnaccess.length; i++) {
 3264:             if (document.display.wafproxy_vpnaccess[i].checked) {
 3265:                 if (document.display.wafproxy_vpnaccess[i].value == 1) {
 3266:                     wafvpn = 1;
 3267:                 }
 3268:                 break;
 3269:             }
 3270:         }
 3271:         var vpn = new Array('vpnint','vpnext');
 3272:         for (var i=0; i<vpn.length; i++) {
 3273:             if (document.getElementById('wafproxy_show_'+vpn[i])) {
 3274:                 if (wafvpn == 1) {
 3275:                     document.getElementById('wafproxy_show_'+vpn[i]).style.display = 'table-row';
 3276:                 }
 3277:                 else {
 3278:                     document.getElementById('wafproxy_show_'+vpn[i]).style.display = 'none';
 3279:                 }
 3280:             }
 3281:         }
 3282:         if (document.getElementById('wafproxyranges_$dom')) {
 3283:             if (wafvpn == 1) {
 3284:                 document.getElementById('wafproxyranges_$dom').style.display = 'inline-block';
 3285:             }
 3286:             else if (document.display.wafproxy_remoteip.options[document.display.wafproxy_remoteip.selectedIndex].value != 'h') {
 3287:                 document.getElementById('wafproxyranges_$dom').style.display = 'none';
 3288:             }
 3289:         }
 3290:     }
 3291:     return;
 3292: }
 3293: 
 3294: function toggleWAF() {
 3295:     if (document.getElementById('wafproxy_table')) {
 3296:         var wafproxy = 0;
 3297:         for (var i=0; i<document.display.wafproxy_${dom}.length; i++) {
 3298:              if (document.display.wafproxy_${dom}[i].checked) {
 3299:                  if (document.display.wafproxy_${dom}[i].value == 1) {
 3300:                      wafproxy = 1;
 3301:                      break;
 3302:                 }
 3303:             }
 3304:         }
 3305:         if (wafproxy == 1) {
 3306:             document.getElementById('wafproxy_table').style.display='inline';
 3307:         }
 3308:         else {
 3309:            document.getElementById('wafproxy_table').style.display='none';
 3310:         }
 3311:         if (document.getElementById('wafproxyrow_${dom}')) {
 3312:             if (wafproxy == 1) {
 3313:                 document.getElementById('wafproxyrow_${dom}').style.display = 'table-row';
 3314:             }
 3315:             else {
 3316:                 document.getElementById('wafproxyrow_${dom}').style.display = 'none';
 3317:             }
 3318:         }
 3319:         if (document.getElementById('nowafproxyrow_$dom')) {
 3320:             if (wafproxy == 1) {
 3321:                 document.getElementById('nowafproxyrow_${dom}').style.display = 'none';
 3322:             }
 3323:             else {
 3324:                 document.getElementById('nowafproxyrow_${dom}').style.display = 'table-row';
 3325:             }
 3326:         }
 3327:     }
 3328:     return;
 3329: }
 3330: // ]]>
 3331: </script>
 3332: 
 3333: ENDSCRIPT
 3334: }
 3335: 
 3336: sub proctoring_javascript {
 3337:     my ($settings) = @_;
 3338:     my (%ordered,$total,%jstext);
 3339:     $total = 0;
 3340:     if (ref($settings) eq 'HASH') {
 3341:         foreach my $item (keys(%{$settings})) {
 3342:             if (ref($settings->{$item}) eq 'HASH') {
 3343:                 my $num = $settings->{$item}{'order'};
 3344:                 $ordered{$num} = $item;
 3345:             }
 3346:         }
 3347:         $total = scalar(keys(%{$settings}));
 3348:     } else {
 3349:         %ordered = (
 3350:                        0 => 'proctorio',
 3351:                        1 => 'examity',
 3352:                    );
 3353:         $total = 2; 
 3354:     }
 3355:     my @jsarray = ();
 3356:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3357:         push(@jsarray,$ordered{$item});
 3358:     }
 3359:     my $jstext = '    var proctors = Array('."'".join("','",@jsarray)."'".');'."\n";
 3360:     return <<"ENDSCRIPT";
 3361: <script type="text/javascript">
 3362: // <![CDATA[
 3363: function reorderProctoring(form,item) {
 3364:     var changedVal;
 3365: $jstext
 3366:     var maxh = $total;
 3367:     var current = new Array;
 3368:     var changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3369:     for (var i=0; i<proctors.length; i++) {
 3370:         var elementName = 'proctoring_pos_'+proctors[i];
 3371:         if (elementName != item) {
 3372:             if (form.elements[elementName]) {
 3373:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3374:                 current[currVal] = elementName;
 3375:             }
 3376:         }
 3377:     }
 3378:     var oldVal;
 3379:     for (var j=0; j<maxh; j++) {
 3380:         if (current[j] == undefined) {
 3381:             oldVal = j;
 3382:         }
 3383:     }
 3384:     if (oldVal < changedVal) {
 3385:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3386:            var elementName = current[k];
 3387:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3388:         }
 3389:     } else {
 3390:         for (var k=changedVal; k<oldVal; k++) {
 3391:             var elementName = current[k];
 3392:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3393:         }
 3394:     }
 3395:     return;
 3396: }
 3397: 
 3398: function toggleProctoring(form,item) {
 3399:     var fieldsets = document.getElementsByClassName('proctoring_'+item);
 3400:     if (fieldsets.length) {
 3401:         var radioname = 'proctoring_available_'+item;
 3402:         var num = form.elements[radioname].length;
 3403:         if (num) {
 3404:             var setvis = '';
 3405:             for (var i=0; i<num; i++) {
 3406:                 if (form.elements[radioname][i].checked) {
 3407:                     if (form.elements[radioname][i].value == '1') {
 3408:                        setvis = 1;
 3409:                        break;
 3410:                     }
 3411:                 }
 3412:             }
 3413:             for (var j=0; j<fieldsets.length; j++) {
 3414:                 if (setvis) {
 3415:                     fieldsets[j].style.display = 'block';
 3416:                 } else {
 3417:                     fieldsets[j].style.display = 'none';
 3418:                 }
 3419:             }
 3420:         }
 3421:     }
 3422:     return;
 3423: }
 3424: 
 3425: // ]]>
 3426: </script>
 3427: 
 3428: ENDSCRIPT
 3429: }
 3430: 
 3431: 
 3432: sub lti_javascript {
 3433:     my ($dom,$settings) = @_;
 3434:     my $togglejs = &lti_toggle_js($dom);
 3435:     my $linkprot_js = &Apache::courseprefs::linkprot_javascript();
 3436:     unless (ref($settings) eq 'HASH') {
 3437:         return $togglejs.'
 3438: <script type="text/javascript">
 3439: // <![CDATA[
 3440: 
 3441: '.$linkprot_js.'
 3442: 
 3443: // ]]>
 3444: </script>
 3445: ';
 3446:     }
 3447:     my (%ordered,$total,%jstext);
 3448:     $total = scalar(keys(%{$settings}));
 3449:     foreach my $item (keys(%{$settings})) {
 3450:         if (ref($settings->{$item}) eq 'HASH') {
 3451:             my $num = $settings->{$item}{'order'};
 3452:             if ($num eq '') {
 3453:                 $num = $total - 1;
 3454:             }
 3455:             $ordered{$num} = $item;
 3456:         }
 3457:     }
 3458:     my @jsarray = ();
 3459:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3460:         push(@jsarray,$ordered{$item});
 3461:     }
 3462:     my $jstext = '    var lti = Array('."'".join("','",@jsarray)."'".');'."\n";
 3463:     return <<"ENDSCRIPT";
 3464: <script type="text/javascript">
 3465: // <![CDATA[
 3466: function reorderLTI(form,item) {
 3467:     var changedVal;
 3468: $jstext
 3469:     var newpos = 'lti_pos_add';
 3470:     var maxh = 1 + $total;
 3471:     var current = new Array;
 3472:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 3473:     if (item == newpos) {
 3474:         changedVal = newitemVal;
 3475:     } else {
 3476:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3477:         current[newitemVal] = newpos;
 3478:     }
 3479:     for (var i=0; i<lti.length; i++) {
 3480:         var elementName = 'lti_pos_'+lti[i];
 3481:         if (elementName != item) {
 3482:             if (form.elements[elementName]) {
 3483:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3484:                 current[currVal] = elementName;
 3485:             }
 3486:         }
 3487:     }
 3488:     var oldVal;
 3489:     for (var j=0; j<maxh; j++) {
 3490:         if (current[j] == undefined) {
 3491:             oldVal = j;
 3492:         }
 3493:     }
 3494:     if (oldVal < changedVal) {
 3495:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3496:            var elementName = current[k];
 3497:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3498:         }
 3499:     } else {
 3500:         for (var k=changedVal; k<oldVal; k++) {
 3501:             var elementName = current[k];
 3502:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3503:         }
 3504:     }
 3505:     return;
 3506: }
 3507: 
 3508: $linkprot_js
 3509: 
 3510: // ]]>
 3511: </script>
 3512: 
 3513: $togglejs
 3514: 
 3515: ENDSCRIPT
 3516: }
 3517: 
 3518: sub lti_toggle_js {
 3519:     my ($dom) = @_;
 3520:     my %lcauthparmtext = &Apache::lonlocal::texthash (
 3521:                             localauth => 'Local auth argument',
 3522:                             krb       => 'Kerberos domain',
 3523:                          );
 3524:     my $crsincalert = &mt('"User\'s identity sent" needs to be set to "Yes" first,[_1] before setting "Course\'s identity sent" to "Yes"',"\n");
 3525:     &js_escape(\$crsincalert);
 3526:     my %servers = &Apache::lonnet::get_servers($dom,'library');
 3527:     my $primary = &Apache::lonnet::domain($dom,'primary');
 3528:     my $course_servers = "'".join("','",keys(%servers))."'";
 3529: 
 3530:     return <<"ENDSCRIPT";
 3531: <script type="text/javascript">
 3532: // <![CDATA[
 3533: 
 3534: function toggleLTI(form,setting,item) {
 3535:     if ((setting == 'requser') || (setting == 'crsinc')) {
 3536:         var usrfieldsets = document.getElementsByClassName('ltioption_usr_'+item);
 3537:         var setvis = '';
 3538:         var radioname = 'lti_requser_'+item;
 3539:         var num = form.elements[radioname].length;
 3540:         if (num) {
 3541:             for (var i=0; i<num; i++) {
 3542:                 if (form.elements[radioname][i].checked) {
 3543:                     if (form.elements[radioname][i].value == '1') {
 3544:                         setvis = 1;
 3545:                         break;
 3546:                     }
 3547:                 }
 3548:             }
 3549:         }
 3550:         if (usrfieldsets.length) {
 3551:             for (var j=0; j<usrfieldsets.length; j++) {
 3552:                 if (setvis) {
 3553:                     usrfieldsets[j].style.display = 'block';
 3554:                 } else {
 3555:                     usrfieldsets[j].style.display = 'none';
 3556:                 }
 3557:             }
 3558:         }
 3559:         var crsfieldsets = document.getElementsByClassName('ltioption_crs_'+item);
 3560:         if (crsfieldsets.length) {
 3561:             radioname = 'lti_crsinc_'+item;
 3562:             var num = form.elements[radioname].length;
 3563:             if (num) {
 3564:                 var crsvis = '';
 3565:                 for (var i=0; i<num; i++) {
 3566:                     if (form.elements[radioname][i].checked) {
 3567:                         if (form.elements[radioname][i].value == '1') {
 3568:                             if (setvis == '') {
 3569:                                 if (setting == 'crsinc'){
 3570:                                     alert("$crsincalert");
 3571:                                     form.elements[radioname][0].checked = true;
 3572:                                 }
 3573:                             } else {
 3574:                                 crsvis = 1;
 3575:                             }
 3576:                             break;
 3577:                         }
 3578:                     }
 3579:                 }
 3580:                 setvis = crsvis;
 3581:             }
 3582:             for (var j=0; j<crsfieldsets.length; j++) {
 3583:                 if (setvis) {
 3584:                     crsfieldsets[j].style.display = 'block';
 3585:                 } else {
 3586:                     crsfieldsets[j].style.display = 'none';
 3587:                 }
 3588:             }
 3589:         }
 3590:     } else if ((setting == 'user') || (setting == 'crs') || (setting == 'passback') || (setting == 'callback')) {
 3591:         var radioname = '';
 3592:         var divid = '';
 3593:         if (setting == 'user') {
 3594:             radioname = 'lti_mapuser_'+item;
 3595:             divid = 'lti_userfield_'+item;
 3596:         } else if (setting == 'crs') {
 3597:             radioname = 'lti_mapcrs_'+item;
 3598:             divid = 'lti_crsfield_'+item;
 3599:         } else if (setting == 'callback') {
 3600:             radioname = 'lti_callback_'+item;
 3601:             divid = 'lti_callbackfield_'+item;
 3602:         } else {
 3603:             radioname = 'lti_passback_'+item;
 3604:             divid =  'lti_passback_'+item;
 3605:         }
 3606:         var num = form.elements[radioname].length;
 3607:         if (num) {
 3608:             var setvis = '';
 3609:             for (var i=0; i<num; i++) {
 3610:                if (form.elements[radioname][i].checked) {
 3611:                    if ((setting == 'passback') || (setting == 'callback')) {
 3612:                        if (form.elements[radioname][i].value == '1') {
 3613:                            if (document.getElementById(divid)) {
 3614:                                document.getElementById(divid).style.display = 'inline-block';
 3615:                            }
 3616:                            setvis = 1;
 3617:                            break;
 3618:                        }
 3619:                    } else {
 3620:                        if (form.elements[radioname][i].value == 'other') {
 3621:                            if (document.getElementById(divid)) {
 3622:                                document.getElementById(divid).style.display = 'inline-block';
 3623:                            }
 3624:                            setvis = 1;
 3625:                            break;
 3626:                        }
 3627:                    }
 3628:                } 
 3629:             }
 3630:             if (!setvis) {
 3631:                 if (document.getElementById(divid)) {
 3632:                     document.getElementById(divid).style.display = 'none';
 3633:                 }
 3634:             }
 3635:         }
 3636:     } else if ((setting == 'sec') || (setting == 'secsrc')) {
 3637:         var numsec = form.elements['lti_crssec_'+item].length;
 3638:         if (numsec) {
 3639:             var setvis = '';
 3640:             for (var i=0; i<numsec; i++) {
 3641:                 if (form.elements['lti_crssec_'+item][i].checked) {
 3642:                     if (form.elements['lti_crssec_'+item][i].value == '1') {
 3643:                         if (document.getElementById('lti_crssecfield_'+item)) {
 3644:                             document.getElementById('lti_crssecfield_'+item).style.display = 'inline-block';
 3645:                             setvis = 1;
 3646:                             var numsrcsec = form.elements['lti_crssecsrc_'+item].length;
 3647:                             if (numsrcsec) {
 3648:                                 var setsrcvis = '';
 3649:                                 for (var j=0; j<numsrcsec; j++) {
 3650:                                     if (form.elements['lti_crssecsrc_'+item][j].checked) {
 3651:                                         if (form.elements['lti_crssecsrc_'+item][j].value == 'other') {
 3652:                                             if (document.getElementById('lti_secsrcfield_'+item)) {
 3653:                                                 document.getElementById('lti_secsrcfield_'+item).style.display = 'inline-block';
 3654:                                                 setsrcvis = 1;
 3655:                                             }
 3656:                                         }
 3657:                                     }
 3658:                                 }
 3659:                                 if (!setsrcvis) {
 3660:                                     if (document.getElementById('lti_secsrcfield_'+item)) {
 3661:                                         document.getElementById('lti_secsrcfield_'+item).style.display = 'none';
 3662:                                     }
 3663:                                 }
 3664:                             }
 3665:                         }
 3666:                     }
 3667:                 }
 3668:             }
 3669:             if (!setvis) {
 3670:                 if (document.getElementById('lti_crssecfield_'+item)) {
 3671:                     document.getElementById('lti_crssecfield_'+item).style.display = 'none';
 3672:                 }
 3673:                 if (document.getElementById('lti_secsrcfield_'+item)) {
 3674:                     document.getElementById('lti_secsrcfield_'+item).style.display = 'none';
 3675:                 }
 3676:             }
 3677:         }
 3678:     } else if (setting == 'lcauth') {
 3679:         var numauth = form.elements['lti_lcauth_'+item].length;
 3680:         if (numauth) {
 3681:             for (var i=0; i<numauth; i++) {
 3682:                 if (form.elements['lti_lcauth_'+item][i].checked) {
 3683:                     if (document.getElementById('lti_'+setting+'_parmrow_'+item)) {
 3684:                         if ((form.elements['lti_'+setting+'_'+item][i].value == 'internal') || (form.elements['lti_'+setting+'_'+item][i].value == 'lti')) {
 3685:                             document.getElementById('lti_'+setting+'_parmrow_'+item).style.display = 'none';
 3686:                         } else {
 3687:                             document.getElementById('lti_'+setting+'_parmrow_'+item).style.display = 'table-row';
 3688:                             if (document.getElementById('lti_'+setting+'_parmtext_'+item)) {
 3689:                                 if (form.elements['lti_'+setting+'_'+item][i].value == 'localauth') {
 3690:                                     document.getElementById('lti_'+setting+'_parmtext_'+item).innerHTML = "$lcauthparmtext{'localauth'}";
 3691:                                 } else {
 3692:                                     document.getElementById('lti_'+setting+'_parmtext_'+item).innerHTML = "$lcauthparmtext{'krb'}";
 3693:                                 }
 3694:                             }
 3695:                         }
 3696:                     }
 3697:                 }
 3698:             }
 3699:         }
 3700:     } else if (setting == 'lcmenu') {
 3701:         var menus = new Array('lti_topmenu_'+item,'lti_inlinemenu_'+item);
 3702:         var divid = 'lti_menufield_'+item;
 3703:         var setvis = '';
 3704:         for (var i=0; i<menus.length; i++) {
 3705:             var radioname = menus[i];  
 3706:             var num = form.elements[radioname].length;
 3707:             if (num) {
 3708:                 for (var j=0; j<num; j++) {
 3709:                     if (form.elements[radioname][j].checked) {
 3710:                         if (form.elements[radioname][j].value == '1') {
 3711:                             if (document.getElementById(divid)) {
 3712:                                 document.getElementById(divid).style.display = 'inline-block';
 3713:                             }
 3714:                             setvis = 1;
 3715:                             break;
 3716:                         }
 3717:                     }
 3718:                 }
 3719:             }
 3720:             if (setvis == 1) {
 3721:                 break;
 3722:             }
 3723:         }
 3724:         if (!setvis) {
 3725:             if (document.getElementById(divid)) {
 3726:                 document.getElementById(divid).style.display = 'none';
 3727:             }
 3728:         }
 3729:     }
 3730:     return;
 3731: }
 3732: 
 3733: function toggleLTIEncKey(form) {
 3734:     var shownhosts = new Array();
 3735:     var hiddenhosts = new Array();
 3736:     var forcourse = new Array($course_servers);
 3737:     var fromdomain = '$primary';
 3738:     var crsradio = form.elements['ltisec_crslinkprot'];
 3739:     if (crsradio.length) {
 3740:         for (var i=0; i<crsradio.length; i++) {
 3741:             if (crsradio[i].checked) {
 3742:                 if (crsradio[i].value == 1) {
 3743:                     if (forcourse.length > 0) {
 3744:                         for (var j=0; j<forcourse.length; j++) {
 3745:                             if (!shownhosts.includes(forcourse[j])) {
 3746:                                 shownhosts.push(forcourse[j]);
 3747:                             }
 3748:                         }
 3749:                     }
 3750:                 } else {
 3751:                     if (forcourse.length > 0) {
 3752:                         for (var j=0; j<forcourse.length; j++) {
 3753:                             if (!hiddenhosts.includes(forcourse[j])) { 
 3754:                                 hiddenhosts.push(forcourse[j]);
 3755:                             }
 3756:                         }
 3757:                     } 
 3758:                 }
 3759:             }
 3760:         }
 3761:     }
 3762:     var domradio = form.elements['ltisec_domlinkprot'];
 3763:     if (domradio.length) {
 3764:         for (var i=0; i<domradio.length; i++) {
 3765:             if (domradio[i].checked) {
 3766:                 if (domradio[i].value == 1) {
 3767:                     if (!shownhosts.includes(fromdomain)) { 
 3768:                         shownhosts.push(fromdomain);
 3769:                     }
 3770:                 } else {
 3771:                     if (!hiddenhosts.includes(fromdomain)) {
 3772:                         hiddenhosts.push(fromdomain);
 3773:                     }
 3774:                 }
 3775:             }
 3776:         }
 3777:     }
 3778:     var consumersradio = form.elements['ltisec_consumers'];
 3779:     if (consumersradio.length) {
 3780:         for (var i=0; i<consumersradio.length; i++) {
 3781:             if (consumersradio[i].checked) {
 3782:                 if (consumersradio[i].value == 1) {
 3783:                     if (!shownhosts.includes(fromdomain)) {     
 3784:                         shownhosts.push(fromdomain);
 3785:                     }
 3786:                 } else {
 3787:                     if (!hiddenhosts.includes(fromdomain)) {
 3788:                         hiddenhosts.push(fromdomain);
 3789:                     }
 3790:                 }
 3791:             }
 3792:         }
 3793:     }
 3794:     if (shownhosts.length > 0) {
 3795:         for (var i=0; i<shownhosts.length; i++) {
 3796:             if (document.getElementById('ltisec_info_'+shownhosts[i])) {
 3797:                 document.getElementById('ltisec_info_'+shownhosts[i]).style.display = 'block';                 
 3798:             }
 3799:         }
 3800:         if (document.getElementById('ltisec_noprivkey')) {
 3801:             document.getElementById('ltisec_noprivkey').style.display = 'none';
 3802:         }
 3803:     } else {
 3804:         if (document.getElementById('ltisec_noprivkey')) {
 3805:             document.getElementById('ltisec_noprivkey').style.display = 'inline-block';
 3806:         }
 3807:     }
 3808:     if (hiddenhosts.length > 0) {
 3809:         for (var i=0; i<hiddenhosts.length; i++) {
 3810:             if (!shownhosts.includes(hiddenhosts[i])) {
 3811:                 if (document.getElementById('ltisec_info_'+hiddenhosts[i])) {
 3812:                     document.getElementById('ltisec_info_'+hiddenhosts[i]).style.display = 'none';
 3813:                 }
 3814:             }
 3815:         }
 3816:     }
 3817:     return;
 3818: }
 3819: 
 3820: function togglePrivKey(form,hostid) {
 3821:     var radioname = '';
 3822:     var currdivid = '';
 3823:     var newdivid = '';
 3824:     if ((document.getElementById('ltisec_divcurrprivkey_'+hostid)) &&
 3825:         (document.getElementById('ltisec_divchgprivkey_'+hostid))) {
 3826:         currdivid = document.getElementById('ltisec_divcurrprivkey_'+hostid);
 3827:         newdivid = document.getElementById('ltisec_divchgprivkey_'+hostid);
 3828:         radioname = form.elements['ltisec_changeprivkey_'+hostid];
 3829:         if (radioname) {
 3830:             if (radioname.length > 0) {
 3831:                 var setvis;
 3832:                 for (var i=0; i<radioname.length; i++) {
 3833:                     if (radioname[i].checked == true) {
 3834:                         if (radioname[i].value == 1) {
 3835:                             newdivid.style.display = 'inline-block';
 3836:                             currdivid.style.display = 'none';
 3837:                             setvis = 1;
 3838:                         }
 3839:                         break;
 3840:                     }
 3841:                 }
 3842:                 if (!setvis) {
 3843:                     newdivid.style.display = 'none';
 3844:                     currdivid.style.display = 'inline-block';
 3845:                 }
 3846:             }
 3847:         }
 3848:     }
 3849: }
 3850: 
 3851: // ]]>
 3852: </script>
 3853: 
 3854: ENDSCRIPT
 3855: }
 3856: 
 3857: sub autoupdate_javascript {
 3858:     return <<"ENDSCRIPT";
 3859: <script type="text/javascript">
 3860: // <![CDATA[
 3861: function toggleLastActiveDays(form) {
 3862:     var radioname = 'lastactive';
 3863:     var divid = 'lastactive_div';
 3864:     var num = form.elements[radioname].length;
 3865:     if (num) {
 3866:         var setvis = '';
 3867:         for (var i=0; i<num; i++) {
 3868:             if (form.elements[radioname][i].checked) {
 3869:                 if (form.elements[radioname][i].value == '1') {
 3870:                     if (document.getElementById(divid)) {
 3871:                         document.getElementById(divid).style.display = 'inline-block';
 3872:                     }
 3873:                     setvis = 1;
 3874:                 }
 3875:                 break;
 3876:             }
 3877:         }
 3878:         if (!setvis) {
 3879:             if (document.getElementById(divid)) {
 3880:                 document.getElementById(divid).style.display = 'none';
 3881:             }
 3882:         }
 3883:     }
 3884:     return;
 3885: }
 3886: // ]]>
 3887: </script>
 3888: 
 3889: ENDSCRIPT
 3890: }
 3891: 
 3892: sub autoenroll_javascript {
 3893:     return <<"ENDSCRIPT";
 3894: <script type="text/javascript">
 3895: // <![CDATA[
 3896: function toggleFailsafe(form) {
 3897:     var radioname = 'autoenroll_failsafe';
 3898:     var divid = 'autoenroll_failsafe_div';
 3899:     var num = form.elements[radioname].length;
 3900:     if (num) {
 3901:         var setvis = '';
 3902:         for (var i=0; i<num; i++) {
 3903:             if (form.elements[radioname][i].checked) {
 3904:                 if ((form.elements[radioname][i].value == 'zero') || (form.elements[radioname][i].value == 'any')) {
 3905:                     if (document.getElementById(divid)) {
 3906:                         document.getElementById(divid).style.display = 'inline-block';
 3907:                     }
 3908:                     setvis = 1;
 3909:                 }
 3910:                 break;
 3911:             }
 3912:         }
 3913:         if (!setvis) {
 3914:             if (document.getElementById(divid)) {
 3915:                 document.getElementById(divid).style.display = 'none';
 3916:             }
 3917:         }
 3918:     }
 3919:     return;
 3920: }
 3921: // ]]>
 3922: </script>
 3923: 
 3924: ENDSCRIPT
 3925: }
 3926: 
 3927: sub saml_javascript {
 3928:     return <<"ENDSCRIPT";
 3929: <script type="text/javascript">
 3930: // <![CDATA[
 3931: function toggleSamlOptions(form,hostid) { 
 3932:     var radioname = 'saml_'+hostid;
 3933:     var tablecellon = 'samloptionson_'+hostid;
 3934:     var tablecelloff = 'samloptionsoff_'+hostid;
 3935:     var num = form.elements[radioname].length;
 3936:     if (num) {
 3937:         var setvis = ''; 
 3938:         for (var i=0; i<num; i++) {
 3939:             if (form.elements[radioname][i].checked) {
 3940:                 if (form.elements[radioname][i].value == '1') { 
 3941:                     if (document.getElementById(tablecellon)) {
 3942:                         document.getElementById(tablecellon).style.display='';
 3943:                     }
 3944:                     if (document.getElementById(tablecelloff)) {
 3945:                         document.getElementById(tablecelloff).style.display='none';
 3946:                     }
 3947:                     setvis = 1;
 3948:                 }
 3949:                 break;
 3950:             }
 3951:         }
 3952:         if (!setvis) {
 3953:             if (document.getElementById(tablecellon)) {
 3954:                 document.getElementById(tablecellon).style.display='none';
 3955:             }
 3956:             if (document.getElementById(tablecelloff)) {
 3957:                 document.getElementById(tablecelloff).style.display='';
 3958:             }
 3959:         }
 3960:     }
 3961:     return;
 3962: }
 3963: // ]]>
 3964: </script>
 3965: 
 3966: ENDSCRIPT
 3967: }
 3968: 
 3969: sub ipaccess_javascript {
 3970:     my ($settings) = @_;
 3971:     my (%ordered,$total,%jstext);
 3972:     $total = 0;
 3973:     if (ref($settings) eq 'HASH') {
 3974:         foreach my $item (keys(%{$settings})) {
 3975:             if (ref($settings->{$item}) eq 'HASH') {
 3976:                 my $num = $settings->{$item}{'order'};
 3977:                 $ordered{$num} = $item;
 3978:             }
 3979:         }
 3980:         $total = scalar(keys(%{$settings}));
 3981:     }
 3982:     my @jsarray = ();
 3983:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3984:         push(@jsarray,$ordered{$item});
 3985:     }
 3986:     my $jstext = '    var ipaccess = Array('."'".join("','",@jsarray)."'".');'."\n";
 3987:     return <<"ENDSCRIPT";
 3988: <script type="text/javascript">
 3989: // <![CDATA[
 3990: function reorderIPaccess(form,item) {
 3991:     var changedVal;
 3992: $jstext
 3993:     var newpos = 'ipaccess_pos_add';
 3994:     var maxh = 1 + $total;
 3995:     var current = new Array;
 3996:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 3997:     if (item == newpos) {
 3998:         changedVal = newitemVal;
 3999:     } else {
 4000:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 4001:         current[newitemVal] = newpos;
 4002:     }
 4003:     for (var i=0; i<ipaccess.length; i++) {
 4004:         var elementName = 'ipaccess_pos_'+ipaccess[i];
 4005:         if (elementName != item) {
 4006:             if (form.elements[elementName]) {
 4007:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 4008:                 current[currVal] = elementName;
 4009:             }
 4010:         }
 4011:     }
 4012:     var oldVal;
 4013:     for (var j=0; j<maxh; j++) {
 4014:         if (current[j] == undefined) {
 4015:             oldVal = j;
 4016:         }
 4017:     }
 4018:     if (oldVal < changedVal) {
 4019:         for (var k=oldVal+1; k<=changedVal ; k++) {
 4020:            var elementName = current[k];
 4021:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 4022:         }
 4023:     } else {
 4024:         for (var k=changedVal; k<oldVal; k++) {
 4025:             var elementName = current[k];
 4026:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 4027:         }
 4028:     }
 4029:     return;
 4030: }
 4031: // ]]>
 4032: </script>
 4033: 
 4034: ENDSCRIPT
 4035: }
 4036: 
 4037: sub print_autoenroll {
 4038:     my ($dom,$settings,$rowtotal) = @_;
 4039:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
 4040:     my ($defdom,$runon,$runoff,$coownerson,$coownersoff,
 4041:         $failsafe,$autofailsafe,$failsafesty,%failsafechecked);
 4042:     $failsafesty = 'none';
 4043:     %failsafechecked = (
 4044:         off => ' checked="checked"',
 4045:     );
 4046:     if (ref($settings) eq 'HASH') {
 4047:         if (exists($settings->{'run'})) {
 4048:             if ($settings->{'run'} eq '0') {
 4049:                 $runoff = ' checked="checked" ';
 4050:                 $runon = ' ';
 4051:             } else {
 4052:                 $runon = ' checked="checked" ';
 4053:                 $runoff = ' ';
 4054:             }
 4055:         } else {
 4056:             if ($autorun) {
 4057:                 $runon = ' checked="checked" ';
 4058:                 $runoff = ' ';
 4059:             } else {
 4060:                 $runoff = ' checked="checked" ';
 4061:                 $runon = ' ';
 4062:             }
 4063:         }
 4064:         if (exists($settings->{'co-owners'})) {
 4065:             if ($settings->{'co-owners'} eq '0') {
 4066:                 $coownersoff = ' checked="checked" ';
 4067:                 $coownerson = ' ';
 4068:             } else {
 4069:                 $coownerson = ' checked="checked" ';
 4070:                 $coownersoff = ' ';
 4071:             }
 4072:         } else {
 4073:             $coownersoff = ' checked="checked" ';
 4074:             $coownerson = ' ';
 4075:         }
 4076:         if (exists($settings->{'sender_domain'})) {
 4077:             $defdom = $settings->{'sender_domain'};
 4078:         }
 4079:         if (exists($settings->{'failsafe'})) {
 4080:             $failsafe = $settings->{'failsafe'};
 4081:             if ($failsafe eq 'zero') {
 4082:                 $failsafechecked{'zero'} = ' checked="checked"';
 4083:                 $failsafechecked{'off'} = '';
 4084:                 $failsafesty = 'inline-block';
 4085:             } elsif ($failsafe eq 'any') {
 4086:                 $failsafechecked{'any'} = ' checked="checked"';
 4087:                 $failsafechecked{'off'} = '';
 4088:             }
 4089:             $autofailsafe = $settings->{'autofailsafe'};
 4090:         } elsif (exists($settings->{'autofailsafe'})) {
 4091:             $autofailsafe = $settings->{'autofailsafe'};
 4092:             if ($autofailsafe ne '') {
 4093:                 $failsafechecked{'zero'} = ' checked="checked"';
 4094:                 $failsafe = 'zero';
 4095:                 $failsafechecked{'off'} = '';
 4096:             }
 4097:         }
 4098:     } else {
 4099:         if ($autorun) {
 4100:             $runon = ' checked="checked" ';
 4101:             $runoff = ' ';
 4102:         } else {
 4103:             $runoff = ' checked="checked" ';
 4104:             $runon = ' ';
 4105:         }
 4106:     }
 4107:     my $domform = &Apache::loncommon::select_dom_form($defdom,'sender_domain',1);
 4108:     my $notif_sender;
 4109:     if (ref($settings) eq 'HASH') {
 4110:         $notif_sender = $settings->{'sender_uname'};
 4111:     }
 4112:     my $datatable='<tr class="LC_odd_row">'.
 4113:                   '<td>'.&mt('Auto-enrollment active?').'</td>'.
 4114:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4115:                   '<input type="radio" name="autoenroll_run"'.
 4116:                   $runon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4117:                   '<label><input type="radio" name="autoenroll_run"'.
 4118:                   $runoff.' value="0" />'.&mt('No').'</label></span></td>'.
 4119:                   '</tr><tr>'.
 4120:                   '<td>'.&mt('Notification messages - sender').
 4121:                   '</td><td class="LC_right_item"><span class="LC_nobreak">'.
 4122:                   &mt('username').':&nbsp;'.
 4123:                   '<input type="text" name="sender_uname" value="'.
 4124:                   $notif_sender.'" size="10" />&nbsp;&nbsp;'.&mt('domain').
 4125:                   ':&nbsp;'.$domform.'</span></td></tr>'.
 4126:                   '<tr class="LC_odd_row">'.
 4127:                   '<td>'.&mt('Automatically assign co-ownership').'</td>'.
 4128:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4129:                   '<input type="radio" name="autoassign_coowners"'.
 4130:                   $coownerson.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4131:                   '<label><input type="radio" name="autoassign_coowners"'.
 4132:                   $coownersoff.' value="0" />'.&mt('No').'</label></span></td>'.
 4133:                   '</tr><tr>'.
 4134:                   '<td>'.&mt('Failsafe for no drops when institutional data missing').'</td>'.
 4135:                   '<td class="LC_left_item"><span class="LC_nobreak">'.
 4136:                   '<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; '.
 4137:                   '<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 />'.
 4138:                   '<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>'.
 4139:                   '<div class="LC_floatleft" style="display:'.$failsafesty.';" id="autoenroll_failsafe_div">'.
 4140:                   '<span class="LC_nobreak">'.
 4141:                   &mt('Threshold for number of students in section to drop: [_1]',
 4142:                       '<input type="text" name="autoenroll_autofailsafe" value="'.$autofailsafe.'" size="4" />').
 4143:                   '</span></div></td></tr>';
 4144:     $$rowtotal += 4;
 4145:     return $datatable;
 4146: }
 4147: 
 4148: sub print_autoupdate {
 4149:     my ($position,$dom,$settings,$rowtotal) = @_;
 4150:     my ($enable,$datatable);
 4151:     if ($position eq 'top') {
 4152:         my %choices = &Apache::lonlocal::texthash (
 4153:                           run        => 'Auto-update active?',
 4154:                           classlists => 'Update information in classlists?',
 4155:                           unexpired  => 'Skip updates for users without active or future roles?',
 4156:                           lastactive => 'Skip updates for inactive users?',
 4157:         );
 4158:         my $itemcount = 0;
 4159:         my $updateon = ' ';
 4160:         my $updateoff = ' checked="checked" ';
 4161:         if (ref($settings) eq 'HASH') {
 4162:             if ($settings->{'run'} eq '1') {
 4163:                 $updateon = $updateoff;
 4164:                 $updateoff = ' ';
 4165:             }
 4166:         }
 4167:         $enable = '<tr class="LC_odd_row">'.
 4168:                   '<td>'.$choices{'run'}.'</td>'.
 4169:                   '<td class="LC_left_item"><span class="LC_nobreak"><label>'.
 4170:                   '<input type="radio" name="autoupdate_run"'.
 4171:                   $updateoff.'value="0" />'.&mt('No').'</label>&nbsp;'.
 4172:                   '<label><input type="radio" name="autoupdate_run"'.
 4173:                   $updateon.'value="1" />'.&mt('Yes').'</label></span></td>'.
 4174:                   '</tr>';
 4175:         my @toggles = ('classlists','unexpired');
 4176:         my %defaultchecked = ('classlists' => 'off',
 4177:                               'unexpired'  => 'off'
 4178:                               );
 4179:         $$rowtotal ++;
 4180:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 4181:                                                      \%choices,$itemcount,'','','left','no');
 4182:         $datatable = $enable.$datatable;
 4183:         $$rowtotal += $itemcount;
 4184:         my $lastactiveon = ' ';
 4185:         my $lastactiveoff = ' checked="checked" ';
 4186:         my $lastactivestyle = 'none';
 4187:         my $lastactivedays;
 4188:         my $onclick = ' onclick="javascript:toggleLastActiveDays(this.form);"';
 4189:         if (ref($settings) eq 'HASH') {
 4190:             if ($settings->{'lastactive'} =~ /^\d+$/) {
 4191:                 $lastactiveon = $lastactiveoff;
 4192:                 $lastactiveoff = ' ';
 4193:                 $lastactivestyle = 'inline-block';
 4194:                 $lastactivedays = $settings->{'lastactive'};
 4195:             }
 4196:         }
 4197:         my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4198:         $datatable .= '<tr'.$css_class.'>'.
 4199:                       '<td>'.$choices{'lastactive'}.'</td>'.
 4200:                       '<td class="LC_left_item"><span class="LC_nobreak"><label>'.
 4201:                       '<input type="radio" name="lastactive"'.
 4202:                       $lastactiveoff.'value="0"'.$onclick.' />'.&mt('No').'</label>'.
 4203:                       '&nbsp;<label>'.
 4204:                       '<input type="radio" name="lastactive"'.
 4205:                       $lastactiveon.' value="1"'.$onclick.' />'.&mt('Yes').'</label>'.
 4206:                       '<div id="lastactive_div" style="display:'.$lastactivestyle.';">'.
 4207:                       ':&nbsp;'.&mt('inactive = no activity in last [_1] days',
 4208:                           '<input type="text" size="5" name="lastactivedays" value="'.
 4209:                           $lastactivedays.'" />').
 4210:                       '</span></td>'.
 4211:                       '</tr>';
 4212:         $$rowtotal ++;
 4213:     } elsif ($position eq 'middle') {
 4214:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4215:         my $numinrow = 3;
 4216:         my $locknamesettings;
 4217:         $datatable .= &insttypes_row($settings,$types,$usertypes,
 4218:                                      $dom,$numinrow,$othertitle,
 4219:                                     'lockablenames',$rowtotal);
 4220:         $$rowtotal ++;
 4221:     } else {
 4222:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4223:         my @fields = ('lastname','firstname','middlename','generation',
 4224:                       'permanentemail','id');
 4225:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 4226:         my $numrows = 0;
 4227:         if (ref($types) eq 'ARRAY') {
 4228:             if (@{$types} > 0) {
 4229:                 $datatable = 
 4230:                     &usertype_update_row($settings,$usertypes,\%fieldtitles,
 4231:                                          \@fields,$types,\$numrows);
 4232:                     $$rowtotal += @{$types}; 
 4233:             }
 4234:         }
 4235:         $datatable .= 
 4236:             &usertype_update_row($settings,{'default' => $othertitle},
 4237:                                  \%fieldtitles,\@fields,['default'],
 4238:                                  \$numrows);
 4239:         $$rowtotal ++;     
 4240:     }
 4241:     return $datatable;
 4242: }
 4243: 
 4244: sub print_autocreate {
 4245:     my ($dom,$settings,$rowtotal) = @_;
 4246:     my (%createon,%createoff,%currhash);
 4247:     my @types = ('xml','req');
 4248:     if (ref($settings) eq 'HASH') {
 4249:         foreach my $item (@types) {
 4250:             $createoff{$item} = ' checked="checked" ';
 4251:             $createon{$item} = ' ';
 4252:             if (exists($settings->{$item})) {
 4253:                 if ($settings->{$item}) {
 4254:                     $createon{$item} = ' checked="checked" ';
 4255:                     $createoff{$item} = ' ';
 4256:                 }
 4257:             }
 4258:         }
 4259:         if ($settings->{'xmldc'} ne '') {
 4260:             $currhash{$settings->{'xmldc'}} = 1;
 4261:         }
 4262:     } else {
 4263:         foreach my $item (@types) {
 4264:             $createoff{$item} = ' checked="checked" ';
 4265:             $createon{$item} = ' ';
 4266:         }
 4267:     }
 4268:     $$rowtotal += 2;
 4269:     my $numinrow = 2;
 4270:     my $datatable='<tr class="LC_odd_row">'.
 4271:                   '<td>'.&mt('Create pending official courses from XML files').'</td>'.
 4272:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4273:                   '<input type="radio" name="autocreate_xml"'.
 4274:                   $createon{'xml'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4275:                   '<label><input type="radio" name="autocreate_xml"'.
 4276:                   $createoff{'xml'}.' value="0" />'.&mt('No').'</label></span>'.
 4277:                   '</td></tr><tr>'.
 4278:                   '<td>'.&mt('Create pending requests for official courses (if validated)').'</td>'.
 4279:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4280:                   '<input type="radio" name="autocreate_req"'.
 4281:                   $createon{'req'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4282:                   '<label><input type="radio" name="autocreate_req"'.
 4283:                   $createoff{'req'}.' value="0" />'.&mt('No').'</label></span>';
 4284:     my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 4285:                                                    'autocreate_xmldc',%currhash);
 4286:     $datatable .= '</td></tr><tr class="LC_odd_row"><td>';
 4287:     if ($numdc > 1) {
 4288:         $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)').
 4289:                       '</td><td class="LC_left_item">';
 4290:     } else {
 4291:         $datatable .= &mt('Course creation processed as:').
 4292:                       '</td><td class="LC_right_item">';
 4293:     }
 4294:     $datatable .= $dctable.'</td></tr>';
 4295:     $$rowtotal += $rows;
 4296:     return $datatable;
 4297: }
 4298: 
 4299: sub print_directorysrch {
 4300:     my ($position,$dom,$settings,$rowtotal) = @_;
 4301:     my $datatable;
 4302:     if ($position eq 'top') {
 4303:         my $instsrchon = ' ';
 4304:         my $instsrchoff = ' checked="checked" ';
 4305:         my ($exacton,$containson,$beginson);
 4306:         my $instlocalon = ' ';
 4307:         my $instlocaloff = ' checked="checked" ';
 4308:         if (ref($settings) eq 'HASH') {
 4309:             if ($settings->{'available'} eq '1') {
 4310:                 $instsrchon = $instsrchoff;
 4311:                 $instsrchoff = ' ';
 4312:             }
 4313:             if ($settings->{'localonly'} eq '1') {
 4314:                 $instlocalon = $instlocaloff;
 4315:                 $instlocaloff = ' ';
 4316:             }
 4317:             if (ref($settings->{'searchtypes'}) eq 'ARRAY') {
 4318:                 foreach my $type (@{$settings->{'searchtypes'}}) {
 4319:                     if ($type eq 'exact') {
 4320:                         $exacton = ' checked="checked" ';
 4321:                     } elsif ($type eq 'contains') {
 4322:                         $containson = ' checked="checked" ';
 4323:                     } elsif ($type eq 'begins') {
 4324:                         $beginson = ' checked="checked" ';
 4325:                     }
 4326:                 }
 4327:             } else {
 4328:                 if ($settings->{'searchtypes'} eq 'exact') {
 4329:                     $exacton = ' checked="checked" ';
 4330:                 } elsif ($settings->{'searchtypes'} eq 'contains') {
 4331:                     $containson = ' checked="checked" ';
 4332:                 } elsif ($settings->{'searchtypes'} eq 'specify') {
 4333:                     $exacton = ' checked="checked" ';
 4334:                     $containson = ' checked="checked" ';
 4335:                 }
 4336:             }
 4337:         }
 4338:         my ($searchtitles,$titleorder) = &sorted_searchtitles();
 4339:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4340: 
 4341:         my $numinrow = 4;
 4342:         my $cansrchrow = 0;
 4343:         $datatable='<tr class="LC_odd_row">'.
 4344:                    '<td colspan="2"><span class ="LC_nobreak">'.&mt('Institutional directory search available?').'</span></td>'.
 4345:                    '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4346:                    '<input type="radio" name="dirsrch_available"'.
 4347:                    $instsrchon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4348:                    '<label><input type="radio" name="dirsrch_available"'.
 4349:                    $instsrchoff.' value="0" />'.&mt('No').'</label></span></td>'.
 4350:                    '</tr><tr>'.
 4351:                    '<td colspan="2"><span class ="LC_nobreak">'.&mt('Other domains can search institution?').'</span></td>'.
 4352:                    '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4353:                    '<input type="radio" name="dirsrch_instlocalonly"'.
 4354:                    $instlocaloff.' value="0" />'.&mt('Yes').'</label>&nbsp;'.
 4355:                    '<label><input type="radio" name="dirsrch_instlocalonly"'.
 4356:                    $instlocalon.' value="1" />'.&mt('No').'</label></span></td>'.
 4357:                    '</tr>';
 4358:         $$rowtotal += 2;
 4359:         if (ref($usertypes) eq 'HASH') {
 4360:             if (keys(%{$usertypes}) > 0) {
 4361:                 $datatable .= &insttypes_row($settings,$types,$usertypes,$dom,
 4362:                                              $numinrow,$othertitle,'cansearch',
 4363:                                              $rowtotal);
 4364:                 $cansrchrow = 1;
 4365:             }
 4366:         }
 4367:         if ($cansrchrow) {
 4368:             $$rowtotal ++;
 4369:             $datatable .= '<tr>';
 4370:         } else {
 4371:             $datatable .= '<tr class="LC_odd_row">';
 4372:         }
 4373:         $datatable .= '<td><span class ="LC_nobreak">'.&mt('Supported search methods').
 4374:                       '</span></td><td class="LC_left_item" colspan="2"><table><tr>';
 4375:         foreach my $title (@{$titleorder}) {
 4376:             if (defined($searchtitles->{$title})) {
 4377:                 my $check = ' ';
 4378:                 if (ref($settings) eq 'HASH') {
 4379:                     if (ref($settings->{'searchby'}) eq 'ARRAY') {
 4380:                         if (grep(/^\Q$title\E$/,@{$settings->{'searchby'}})) {
 4381:                             $check = ' checked="checked" ';
 4382:                         }
 4383:                     }
 4384:                 }
 4385:                 $datatable .= '<td class="LC_left_item">'.
 4386:                               '<span class="LC_nobreak"><label>'.
 4387:                               '<input type="checkbox" name="searchby" '.
 4388:                               'value="'.$title.'"'.$check.'/>'.
 4389:                               $searchtitles->{$title}.'</label></span></td>';
 4390:             }
 4391:         }
 4392:         $datatable .= '</tr></table></td></tr>';
 4393:         $$rowtotal ++;
 4394:         if ($cansrchrow) {
 4395:             $datatable .= '<tr class="LC_odd_row">';
 4396:         } else {
 4397:             $datatable .= '<tr>';
 4398:         }
 4399:         $datatable .= '<td><span class ="LC_nobreak">'.&mt('Search latitude').'</span></td>'.   
 4400:                       '<td class="LC_left_item" colspan="2">'.
 4401:                       '<span class="LC_nobreak"><label>'.
 4402:                       '<input type="checkbox" name="searchtypes" '.
 4403:                       $exacton.' value="exact" />'.&mt('Exact match').
 4404:                       '</label>&nbsp;'.
 4405:                       '<label><input type="checkbox" name="searchtypes" '.
 4406:                       $beginson.' value="begins" />'.&mt('Begins with').
 4407:                       '</label>&nbsp;'.
 4408:                       '<label><input type="checkbox" name="searchtypes" '.
 4409:                       $containson.' value="contains" />'.&mt('Contains').
 4410:                       '</label></span></td></tr>';
 4411:         $$rowtotal ++;
 4412:     } else {
 4413:         my $domsrchon = ' checked="checked" ';
 4414:         my $domsrchoff = ' ';
 4415:         my $domlocalon = ' ';
 4416:         my $domlocaloff = ' checked="checked" ';
 4417:         if (ref($settings) eq 'HASH') {
 4418:             if ($settings->{'lclocalonly'} eq '1') {
 4419:                 $domlocalon = $domlocaloff;
 4420:                 $domlocaloff = ' ';
 4421:             }
 4422:             if ($settings->{'lcavailable'} eq '0') {
 4423:                 $domsrchoff = $domsrchon;
 4424:                 $domsrchon = ' ';
 4425:             }
 4426:         }
 4427:         $datatable='<tr class="LC_odd_row">'.
 4428:                       '<td colspan="2"><span class ="LC_nobreak">'.&mt('LON-CAPA directory search available?').'</span></td>'.
 4429:                       '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4430:                       '<input type="radio" name="dirsrch_domavailable"'.
 4431:                       $domsrchon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4432:                       '<label><input type="radio" name="dirsrch_domavailable"'.
 4433:                       $domsrchoff.' value="0" />'.&mt('No').'</label></span></td>'.
 4434:                       '</tr><tr>'.
 4435:                       '<td colspan="2"><span class ="LC_nobreak">'.&mt('Other domains can search LON-CAPA domain?').'</span></td>'.
 4436:                       '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4437:                       '<input type="radio" name="dirsrch_domlocalonly"'.
 4438:                       $domlocaloff.' value="0" />'.&mt('Yes').'</label>&nbsp;'.
 4439:                       '<label><input type="radio" name="dirsrch_domlocalonly"'.
 4440:                       $domlocalon.' value="1" />'.&mt('No').'</label></span></td>'.
 4441:                       '</tr>';
 4442:         $$rowtotal += 2;
 4443:     }
 4444:     return $datatable;
 4445: }
 4446: 
 4447: sub print_contacts {
 4448:     my ($position,$dom,$settings,$rowtotal) = @_;
 4449:     my $datatable;
 4450:     my @contacts = ('adminemail','supportemail');
 4451:     my (%checked,%to,%otheremails,%bccemails,%includestr,%includeloc,%currfield,
 4452:         $maxsize,$fields,$fieldtitles,$fieldoptions,$possoptions,@mailings,%lonstatus);
 4453:     if ($position eq 'top') {
 4454:         if (ref($settings) eq 'HASH') {
 4455:             foreach my $item (@contacts) {
 4456:                 if (exists($settings->{$item})) {
 4457:                     $to{$item} = $settings->{$item};
 4458:                 }
 4459:             }
 4460:         }
 4461:     } elsif ($position eq 'middle') {
 4462:         @mailings = ('errormail','packagesmail','lonstatusmail','requestsmail',
 4463:                      'updatesmail','idconflictsmail','hostipmail');
 4464:         foreach my $type (@mailings) {
 4465:             $otheremails{$type} = '';
 4466:         }
 4467:     } elsif ($position eq 'lower') {
 4468:         if (ref($settings) eq 'HASH') {
 4469:             if (ref($settings->{'lonstatus'}) eq 'HASH') {
 4470:                 %lonstatus = %{$settings->{'lonstatus'}};
 4471:             }
 4472:         }
 4473:     } else {
 4474:         @mailings = ('helpdeskmail','otherdomsmail');
 4475:         foreach my $type (@mailings) {
 4476:             $otheremails{$type} = '';
 4477:         }
 4478:         $bccemails{'helpdeskmail'} = '';
 4479:         $bccemails{'otherdomsmail'} = '';
 4480:         $includestr{'helpdeskmail'} = '';
 4481:         $includestr{'otherdomsmail'} = '';
 4482:         ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
 4483:     }
 4484:     if (ref($settings) eq 'HASH') {
 4485:         unless (($position eq 'top') || ($position eq 'lower')) {
 4486:             foreach my $type (@mailings) {
 4487:                 if (exists($settings->{$type})) {
 4488:                     if (ref($settings->{$type}) eq 'HASH') {
 4489:                         foreach my $item (@contacts) {
 4490:                             if ($settings->{$type}{$item}) {
 4491:                                 $checked{$type}{$item} = ' checked="checked" ';
 4492:                             }
 4493:                         }
 4494:                         $otheremails{$type} = $settings->{$type}{'others'};
 4495:                         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 4496:                             $bccemails{$type} = $settings->{$type}{'bcc'};
 4497:                             if ($settings->{$type}{'include'} ne '') {
 4498:                                 ($includeloc{$type},$includestr{$type}) = split(/:/,$settings->{$type}{'include'},2);
 4499:                                 $includestr{$type} = &unescape($includestr{$type});
 4500:                             }
 4501:                         }
 4502:                     }
 4503:                 } elsif ($type eq 'lonstatusmail') {
 4504:                     $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" ';
 4505:                 }
 4506:             }
 4507:         }
 4508:         if ($position eq 'bottom') {
 4509:             foreach my $type (@mailings) {
 4510:                 $bccemails{$type} = $settings->{$type}{'bcc'};
 4511:                 if ($settings->{$type}{'include'} ne '') {
 4512:                     ($includeloc{$type},$includestr{$type}) = split(/:/,$settings->{$type}{'include'},2);
 4513:                     $includestr{$type} = &unescape($includestr{$type});
 4514:                 }
 4515:             }
 4516:             if (ref($settings->{'helpform'}) eq 'HASH') {
 4517:                 if (ref($fields) eq 'ARRAY') {
 4518:                     foreach my $field (@{$fields}) {
 4519:                         $currfield{$field} = $settings->{'helpform'}{$field};
 4520:                     }
 4521:                 }
 4522:                 if (exists($settings->{'helpform'}{'maxsize'})) {
 4523:                     $maxsize = $settings->{'helpform'}{'maxsize'};
 4524:                 } else {
 4525:                     $maxsize = '1.0';
 4526:                 }
 4527:             } else {
 4528:                 if (ref($fields) eq 'ARRAY') {
 4529:                     foreach my $field (@{$fields}) {
 4530:                         $currfield{$field} = 'yes';
 4531:                     }
 4532:                 }
 4533:                 $maxsize = '1.0';
 4534:             }
 4535:         }
 4536:     } else {
 4537:         if ($position eq 'top') {
 4538:             $to{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
 4539:             $to{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
 4540:             $checked{'errormail'}{'adminemail'} = ' checked="checked" ';
 4541:             $checked{'packagesmail'}{'adminemail'} = ' checked="checked" ';
 4542:             $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" ';
 4543:             $checked{'requestsmail'}{'adminemail'} = ' checked="checked" ';
 4544:             $checked{'updatesmail'}{'adminemail'} = ' checked="checked" ';
 4545:             $checked{'idconflictsmail'}{'adminemail'} = ' checked="checked" ';
 4546:             $checked{'hostipmail'}{'adminemail'} = ' checked="checked" ';
 4547:         } elsif ($position eq 'bottom') {
 4548:             $checked{'helpdeskmail'}{'supportemail'} = ' checked="checked" ';
 4549:             $checked{'otherdomsmail'}{'supportemail'} = ' checked="checked" ';
 4550:             if (ref($fields) eq 'ARRAY') {
 4551:                 foreach my $field (@{$fields}) {
 4552:                     $currfield{$field} = 'yes';
 4553:                 }
 4554:             }
 4555:             $maxsize = '1.0';
 4556:         }
 4557:     }
 4558:     my ($titles,$short_titles) = &contact_titles();
 4559:     my $rownum = 0;
 4560:     my $css_class;
 4561:     if ($position eq 'top') {
 4562:         foreach my $item (@contacts) {
 4563:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 4564:             $datatable .= '<tr'.$css_class.'>'. 
 4565:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
 4566:                           '</span></td><td class="LC_right_item">'.
 4567:                           '<input type="text" name="'.$item.'" value="'.
 4568:                           $to{$item}.'" /></td></tr>';
 4569:             $rownum ++;
 4570:         }
 4571:     } elsif ($position eq 'bottom') {
 4572:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 4573:         $datatable .= '<tr'.$css_class.'>'.
 4574:                       '<td>'.&mt('Extra helpdesk form fields:').'<br />'.
 4575:                       &mt('(e-mail, subject, and description always shown)').
 4576:                       '</td><td class="LC_left_item">';
 4577:         if ((ref($fields) eq 'ARRAY') && (ref($fieldtitles) eq 'HASH') &&
 4578:             (ref($fieldoptions) eq 'HASH') && (ref($possoptions) eq 'HASH')) {
 4579:             $datatable .= '<table><tr><th>'.&mt('Field').'</th><th>'.&mt('Status').'</th></tr>';
 4580:             foreach my $field (@{$fields}) {
 4581:                 $datatable .= '<tr><td>'.$fieldtitles->{$field};
 4582:                 if (($field eq 'screenshot') || ($field eq 'cc')) {
 4583:                     $datatable .= ' '.&mt('(logged-in users)');
 4584:                 }
 4585:                 $datatable .='</td><td>';
 4586:                 my $clickaction;
 4587:                 if ($field eq 'screenshot') {
 4588:                     $clickaction = ' onclick="screenshotSize(this);"';
 4589:                 }
 4590:                 if (ref($possoptions->{$field}) eq 'ARRAY') {
 4591:                     foreach my $option (@{$possoptions->{$field}}) {
 4592:                         my $checked;
 4593:                         if ($currfield{$field} eq $option) {
 4594:                             $checked = ' checked="checked"';
 4595:                         }
 4596:                         $datatable .= '<span class="LC_nobreak"><label>'.
 4597:                                       '<input type="radio" name="helpform_'.$field.'" '.
 4598:                                       'value="'.$option.'"'.$checked.$clickaction.' />'.$fieldoptions->{$option}.
 4599:                                       '</label></span>'.('&nbsp;'x2);
 4600:                     }
 4601:                 }
 4602:                 if ($field eq 'screenshot') {
 4603:                     my $display;
 4604:                     if ($currfield{$field} eq 'no') {
 4605:                         $display = ' style="display:none"';
 4606:                     }
 4607:                     $datatable .= '</td></tr><tr id="help_screenshotsize"'.$display.'>'.
 4608:                                   '<td>'.&mt('Maximum size for upload (MB)').'</td><td>'.
 4609:                                   '<input type="text" size="5" name="helpform_maxsize" value="'.$maxsize.'" />';
 4610:                 }
 4611:                 $datatable .= '</td></tr>';
 4612:             }
 4613:             $datatable .= '</table>';
 4614:         }
 4615:         $datatable .= '</td></tr>'."\n";
 4616:         $rownum ++;
 4617:     }
 4618:     unless (($position eq 'top') || ($position eq 'lower')) {
 4619:         foreach my $type (@mailings) {
 4620:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 4621:             $datatable .= '<tr'.$css_class.'>'.
 4622:                           '<td><span class="LC_nobreak">'.
 4623:                           $titles->{$type}.': </span></td>'.
 4624:                           '<td class="LC_left_item">';
 4625:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 4626:                 $datatable .= '<fieldset><legend>'.&mt('E-mail recipient(s)').'</legend>';
 4627:             }
 4628:             $datatable .= '<span class="LC_nobreak">';
 4629:             foreach my $item (@contacts) {
 4630:                 $datatable .= '<label>'.
 4631:                               '<input type="checkbox" name="'.$type.'"'.
 4632:                               $checked{$type}{$item}.
 4633:                               ' value="'.$item.'" />'.$short_titles->{$item}.
 4634:                               '</label>&nbsp;';
 4635:             }
 4636:             $datatable .= '</span><br />'.&mt('Others').':&nbsp;&nbsp;'.
 4637:                           '<input type="text" name="'.$type.'_others" '.
 4638:                           'value="'.$otheremails{$type}.'"  />';
 4639:             my %locchecked;
 4640:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 4641:                 foreach my $loc ('s','b') {
 4642:                     if ($includeloc{$type} eq $loc) {
 4643:                         $locchecked{$loc} = ' checked="checked"';
 4644:                         last;
 4645:                     }
 4646:                 }
 4647:                 $datatable .= '<br />'.&mt('Bcc:').('&nbsp;'x6).
 4648:                               '<input type="text" name="'.$type.'_bcc" '.
 4649:                               'value="'.$bccemails{$type}.'"  /></fieldset>'.
 4650:                               '<fieldset><legend>'.&mt('Optional added text').'</legend>'.
 4651:                               &mt('Text automatically added to e-mail:').' '.
 4652:                               '<input type="text" name="'.$type.'_includestr" value="'.$includestr{$type}.'" /><br />'.
 4653:                               '<span class="LC_nobreak">'.&mt('Location:').'&nbsp;'.
 4654:                               '<label><input type="radio" name="'.$type.'_includeloc" value="s"'.$locchecked{'s'}.' />'.&mt('in subject').'</label>'.
 4655:                               ('&nbsp;'x2).
 4656:                               '<label><input type="radio" name="'.$type.'_includeloc" value="b"'.$locchecked{'b'}.' />'.&mt('in body').'</label>'.
 4657:                               '</span></fieldset>';
 4658:             }
 4659:             $datatable .= '</td></tr>'."\n";
 4660:             $rownum ++;
 4661:         }
 4662:     }
 4663:     if ($position eq 'middle') {
 4664:         my %choices;
 4665:         my $corelink = &core_link_msu();
 4666:         $choices{'reporterrors'} = &mt('E-mail error reports to [_1]',$corelink);
 4667:         $choices{'reportupdates'} = &mt('E-mail record of completed LON-CAPA updates to [_1]',
 4668:                                         $corelink);
 4669:         $choices{'reportstatus'} = &mt('E-mail status if errors above threshold to [_1]',$corelink);
 4670:         my @toggles = ('reporterrors','reportupdates','reportstatus');
 4671:         my %defaultchecked = ('reporterrors'  => 'on',
 4672:                               'reportupdates' => 'on',
 4673:                               'reportstatus'  => 'on');
 4674:         (my $reports,$rownum) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 4675:                                                    \%choices,$rownum);
 4676:         $datatable .= $reports;
 4677:     } elsif ($position eq 'lower') {
 4678:         my (%current,%excluded,%weights);
 4679:         my ($defaults,$names) = &Apache::loncommon::lon_status_items();
 4680:         if ($lonstatus{'threshold'} =~ /^\d+$/) {
 4681:             $current{'errorthreshold'} = $lonstatus{'threshold'};
 4682:         } else {
 4683:             $current{'errorthreshold'} = $defaults->{'threshold'};
 4684:         }
 4685:         if ($lonstatus{'sysmail'} =~ /^\d+$/) {
 4686:             $current{'errorsysmail'} = $lonstatus{'sysmail'};
 4687:         } else {
 4688:             $current{'errorsysmail'} = $defaults->{'sysmail'};
 4689:         }
 4690:         if (ref($lonstatus{'weights'}) eq 'HASH') {
 4691:             foreach my $type ('E','W','N','U') {
 4692:                 if ($lonstatus{'weights'}{$type} =~ /^\d+$/) {
 4693:                     $weights{$type} = $lonstatus{'weights'}{$type};
 4694:                 } else {
 4695:                     $weights{$type} = $defaults->{$type};
 4696:                 }
 4697:             }
 4698:         } else {
 4699:             foreach my $type ('E','W','N','U') {
 4700:                 $weights{$type} = $defaults->{$type};
 4701:             }
 4702:         }
 4703:         if (ref($lonstatus{'excluded'}) eq 'ARRAY') {
 4704:             if (@{$lonstatus{'excluded'}} > 0) {
 4705:                 map {$excluded{$_} = 1; } @{$lonstatus{'excluded'}};
 4706:             }
 4707:         }
 4708:         foreach my $item ('errorthreshold','errorsysmail') { 
 4709:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 4710:             $datatable .= '<tr'.$css_class.'>'.
 4711:                           '<td class="LC_left_item"><span class="LC_nobreak">'.
 4712:                           $titles->{$item}.
 4713:                           '</span></td><td class="LC_left_item">'.
 4714:                           '<input type="text" name="'.$item.'" value="'.
 4715:                           $current{$item}.'" size="5" /></td></tr>';
 4716:             $rownum ++;
 4717:         }
 4718:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 4719:         $datatable .= '<tr'.$css_class.'>'.
 4720:                       '<td class="LC_left_item">'.
 4721:                       '<span class="LC_nobreak">'.$titles->{'errorweights'}.
 4722:                       '</span></td><td class="LC_left_item"><table><tr>';
 4723:         foreach my $type ('E','W','N','U') {
 4724:             $datatable .= '<td>'.$names->{$type}.'<br />'.
 4725:                           '<input type="text" name="errorweights_'.$type.'" value="'.
 4726:                           $weights{$type}.'" size="5" /></td>';
 4727:         }
 4728:         $datatable .= '</tr></table></tr>';
 4729:         $rownum ++;
 4730:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 4731:         $datatable .= '<tr'.$css_class.'><td class="LC_left_item">'.
 4732:                       $titles->{'errorexcluded'}.'</td>'.
 4733:                       '<td class="LC_left_item"><table>';
 4734:         my $numinrow = 4;
 4735:         my @ids = sort(values(%Apache::lonnet::serverhomeIDs));
 4736:         for (my $i=0; $i<@ids; $i++) {
 4737:             my $rem = $i%($numinrow);
 4738:             if ($rem == 0) {
 4739:                 if ($i > 0) {
 4740:                     $datatable .= '</tr>';
 4741:                 }
 4742:                 $datatable .= '<tr>';
 4743:             }
 4744:             my $check;
 4745:             if ($excluded{$ids[$i]}) {
 4746:                 $check = ' checked="checked" ';
 4747:             }
 4748:             $datatable .= '<td class="LC_left_item">'.
 4749:                           '<span class="LC_nobreak"><label>'.
 4750:                           '<input type="checkbox" name="errorexcluded" '.
 4751:                           'value="'.$ids[$i].'"'.$check.' />'.
 4752:                           $ids[$i].'</label></span></td>';
 4753:         }
 4754:         my $colsleft = $numinrow - @ids%($numinrow);
 4755:         if ($colsleft > 1 ) {
 4756:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 4757:                           '&nbsp;</td>';
 4758:         } elsif ($colsleft == 1) {
 4759:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 4760:         }
 4761:         $datatable .= '</tr></table></td></tr>';
 4762:         $rownum ++;
 4763:     } elsif ($position eq 'bottom') {
 4764:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4765:         my (@posstypes,%usertypeshash);
 4766:         if (ref($types) eq 'ARRAY') {
 4767:             @posstypes = @{$types};
 4768:         }
 4769:         if (@posstypes) {
 4770:             if (ref($usertypes) eq 'HASH') {
 4771:                 %usertypeshash = %{$usertypes};
 4772:             }
 4773:             my @overridden;
 4774:             my $numinrow = 4;
 4775:             if (ref($settings) eq 'HASH') {
 4776:                 if (ref($settings->{'overrides'}) eq 'HASH') {
 4777:                     foreach my $key (sort(keys(%{$settings->{'overrides'}}))) {
 4778:                         if (ref($settings->{'overrides'}{$key}) eq 'HASH') {
 4779:                             push(@overridden,$key);
 4780:                             foreach my $item (@contacts) {
 4781:                                 if ($settings->{'overrides'}{$key}{$item}) {
 4782:                                     $checked{'override_'.$key}{$item} = ' checked="checked" ';
 4783:                                 }
 4784:                             }
 4785:                             $otheremails{'override_'.$key} = $settings->{'overrides'}{$key}{'others'};
 4786:                             $bccemails{'override_'.$key} = $settings->{'overrides'}{$key}{'bcc'};
 4787:                             $includeloc{'override_'.$key} = '';
 4788:                             $includestr{'override_'.$key} = '';
 4789:                             if ($settings->{'overrides'}{$key}{'include'} ne '') {
 4790:                                 ($includeloc{'override_'.$key},$includestr{'override_'.$key}) = 
 4791:                                     split(/:/,$settings->{'overrides'}{$key}{'include'},2);
 4792:                                 $includestr{'override_'.$key} = &unescape($includestr{'override_'.$key});
 4793:                             }
 4794:                         }
 4795:                     }
 4796:                 }
 4797:             }
 4798:             my $customclass = 'LC_helpdesk_override';
 4799:             my $optionsprefix = 'LC_options_helpdesk_';
 4800: 
 4801:             my $onclicktypes = "toggleHelpdeskRow(this.form,'overrides','$customclass','$optionsprefix');";
 4802:  
 4803:             $datatable .= &insttypes_row($settings,$types,$usertypes,$dom,
 4804:                                          $numinrow,$othertitle,'overrides',
 4805:                                          \$rownum,$onclicktypes,$customclass);
 4806:             $rownum ++;
 4807:             $usertypeshash{'default'} = $othertitle;
 4808:             foreach my $status (@posstypes) {
 4809:                 my $css_class;
 4810:                 if ($rownum%2) {
 4811:                     $css_class = 'LC_odd_row ';
 4812:                 }
 4813:                 $css_class .= $customclass;
 4814:                 my $rowid = $optionsprefix.$status;
 4815:                 my $hidden = 1;
 4816:                 my $currstyle = 'display:none';
 4817:                 if (grep(/^\Q$status\E$/,@overridden)) {
 4818:                     $currstyle = 'display:table-row';
 4819:                     $hidden = 0;
 4820:                 }
 4821:                 my $key = 'override_'.$status;
 4822:                 $datatable .= &overridden_helpdesk($checked{$key},$otheremails{$key},$bccemails{$key},
 4823:                                                   $includeloc{$key},$includestr{$key},$status,$rowid,
 4824:                                                   $usertypeshash{$status},$css_class,$currstyle,
 4825:                                                   \@contacts,$short_titles);
 4826:                 unless ($hidden) {
 4827:                     $rownum ++;
 4828:                 }
 4829:             }
 4830:         }
 4831:     }
 4832:     $$rowtotal += $rownum;
 4833:     return $datatable;
 4834: }
 4835: 
 4836: sub core_link_msu {
 4837:     return &Apache::loncommon::modal_link('http://loncapa.org/core.html',
 4838:                                           &mt('LON-CAPA core group - MSU'),600,500);
 4839: }
 4840: 
 4841: sub overridden_helpdesk {
 4842:     my ($checked,$otheremails,$bccemails,$includeloc,$includestr,$type,$rowid,
 4843:         $typetitle,$css_class,$rowstyle,$contacts,$short_titles) = @_;
 4844:     my $class = 'LC_left_item';
 4845:     if ($css_class) {
 4846:         $css_class = ' class="'.$css_class.'"';
 4847:     }
 4848:     if ($rowid) {
 4849:         $rowid = ' id="'.$rowid.'"';
 4850:     }
 4851:     if ($rowstyle) {
 4852:         $rowstyle = ' style="'.$rowstyle.'"';
 4853:     }
 4854:     my ($output,$description);
 4855:     $description = &mt('Helpdesk requests from: [_1] in this domain (overrides default)',"<b>$typetitle</b>");
 4856:     $output = '<tr'.$css_class.$rowid.$rowstyle.'>'.
 4857:               "<td>$description</td>\n".
 4858:               '<td class="'.$class.'" colspan="2">'.
 4859:               '<fieldset><legend>'.&mt('E-mail recipient(s)').'</legend>'.
 4860:               '<span class="LC_nobreak">';
 4861:     if (ref($contacts) eq 'ARRAY') {
 4862:         foreach my $item (@{$contacts}) {
 4863:             my $check;
 4864:             if (ref($checked) eq 'HASH') {
 4865:                $check = $checked->{$item};
 4866:             }
 4867:             my $title;
 4868:             if (ref($short_titles) eq 'HASH') {
 4869:                 $title = $short_titles->{$item}; 
 4870:             }
 4871:             $output .= '<label>'.
 4872:                        '<input type="checkbox" name="override_'.$type.'"'.$check.
 4873:                        ' value="'.$item.'" />'.$title.'</label>&nbsp;';
 4874:         }
 4875:     }
 4876:     $output .= '</span><br />'.&mt('Others').':&nbsp;&nbsp;'.
 4877:                '<input type="text" name="override_'.$type.'_others" '.
 4878:                'value="'.$otheremails.'"  />';
 4879:     my %locchecked;
 4880:     foreach my $loc ('s','b') {
 4881:         if ($includeloc eq $loc) {
 4882:             $locchecked{$loc} = ' checked="checked"';
 4883:             last;
 4884:         }
 4885:     }
 4886:     $output .= '<br />'.&mt('Bcc:').('&nbsp;'x6).
 4887:                '<input type="text" name="override_'.$type.'_bcc" '.
 4888:                'value="'.$bccemails.'"  /></fieldset>'.
 4889:                '<fieldset><legend>'.&mt('Optional added text').'</legend>'.
 4890:                &mt('Text automatically added to e-mail:').' '.
 4891:                '<input type="text" name="override_'.$type.'_includestr" value="'.$includestr.'" /><br />'.
 4892:                '<span class="LC_nobreak">'.&mt('Location:').'&nbsp;'.
 4893:                '<label><input type="radio" name="override_'.$type.'_includeloc" value="s"'.$locchecked{'s'}.' />'.&mt('in subject').'</label>'.
 4894:                ('&nbsp;'x2).
 4895:                '<label><input type="radio" name="override_'.$type.'_includeloc" value="b"'.$locchecked{'b'}.' />'.&mt('in body').'</label>'.
 4896:                '</span></fieldset>'.
 4897:                '</td></tr>'."\n";
 4898:     return $output;
 4899: }
 4900: 
 4901: sub contacts_javascript {
 4902:     return <<"ENDSCRIPT";
 4903: 
 4904: <script type="text/javascript">
 4905: // <![CDATA[
 4906: 
 4907: function screenshotSize(field) {
 4908:     if (document.getElementById('help_screenshotsize')) {
 4909:         if (field.value == 'no') {
 4910:             document.getElementById('help_screenshotsize').style.display="none";
 4911:         } else {
 4912:             document.getElementById('help_screenshotsize').style.display="";
 4913:         }
 4914:     }
 4915:     return;
 4916: }
 4917: 
 4918: function toggleHelpdeskRow(form,checkbox,target,prefix,docount) {
 4919:     if (form.elements[checkbox].length != undefined) {
 4920:         var count = 0;
 4921:         if (docount) {
 4922:             for (var i=0; i<form.elements[checkbox].length; i++) {
 4923:                 if (form.elements[checkbox][i].checked) {
 4924:                     count ++;
 4925:                 }
 4926:             }
 4927:         }
 4928:         for (var i=0; i<form.elements[checkbox].length; i++) {
 4929:             var type = form.elements[checkbox][i].value;
 4930:             if (document.getElementById(prefix+type)) {
 4931:                 if (form.elements[checkbox][i].checked) {
 4932:                     document.getElementById(prefix+type).style.display = 'table-row';
 4933:                     if (count % 2 == 1) {
 4934:                         document.getElementById(prefix+type).className = target+' LC_odd_row';
 4935:                     } else {
 4936:                         document.getElementById(prefix+type).className = target;
 4937:                     }
 4938:                     count ++;
 4939:                 } else {
 4940:                     document.getElementById(prefix+type).style.display = 'none';
 4941:                 }
 4942:             }
 4943:         }
 4944:     }
 4945:     return;
 4946: }
 4947: 
 4948: 
 4949: // ]]>
 4950: </script>
 4951: 
 4952: ENDSCRIPT
 4953: }
 4954: 
 4955: sub print_helpsettings {
 4956:     my ($position,$dom,$settings,$rowtotal) = @_;
 4957:     my $confname = $dom.'-domainconfig';
 4958:     my $formname = 'display';
 4959:     my ($datatable,$itemcount);
 4960:     if ($position eq 'top') {
 4961:         $itemcount = 1;
 4962:         my (%choices,%defaultchecked,@toggles);
 4963:         $choices{'submitbugs'} = &mt('Display link to: [_1]?',
 4964:                                      &Apache::loncommon::modal_link('http://bugs.loncapa.org',
 4965:                                      &mt('LON-CAPA bug tracker'),600,500));
 4966:         %defaultchecked = ('submitbugs' => 'on');
 4967:         @toggles = ('submitbugs');
 4968:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 4969:                                                      \%choices,$itemcount);
 4970:         $$rowtotal ++;
 4971:     } else {
 4972:         my $css_class;
 4973:         my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
 4974:         my (%customroles,%ordered,%current);
 4975:         if (ref($settings) eq 'HASH') {
 4976:             if (ref($settings->{'adhoc'}) eq 'HASH') {
 4977:                 %current = %{$settings->{'adhoc'}};
 4978:             }
 4979:         }
 4980:         my $count = 0;
 4981:         foreach my $key (sort(keys(%existing))) {
 4982:             if ($key=~/^rolesdef\_(\w+)$/) {
 4983:                 my $rolename = $1;
 4984:                 my (%privs,$order);
 4985:                 ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 4986:                 $customroles{$rolename} = \%privs;
 4987:                 if (ref($current{$rolename}) eq 'HASH') {
 4988:                     $order = $current{$rolename}{'order'};
 4989:                 }
 4990:                 if ($order eq '') {
 4991:                     $order = $count;
 4992:                 }
 4993:                 $ordered{$order} = $rolename;
 4994:                 $count++;
 4995:             }
 4996:         }
 4997:         my $maxnum = scalar(keys(%ordered));
 4998:         my @roles_by_num = ();
 4999:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5000:             push(@roles_by_num,$item);
 5001:         }
 5002:         my $context = 'domprefs';
 5003:         my $crstype = 'Course';
 5004:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 5005:         my @accesstypes = ('all','dh','da','none');
 5006:         my ($numstatustypes,@jsarray);
 5007:         if (ref($types) eq 'ARRAY') {
 5008:             if (@{$types} > 0) {
 5009:                 $numstatustypes = scalar(@{$types});
 5010:                 push(@accesstypes,'status');
 5011:                 @jsarray = ('bystatus');
 5012:             }
 5013:         }
 5014:         my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh','da']);
 5015:         if (keys(%domhelpdesk)) {
 5016:             push(@accesstypes,('inc','exc'));
 5017:             push(@jsarray,('notinc','notexc'));
 5018:         }
 5019:         my $hiddenstr = join("','",@jsarray);
 5020:         my $context = 'domprefs';
 5021:         my $crstype = 'Course';
 5022:         my $prefix = 'helproles_';
 5023:         my $add_class = 'LC_hidden';
 5024:         foreach my $num (@roles_by_num) {
 5025:             my $role = $ordered{$num};
 5026:             my ($desc,$access,@statuses);
 5027:             if (ref($current{$role}) eq 'HASH') {
 5028:                 $desc = $current{$role}{'desc'};
 5029:                 $access = $current{$role}{'access'};
 5030:                 if (ref($current{$role}{'insttypes'}) eq 'ARRAY') {
 5031:                     @statuses = @{$current{$role}{'insttypes'}};
 5032:                 }
 5033:             }
 5034:             if ($desc eq '') {
 5035:                 $desc = $role;
 5036:             }
 5037:             my $identifier = 'custhelp'.$num;
 5038:             my %full=();
 5039:             my %levels= (
 5040:                          course => {},
 5041:                          domain => {},
 5042:                          system => {},
 5043:                         );
 5044:             my %levelscurrent=(
 5045:                                course => {},
 5046:                                domain => {},
 5047:                                system => {},
 5048:                               );
 5049:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 5050:             my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 5051:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5052:             my $chgstr = ' onchange="javascript:reorderHelpRoles(this.form,'."'helproles_".$num."_pos'".');"';
 5053:             $datatable .= '<tr '.$css_class.'><td style="vertical-align: top"><b>'.$role.'</b><br />'.
 5054:                           '<select name="helproles_'.$num.'_pos"'.$chgstr.'>';
 5055:             for (my $k=0; $k<=$maxnum; $k++) {
 5056:                 my $vpos = $k+1;
 5057:                 my $selstr;
 5058:                 if ($k == $num) {
 5059:                     $selstr = ' selected="selected" ';
 5060:                 }
 5061:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5062:             }
 5063:             $datatable .= '</select>'.('&nbsp;'x2).
 5064:                           '<input type="hidden" name="helproles_'.$num.'" value="'.$role.'" />'.
 5065:                           '</td>'.
 5066:                           '<td><fieldset><legend>'.&mt('Role name').'</legend>'.
 5067:                           &mt('Name shown to users:').
 5068:                           '<input type="text" name="helproles_'.$num.'_desc" value="'.$desc.'" />'.
 5069:                           '</fieldset>'.
 5070:                           &helpdeskroles_access($dom,$prefix,$num,$add_class,$current{$role},\@accesstypes,
 5071:                                                 $othertitle,$usertypes,$types,\%domhelpdesk).
 5072:                           '<fieldset>'.
 5073:                           '<legend>'.&mt('Role privileges').&adhocbutton($prefix,$num,'privs','show').'</legend>'.
 5074:                           &Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 5075:                                                                    \%levelscurrent,$identifier,
 5076:                                                                    'LC_hidden',$prefix.$num.'_privs').
 5077:                           '</fieldset></td>';
 5078:             $itemcount ++;
 5079:         }
 5080:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5081:         my $newcust = 'custhelp'.$count;
 5082:         my (%privs,%levelscurrent);
 5083:         my %full=();
 5084:         my %levels= (
 5085:                      course => {},
 5086:                      domain => {},
 5087:                      system => {},
 5088:                     );
 5089:         &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 5090:         my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 5091:         my $chgstr = ' onchange="javascript:reorderHelpRoles(this.form,'."'helproles_".$count."_pos'".');"';
 5092:         $datatable .= '<tr '.$css_class.'><td style="vertical-align: top"><span class="LC_nobreak"><label>'.
 5093:                       '<input type="hidden" name="helproles_maxnum" value="'.$maxnum.'" />'."\n".
 5094:                       '<select name="helproles_'.$count.'_pos"'.$chgstr.'>';
 5095:         for (my $k=0; $k<$maxnum+1; $k++) {
 5096:             my $vpos = $k+1;
 5097:             my $selstr;
 5098:             if ($k == $maxnum) {
 5099:                 $selstr = ' selected="selected" ';
 5100:             }
 5101:             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5102:         }
 5103:         $datatable .= '</select>&nbsp;'."\n".
 5104:                       '<input type="checkbox" name="newcusthelp" value="'.$count.'" />'. &mt('Add').
 5105:                       '</label></span></td>'.
 5106:                       '<td><fieldset><legend>'.&mt('Role name').'</legend>'.
 5107:                       '<span class="LC_nobreak">'.
 5108:                       &mt('Internal name:').
 5109:                       '<input type="text" size="10" name="custhelpname'.$count.'" value="" />'.
 5110:                       '</span>'.('&nbsp;'x4).
 5111:                       '<span class="LC_nobreak">'.
 5112:                       &mt('Name shown to users:').
 5113:                       '<input type="text" size="20" name="helproles_'.$count.'_desc" value="" />'.
 5114:                       '</span></fieldset>'.
 5115:                        &helpdeskroles_access($dom,$prefix,$count,'',undef,\@accesstypes,$othertitle,
 5116:                                              $usertypes,$types,\%domhelpdesk).
 5117:                       '<fieldset><legend>'.&mt('Role privileges').'</legend>'.
 5118:                       &Apache::lonuserutils::custom_role_header($context,$crstype,
 5119:                                                                 \@templateroles,$newcust).
 5120:                       &Apache::lonuserutils::custom_role_table('Course',\%full,\%levels,
 5121:                                                                \%levelscurrent,$newcust).
 5122:                       '</fieldset>'.
 5123:                       &helpsettings_javascript(\@roles_by_num,$maxnum,$hiddenstr,$formname).
 5124:                       '</td></tr>';
 5125:         $count ++;
 5126:         $$rowtotal += $count;
 5127:     }
 5128:     return $datatable;
 5129: }
 5130: 
 5131: sub adhocbutton {
 5132:     my ($prefix,$num,$field,$visibility) = @_;
 5133:     my %lt = &Apache::lonlocal::texthash(
 5134:                                           show => 'Show details',
 5135:                                           hide => 'Hide details',
 5136:                                         );
 5137:     return '<span style="text-decoration:line-through; font-weight: normal;">'.('&nbsp;'x10).
 5138:            '</span>'.('&nbsp;'x2).'<input type="button" id="'.$prefix.$num.'_'.$field.'_vis"'.
 5139:            ' value="'.$lt{$visibility}.'" style="height:20px;" '.
 5140:            'onclick="toggleHelpdeskItem('."'$num','$field'".');" />'.('&nbsp;'x2);
 5141: }
 5142: 
 5143: sub helpsettings_javascript {
 5144:     my ($roles_by_num,$total,$hiddenstr,$formname) = @_;
 5145:     return unless(ref($roles_by_num) eq 'ARRAY');
 5146:     my %html_js_lt = &Apache::lonlocal::texthash(
 5147:                                           show => 'Show details',
 5148:                                           hide => 'Hide details',
 5149:                                         );
 5150:     &html_escape(\%html_js_lt);
 5151:     my $jstext = '    var helproles = Array('."'".join("','",@{$roles_by_num})."'".');'."\n";
 5152:     return <<"ENDSCRIPT";
 5153: <script type="text/javascript">
 5154: // <![CDATA[
 5155: 
 5156: function reorderHelpRoles(form,item) {
 5157:     var changedVal;
 5158: $jstext
 5159:     var newpos = 'helproles_${total}_pos';
 5160:     var maxh = 1 + $total;
 5161:     var current = new Array();
 5162:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 5163:     if (item == newpos) {
 5164:         changedVal = newitemVal;
 5165:     } else {
 5166:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 5167:         current[newitemVal] = newpos;
 5168:     }
 5169:     for (var i=0; i<helproles.length; i++) {
 5170:         var elementName = 'helproles_'+helproles[i]+'_pos';
 5171:         if (elementName != item) {
 5172:             if (form.elements[elementName]) {
 5173:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 5174:                 current[currVal] = elementName;
 5175:             }
 5176:         }
 5177:     }
 5178:     var oldVal;
 5179:     for (var j=0; j<maxh; j++) {
 5180:         if (current[j] == undefined) {
 5181:             oldVal = j;
 5182:         }
 5183:     }
 5184:     if (oldVal < changedVal) {
 5185:         for (var k=oldVal+1; k<=changedVal ; k++) {
 5186:            var elementName = current[k];
 5187:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 5188:         }
 5189:     } else {
 5190:         for (var k=changedVal; k<oldVal; k++) {
 5191:             var elementName = current[k];
 5192:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 5193:         }
 5194:     }
 5195:     return;
 5196: }
 5197: 
 5198: function helpdeskAccess(num) {
 5199:     var curraccess = null;
 5200:     if (document.$formname.elements['helproles_'+num+'_access'].length) {
 5201:         for (var i=0; i<document.$formname.elements['helproles_'+num+'_access'].length; i++) {
 5202:             if (document.$formname.elements['helproles_'+num+'_access'][i].checked) {
 5203:                 curraccess = document.$formname.elements['helproles_'+num+'_access'][i].value;
 5204:             }
 5205:         }
 5206:     }
 5207:     var shown = Array();
 5208:     var hidden = Array();
 5209:     if (curraccess == 'none') {
 5210:         hidden = Array('$hiddenstr');
 5211:     } else {
 5212:         if (curraccess == 'status') {
 5213:             shown = Array('bystatus');
 5214:             hidden = Array('notinc','notexc');
 5215:         } else {
 5216:             if (curraccess == 'exc') {
 5217:                 shown = Array('notexc');
 5218:                 hidden = Array('notinc','bystatus');
 5219:             }
 5220:             if (curraccess == 'inc') {
 5221:                 shown = Array('notinc');
 5222:                 hidden = Array('notexc','bystatus');
 5223:             }
 5224:             if ((curraccess == 'all') || (curraccess == 'dh') || (curraccess == 'da')) {
 5225:                 hidden = Array('notinc','notexc','bystatus');
 5226:             }
 5227:         }
 5228:     }
 5229:     if (hidden.length > 0) {
 5230:         for (var i=0; i<hidden.length; i++) {
 5231:             if (document.getElementById('helproles_'+num+'_'+hidden[i])) {
 5232:                 document.getElementById('helproles_'+num+'_'+hidden[i]).style.display = 'none';
 5233:             }
 5234:         }
 5235:     }
 5236:     if (shown.length > 0) {
 5237:         for (var i=0; i<shown.length; i++) {
 5238:             if (document.getElementById('helproles_'+num+'_'+shown[i])) {
 5239:                 if (shown[i] == 'privs') {
 5240:                     document.getElementById('helproles_'+num+'_'+shown[i]).style.display = 'block';
 5241:                 } else {
 5242:                     document.getElementById('helproles_'+num+'_'+shown[i]).style.display = 'inline-block';
 5243:                 }
 5244:             }
 5245:         }
 5246:     }
 5247:     return;
 5248: }
 5249: 
 5250: function toggleHelpdeskItem(num,field) {
 5251:     if (document.getElementById('helproles_'+num+'_'+field)) {
 5252:         if (document.getElementById('helproles_'+num+'_'+field).className.match(/(?:^|\\s)LC_hidden(?!\\S)/)) {
 5253:             document.getElementById('helproles_'+num+'_'+field).className =
 5254:                 document.getElementById('helproles_'+num+'_'+field).className.replace(/(?:^|\\s)LC_hidden(?!\\S)/g ,'');
 5255:             if (document.getElementById('helproles_'+num+'_'+field+'_vis')) {
 5256:                 document.getElementById('helproles_'+num+'_'+field+'_vis').value = '$html_js_lt{hide}';
 5257:             }
 5258:         } else {
 5259:             document.getElementById('helproles_'+num+'_'+field).className += ' LC_hidden';
 5260:             if (document.getElementById('helproles_'+num+'_'+field+'_vis')) {
 5261:                 document.getElementById('helproles_'+num+'_'+field+'_vis').value = '$html_js_lt{show}';
 5262:             }
 5263:         }
 5264:     }
 5265:     return;
 5266: }
 5267: 
 5268: // ]]>
 5269: </script>
 5270: 
 5271: ENDSCRIPT
 5272: }
 5273: 
 5274: sub helpdeskroles_access {
 5275:     my ($dom,$prefix,$num,$add_class,$current,$accesstypes,$othertitle,
 5276:         $usertypes,$types,$domhelpdesk) = @_;
 5277:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($domhelpdesk) eq 'HASH'));
 5278:     my %lt = &Apache::lonlocal::texthash(
 5279:                     'rou'    => 'Role usage',
 5280:                     'whi'    => 'Which helpdesk personnel may use this role?',
 5281:                     'all'    => 'All with domain helpdesk or helpdesk assistant role',
 5282:                     'dh'     => 'All with domain helpdesk role',
 5283:                     'da'     => 'All with domain helpdesk assistant role',
 5284:                     'none'   => 'None',
 5285:                     'status' => 'Determined based on institutional status',
 5286:                     'inc'    => 'Include all, but exclude specific personnel',
 5287:                     'exc'    => 'Exclude all, but include specific personnel',
 5288:                   );
 5289:     my %usecheck = (
 5290:                      all => ' checked="checked"',
 5291:                    );
 5292:     my %displaydiv = (
 5293:                       status => 'none',
 5294:                       inc    => 'none',
 5295:                       exc    => 'none',
 5296:                       priv   => 'block',
 5297:                      );
 5298:     my $output;
 5299:     if (ref($current) eq 'HASH') {
 5300:         if (($current->{'access'} ne '') && ($current->{'access'} ne 'all')) {
 5301:             if (grep(/^\Q$current->{access}\E$/,@{$accesstypes})) {
 5302:                 $usecheck{$current->{access}} = $usecheck{'all'};
 5303:                 delete($usecheck{'all'});
 5304:                 if ($current->{access} =~ /^(status|inc|exc)$/) {
 5305:                     my $access = $1;
 5306:                     $displaydiv{$access} = 'inline';
 5307:                 } elsif ($current->{access} eq 'none') {
 5308:                     $displaydiv{'priv'} = 'none';
 5309:                 }
 5310:             }
 5311:         }
 5312:     }
 5313:     $output = '<fieldset id="'.$prefix.$num.'_usage"><legend>'.$lt{'rou'}.'</legend>'.
 5314:               '<p>'.$lt{'whi'}.'</p>';
 5315:     foreach my $access (@{$accesstypes}) {
 5316:         $output .= '<p><label><input type="radio" name="'.$prefix.$num.'_access" value="'.$access.'" '.$usecheck{$access}.
 5317:                    ' onclick="helpdeskAccess('."'$num'".');" />'.
 5318:                    $lt{$access}.'</label>';
 5319:         if ($access eq 'status') {
 5320:             $output .= '<div id="'.$prefix.$num.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 5321:                        &Apache::lonuserutils::adhoc_status_types($dom,$prefix,$num,$current->{$access},
 5322:                                                                  $othertitle,$usertypes,$types).
 5323:                        '</div>';
 5324:         } elsif (($access eq 'inc') && (keys(%{$domhelpdesk}) > 0)) {
 5325:             $output .= '<div id="'.$prefix.$num.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 5326:                        &Apache::lonuserutils::adhoc_staff($access,$prefix,$num,$current->{$access},$domhelpdesk).
 5327:                        '</div>';
 5328:         } elsif (($access eq 'exc') && (keys(%{$domhelpdesk}) > 0)) {
 5329:             $output .= '<div id="'.$prefix.$num.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 5330:                        &Apache::lonuserutils::adhoc_staff($access,$prefix,$num,$current->{$access},$domhelpdesk).
 5331:                        '</div>';
 5332:         }
 5333:         $output .= '</p>';
 5334:     }
 5335:     $output .= '</fieldset>';
 5336:     return $output;
 5337: }
 5338: 
 5339: sub radiobutton_prefs {
 5340:     my ($settings,$toggles,$defaultchecked,$choices,$itemcount,$onclick,
 5341:         $additional,$align,$firstval) = @_;
 5342:     return unless ((ref($toggles) eq 'ARRAY') && (ref($defaultchecked) eq 'HASH') &&
 5343:                    (ref($choices) eq 'HASH'));
 5344: 
 5345:     my (%checkedon,%checkedoff,$datatable,$css_class);
 5346: 
 5347:     foreach my $item (@{$toggles}) {
 5348:         if ($defaultchecked->{$item} eq 'on') {
 5349:             $checkedon{$item} = ' checked="checked" ';
 5350:             $checkedoff{$item} = ' ';
 5351:         } elsif ($defaultchecked->{$item} eq 'off') {
 5352:             $checkedoff{$item} = ' checked="checked" ';
 5353:             $checkedon{$item} = ' ';
 5354:         }
 5355:     }
 5356:     if (ref($settings) eq 'HASH') {
 5357:         foreach my $item (@{$toggles}) {
 5358:             if ($settings->{$item} eq '1') {
 5359:                 $checkedon{$item} =  ' checked="checked" ';
 5360:                 $checkedoff{$item} = ' ';
 5361:             } elsif ($settings->{$item} eq '0') {
 5362:                 $checkedoff{$item} =  ' checked="checked" ';
 5363:                 $checkedon{$item} = ' ';
 5364:             }
 5365:         }
 5366:     }
 5367:     if ($onclick) {
 5368:         $onclick = ' onclick="'.$onclick.'"';
 5369:     }
 5370:     foreach my $item (@{$toggles}) {
 5371:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5372:         $datatable .=
 5373:             '<tr'.$css_class.'><td style="vertical-align: top">'.
 5374:             '<span class="LC_nobreak">'.$choices->{$item}.
 5375:             '</span></td>';
 5376:         if ($align eq 'left') {
 5377:             $datatable .= '<td class="LC_left_item">';
 5378:         } else {
 5379:             $datatable .= '<td class="LC_right_item">';
 5380:         }
 5381:         $datatable .= '<span class="LC_nobreak">';
 5382:         if ($firstval eq 'no') {
 5383:             $datatable .=
 5384:                 '<label><input type="radio" name="'.
 5385:                 $item.'" '.$checkedoff{$item}.' value="0"'.$onclick.' />'.&mt('No').
 5386:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'" '.
 5387:                 $checkedon{$item}.' value="1"'.$onclick.' />'.&mt('Yes').'</label>';
 5388:         } else {
 5389:             $datatable .=
 5390:                 '<label><input type="radio" name="'.
 5391:                 $item.'" '.$checkedon{$item}.' value="1"'.$onclick.' />'.&mt('Yes').
 5392:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'" '.
 5393:                 $checkedoff{$item}.' value="0"'.$onclick.' />'.&mt('No').'</label>';
 5394:         }
 5395:         $datatable .= '</span>'.$additional.'</td></tr>';
 5396:         $itemcount ++;
 5397:     }
 5398:     return ($datatable,$itemcount);
 5399: }
 5400: 
 5401: sub print_ltitools {
 5402:     my ($dom,$settings,$rowtotal) = @_;
 5403:     my $rownum = 0;
 5404:     my $css_class;
 5405:     my $itemcount = 1;
 5406:     my $maxnum = 0;
 5407:     my %ordered;
 5408:     if (ref($settings) eq 'HASH') {
 5409:         foreach my $item (keys(%{$settings})) {
 5410:             if (ref($settings->{$item}) eq 'HASH') {
 5411:                 my $num = $settings->{$item}{'order'};
 5412:                 $ordered{$num} = $item;
 5413:             }
 5414:         }
 5415:     }
 5416:     my $confname = $dom.'-domainconfig';
 5417:     my $switchserver = &check_switchserver($dom,$confname);
 5418:     my $maxnum = scalar(keys(%ordered));
 5419:     my $datatable;
 5420:     my %lt = &ltitools_names();
 5421:     my @courseroles = ('cc','in','ta','ep','st');
 5422:     my @ltiroles = qw(Instructor ContentDeveloper TeachingAssistant Learner);
 5423:     my @fields = ('fullname','firstname','lastname','email','roles','user');
 5424:     if (keys(%ordered)) {
 5425:         my @items = sort { $a <=> $b } keys(%ordered);
 5426:         for (my $i=0; $i<@items; $i++) {
 5427:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5428:             my $item = $ordered{$items[$i]};
 5429:             my ($title,$key,$secret,$url,$lifetime,$imgsrc,%sigsel);
 5430:             if (ref($settings->{$item}) eq 'HASH') {
 5431:                 $title = $settings->{$item}->{'title'};
 5432:                 $url = $settings->{$item}->{'url'};
 5433:                 $key = $settings->{$item}->{'key'};
 5434:                 $secret = $settings->{$item}->{'secret'};
 5435:                 $lifetime = $settings->{$item}->{'lifetime'};
 5436:                 my $image = $settings->{$item}->{'image'};
 5437:                 if ($image ne '') {
 5438:                     $imgsrc = '<img src="'.$image.'" alt="'.&mt('Tool Provider icon').'" />';
 5439:                 }
 5440:                 if ($settings->{$item}->{'sigmethod'} eq 'HMAC-256') {
 5441:                     $sigsel{'HMAC-256'} = ' selected="selected"';
 5442:                 } else {
 5443:                     $sigsel{'HMAC-SHA1'} = ' selected="selected"';
 5444:                 }
 5445:             }
 5446:             my $chgstr = ' onchange="javascript:reorderLTITools(this.form,'."'ltitools_".$item."'".');"';
 5447:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 5448:                          .'<select name="ltitools_'.$item.'"'.$chgstr.'>';
 5449:             for (my $k=0; $k<=$maxnum; $k++) {
 5450:                 my $vpos = $k+1;
 5451:                 my $selstr;
 5452:                 if ($k == $i) {
 5453:                     $selstr = ' selected="selected" ';
 5454:                 }
 5455:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5456:             }
 5457:             $datatable .= '</select>'.('&nbsp;'x2).
 5458:                 '<label><input type="checkbox" name="ltitools_del" value="'.$item.'" />'.
 5459:                 &mt('Delete?').'</label></span></td>'.
 5460:                 '<td colspan="2">'.
 5461:                 '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 5462:                 '<span class="LC_nobreak">'.$lt{'title'}.':<input type="text" size="20" name="ltitools_title_'.$i.'" value="'.$title.'" /></span> '.
 5463:                 ('&nbsp;'x2).
 5464:                 '<span class="LC_nobreak">'.$lt{'version'}.':<select name="ltitools_version_'.$i.'">'.
 5465:                 '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '.
 5466:                 ('&nbsp;'x2).
 5467:                 '<span class="LC_nobreak">'.$lt{'msgtype'}.':<select name="ltitools_msgtype_'.$i.'">'.
 5468:                 '<option value="basic-lti-launch-request" selected="selected">Launch</option></select></span> '.
 5469:                 ('&nbsp;'x2).
 5470:                 '<span class="LC_nobreak">'.$lt{'sigmethod'}.':<select name="ltitools_sigmethod_'.$i.'">'.
 5471:                 '<option value="HMAC-SHA1"'.$sigsel{'HMAC-SHA1'}.'>HMAC-SHA1</option>'.
 5472:                 '<option value="HMAC-SHA256"'.$sigsel{'HMAC-SHA256'}.'>HMAC-SHA256</option></select></span>'.
 5473:                 '<br /><br />'.
 5474:                 '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="40" name="ltitools_url_'.$i.'"'.
 5475:                 ' value="'.$url.'" /></span>'.
 5476:                 ('&nbsp;'x2).
 5477:                 '<span class="LC_nobreak">'.$lt{'key'}.':'.
 5478:                 '<input type="text" size="25" name="ltitools_key_'.$i.'" value="'.$key.'" /></span> '.
 5479:                 ('&nbsp;'x2).
 5480:                 '<span class="LC_nobreak">'.$lt{'lifetime'}.':'.
 5481:                 '<input type="text" size="5" name="ltitools_lifetime_'.$i.'" value="'.$lifetime.'" /></span> '.
 5482:                 ('&nbsp;'x2).
 5483:                 '<span class="LC_nobreak">'.$lt{'secret'}.':'.
 5484:                 '<input type="password" size="20" name="ltitools_secret_'.$i.'" value="'.$secret.'" />'.
 5485:                 '<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>'.
 5486:                 '<input type="hidden" name="ltitools_id_'.$i.'" value="'.$item.'" /></span>'.
 5487:                 '</fieldset>'.
 5488:                 '<fieldset><legend>'.&mt('Optional settings').'</legend>'.
 5489:                 '<span class="LC_nobreak">'.&mt('Display target:');
 5490:             my %currdisp;
 5491:             if (ref($settings->{$item}->{'display'}) eq 'HASH') {
 5492:                 if ($settings->{$item}->{'display'}->{'target'} eq 'window') {
 5493:                     $currdisp{'window'} = ' checked="checked"';
 5494:                 } elsif ($settings->{$item}->{'display'}->{'target'} eq 'tab') {
 5495:                     $currdisp{'tab'} = ' checked="checked"';
 5496:                 } else {
 5497:                     $currdisp{'iframe'} = ' checked="checked"';
 5498:                 }
 5499:                 if ($settings->{$item}->{'display'}->{'width'} =~ /^(\d+)$/) {
 5500:                     $currdisp{'width'} = $1;
 5501:                 }
 5502:                 if ($settings->{$item}->{'display'}->{'height'} =~ /^(\d+)$/) {
 5503:                      $currdisp{'height'} = $1;
 5504:                 }
 5505:                 $currdisp{'linktext'} = $settings->{$item}->{'display'}->{'linktext'};
 5506:                 $currdisp{'explanation'} = $settings->{$item}->{'display'}->{'explanation'};
 5507:             } else {
 5508:                 $currdisp{'iframe'} = ' checked="checked"';
 5509:             }
 5510:             foreach my $disp ('iframe','tab','window') {
 5511:                 $datatable .= '<label><input type="radio" name="ltitools_target_'.$i.'" value="'.$disp.'"'.$currdisp{$disp}.' />'.
 5512:                               $lt{$disp}.'</label>'.('&nbsp;'x2);
 5513:             }
 5514:             $datatable .= ('&nbsp;'x4);
 5515:             foreach my $dimen ('width','height') {
 5516:                 $datatable .= '<label>'.$lt{$dimen}.'&nbsp;'.
 5517:                               '<input type="text" name="ltitools_'.$dimen.'_'.$i.'" size="5" value="'.$currdisp{$dimen}.'" /></label>'.
 5518:                               ('&nbsp;'x2);
 5519:             }
 5520:             $datatable .= '</span><br />'.
 5521:                           '<div class="LC_left_float">'.$lt{'linktext'}.'<br />'.
 5522:                           '<input type="text" name="ltitools_linktext_'.$i.'" size="25" value="'.$currdisp{'linktext'}.'" /></div>'.
 5523:                           '<div class="LC_left_float">'.$lt{'explanation'}.'<br />'.
 5524:                           '<textarea name="ltitools_explanation_'.$i.'" rows="5" cols="40">'.$currdisp{'explanation'}.
 5525:                           '</textarea></div><div style=""></div><br />';
 5526:             my %units = (
 5527:                           'passback' => 'days',
 5528:                           'roster'   => 'seconds',
 5529:                         );
 5530:             foreach my $extra ('passback','roster') {
 5531:                 my $validsty = 'none';
 5532:                 my $currvalid;
 5533:                 my $checkedon = '';
 5534:                 my $checkedoff = ' checked="checked"';
 5535:                 if ($settings->{$item}->{$extra}) {
 5536:                     $checkedon = $checkedoff;
 5537:                     $checkedoff = '';
 5538:                     $validsty = 'inline-block';
 5539:                     if ($settings->{$item}->{$extra.'valid'} =~ /^\d+\.?\d*$/) {
 5540:                         $currvalid = $settings->{$item}->{$extra.'valid'};
 5541:                     }
 5542:                 }
 5543:                 my $onclick = ' onclick="toggleLTITools(this.form,'."'$extra','$i'".');"';
 5544:                 $datatable .= '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{$extra}.'&nbsp;'.
 5545:                               '<label><input type="radio" name="ltitools_'.$extra.'_'.$i.'" value="0"'.$checkedoff.$onclick.' />'.
 5546:                               &mt('No').'</label>'.('&nbsp;'x2).
 5547:                               '<label><input type="radio" name="ltitools_'.$extra.'_'.$i.'" value="1"'.$checkedon.$onclick.' />'.
 5548:                               &mt('Yes').'</label></span></div>'.
 5549:                               '<div class="LC_floatleft" style="display:'.$validsty.';" id="ltitools_'.$extra.'time_'.$i.'">'.
 5550:                               '<span class="LC_nobreak">'.
 5551:                               &mt("at least [_1] $units{$extra} after launch",
 5552:                                   '<input type="text" name="ltitools_'.$extra.'valid_'.$i.'" value="'.$currvalid.'" />').
 5553:                               '</span></div><div style="padding:0;clear:both;margin:0;border:0"></div>';
 5554:             }
 5555:             $datatable .= '<span class="LC_nobreak">'.$lt{'icon'}.':&nbsp;';
 5556:             if ($imgsrc) {
 5557:                 $datatable .= $imgsrc.
 5558:                               '<label><input type="checkbox" name="ltitools_image_del"'.
 5559:                               ' value="'.$item.'" />'.&mt('Delete?').'</label></span> '.
 5560:                               '<span class="LC_nobreak">&nbsp;'.&mt('Replace:').'&nbsp;';
 5561:             } else {
 5562:                 $datatable .= '('.&mt('if larger than 21x21 pixels, image will be scaled').')&nbsp;';
 5563:             }
 5564:             if ($switchserver) {
 5565:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 5566:             } else {
 5567:                 $datatable .= '<input type="file" name="ltitools_image_'.$i.'" value="" />';
 5568:             }
 5569:             $datatable .= '</span></fieldset>';
 5570:             my (%checkedfields,%rolemaps,$userincdom);
 5571:             if (ref($settings->{$item}) eq 'HASH') {
 5572:                 if (ref($settings->{$item}->{'fields'}) eq 'HASH') {
 5573:                     %checkedfields = %{$settings->{$item}->{'fields'}};
 5574:                 }
 5575:                 $userincdom = $settings->{$item}->{'incdom'};
 5576:                 if (ref($settings->{$item}->{'roles'}) eq 'HASH') {
 5577:                     %rolemaps = %{$settings->{$item}->{'roles'}};
 5578:                     $checkedfields{'roles'} = 1;
 5579:                 }
 5580:             }
 5581:             $datatable .= '<fieldset><legend>'.&mt('User data sent on launch').'</legend>'.
 5582:                           '<span class="LC_nobreak">';
 5583:             my $userfieldstyle = 'display:none;';
 5584:             my $seluserdom = '';
 5585:             my $unseluserdom = ' selected="selected"';
 5586:             foreach my $field (@fields) {
 5587:                 my ($checked,$onclick,$id,$spacer);
 5588:                 if ($checkedfields{$field}) {
 5589:                     $checked = ' checked="checked"';
 5590:                 }
 5591:                 if ($field eq 'user') {
 5592:                     $id = ' id="ltitools_user_field_'.$i.'"';
 5593:                     $onclick = ' onclick="toggleLTITools(this.form,'."'$field','$i'".')"';
 5594:                     if ($checked) {
 5595:                         $userfieldstyle = 'display:inline-block';
 5596:                         if ($userincdom) {
 5597:                             $seluserdom = $unseluserdom;
 5598:                             $unseluserdom = '';
 5599:                         }
 5600:                     }
 5601:                 } else {
 5602:                     $spacer = ('&nbsp;' x2);
 5603:                 }
 5604:                 $datatable .= '<label>'.
 5605:                               '<input type="checkbox" name="ltitools_fields_'.$i.'" value="'.$field.'"'.$id.$checked.$onclick.' />'.
 5606:                               $lt{$field}.'</label>'.$spacer;
 5607:             }
 5608:             $datatable .= '</span>';
 5609:             $datatable .= '<div style="'.$userfieldstyle.'" id="ltitools_user_div_'.$i.'">'.
 5610:                           '<span class="LC_nobreak"> : '.
 5611:                           '<select name="ltitools_userincdom_'.$i.'">'.
 5612:                           '<option value="">'.&mt('Select').'</option>'.
 5613:                           '<option value="0"'.$unseluserdom.'>'.&mt('username').'</option>'.
 5614:                           '<option value="1"'.$seluserdom.'>'.&mt('username:domain').'</option>'.
 5615:                           '</select></span></div>';
 5616:             $datatable .= '</fieldset>'.
 5617:                           '<fieldset><legend>'.&mt('Role mapping').'</legend><table><tr>';
 5618:             foreach my $role (@courseroles) {
 5619:                 my ($selected,$selectnone);
 5620:                 if (!$rolemaps{$role}) {
 5621:                     $selectnone = ' selected="selected"';
 5622:                 }
 5623:                 $datatable .= '<td style="text-align: center">'. 
 5624:                               &Apache::lonnet::plaintext($role,'Course').'<br />'.
 5625:                               '<select name="ltitools_roles_'.$role.'_'.$i.'">'.
 5626:                               '<option value=""'.$selectnone.'>'.&mt('Select').'</option>';
 5627:                 foreach my $ltirole (@ltiroles) {
 5628:                     unless ($selectnone) {
 5629:                         if ($rolemaps{$role} eq $ltirole) {
 5630:                             $selected = ' selected="selected"';
 5631:                         } else {
 5632:                             $selected = '';
 5633:                         }
 5634:                     }
 5635:                     $datatable .= '<option value="'.$ltirole.'"'.$selected.'>'.$ltirole.'</option>';
 5636:                 }
 5637:                 $datatable .= '</select></td>';
 5638:             }
 5639:             $datatable .= '</tr></table></fieldset>';
 5640:             my %courseconfig;
 5641:             if (ref($settings->{$item}) eq 'HASH') {
 5642:                 if (ref($settings->{$item}->{'crsconf'}) eq 'HASH') {
 5643:                     %courseconfig = %{$settings->{$item}->{'crsconf'}};
 5644:                 }
 5645:             }
 5646:             $datatable .= '<fieldset><legend>'.&mt('Configurable in course').'</legend><span class="LC_nobreak">';
 5647:             foreach my $item ('label','title','target','linktext','explanation','append') {
 5648:                 my $checked;
 5649:                 if ($courseconfig{$item}) {
 5650:                     $checked = ' checked="checked"';
 5651:                 }
 5652:                 $datatable .= '<label>'.
 5653:                        '<input type="checkbox" name="ltitools_courseconfig_'.$i.'" value="'.$item.'"'.$checked.' />'.
 5654:                        $lt{'crs'.$item}.'</label>&nbsp; '."\n";
 5655:             }
 5656:             $datatable .= '</span></fieldset>'.
 5657:                           '<fieldset><legend>'.&mt('Custom items sent on launch').'</legend>'.
 5658:                           '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>';
 5659:             if (ref($settings->{$item}->{'custom'}) eq 'HASH') {
 5660:                 my %custom = %{$settings->{$item}->{'custom'}};
 5661:                 if (keys(%custom) > 0) {
 5662:                     foreach my $key (sort(keys(%custom))) {
 5663:                         $datatable .= '<tr><td><span class="LC_nobreak">'.
 5664:                                       '<label><input type="checkbox" name="ltitools_customdel_'.$i.'" value="'.
 5665:                                       $key.'" />'.&mt('Delete').'</label></span></td><td>'.$key.'</td>'.
 5666:                                       '<td><input type="text" name="ltitools_customval_'.$key.'_'.$i.'"'.
 5667:                                       ' value="'.$custom{$key}.'" /></td></tr>';
 5668:                     }
 5669:                 }
 5670:             }
 5671:             $datatable .= '<tr><td><span class="LC_nobreak">'.
 5672:                           '<label><input type="checkbox" name="ltitools_customadd" value="'.$i.'" />'.
 5673:                           &mt('Add').'</label></span></td><td><input type="text" name="ltitools_custom_name_'.$i.'" />'.
 5674:                           '</td><td><input type="text" name="ltitools_custom_value_'.$i.'" /></td></tr>';
 5675:             $datatable .= '</table></fieldset></td></tr>'."\n";
 5676:             $itemcount ++;
 5677:         }
 5678:     }
 5679:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5680:     my $chgstr = ' onchange="javascript:reorderLTITools(this.form,'."'ltitools_add_pos'".');"';
 5681:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 5682:                   '<input type="hidden" name="ltitools_maxnum" value="'.$maxnum.'" />'."\n".
 5683:                   '<select name="ltitools_add_pos"'.$chgstr.'>';
 5684:     for (my $k=0; $k<$maxnum+1; $k++) {
 5685:         my $vpos = $k+1;
 5686:         my $selstr;
 5687:         if ($k == $maxnum) {
 5688:             $selstr = ' selected="selected" ';
 5689:         }
 5690:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5691:     }
 5692:     $datatable .= '</select>&nbsp;'."\n".
 5693:                   '<input type="checkbox" name="ltitools_add" value="1" />'.&mt('Add').'</span></td>'."\n".
 5694:                   '<td colspan="2">'.
 5695:                   '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 5696:                   '<span class="LC_nobreak">'.$lt{'title'}.':<input type="text" size="20" name="ltitools_add_title" value="" /></span> '."\n".
 5697:                   ('&nbsp;'x2).
 5698:                   '<span class="LC_nobreak">'.$lt{'version'}.':<select name="ltitools_add_version">'.
 5699:                   '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '."\n".
 5700:                   ('&nbsp;'x2).
 5701:                   '<span class="LC_nobreak">'.$lt{'msgtype'}.':<select name="ltitools_add_msgtype">'.
 5702:                   '<option value="basic-lti-launch-request" selected="selected">Launch</option></select></span> '.
 5703:                   '<span class="LC_nobreak">'.$lt{'sigmethod'}.':<select name="ltitools_add_sigmethod">'.
 5704:                   '<option value="HMAC-SHA1" selected="selected">HMAC-SHA1</option>'.
 5705:                   '<option value="HMAC-SHA256">HMAC-SHA256</option></select></span>'.
 5706:                   '<br />'.
 5707:                   '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="40" name="ltitools_add_url" value="" /></span> '."\n".
 5708:                   ('&nbsp;'x2).
 5709:                   '<span class="LC_nobreak">'.$lt{'key'}.':<input type="text" size="25" name="ltitools_add_key" value="" /></span> '."\n".
 5710:                   ('&nbsp;'x2).
 5711:                   '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" size="5" name="ltitools_add_lifetime" value="300" /></span> '."\n".
 5712:                   ('&nbsp;'x2).
 5713:                   '<span class="LC_nobreak">'.$lt{'secret'}.':<input type="password" size="20" name="ltitools_add_secret" value="" />'.
 5714:                   '<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".
 5715:                   '</fieldset>'.
 5716:                   '<fieldset><legend>'.&mt('Optional settings').'</legend>'.
 5717:                   '<span class="LC_nobreak">'.&mt('Display target:');
 5718:     my %defaultdisp;
 5719:     $defaultdisp{'iframe'} = ' checked="checked"';
 5720:     foreach my $disp ('iframe','tab','window') {
 5721:         $datatable .= '<label><input type="radio" name="ltitools_add_target" value="'.$disp.'"'.$defaultdisp{$disp}.' />'.
 5722:                       $lt{$disp}.'</label>'.('&nbsp;'x2);
 5723:     }
 5724:     $datatable .= ('&nbsp;'x4);
 5725:     foreach my $dimen ('width','height') {
 5726:         $datatable .= '<label>'.$lt{$dimen}.'&nbsp;'.
 5727:                       '<input type="text" name="ltitools_add_'.$dimen.'" size="5" /></label>'.
 5728:                       ('&nbsp;'x2);
 5729:     }
 5730:     $datatable .= '</span><br />'.
 5731:                   '<div class="LC_left_float">'.$lt{'linktext'}.'<br />'.
 5732:                   '<input type="text" name="ltitools_add_linktext" size="5" /></div>'.
 5733:                   '<div class="LC_left_float">'.$lt{'explanation'}.'<br />'.
 5734:                   '<textarea name="ltitools_add_explanation" rows="5" cols="40"></textarea>'.
 5735:                   '</div><div style=""></div><br />';
 5736:     my %units = (
 5737:                   'passback' => 'days',
 5738:                   'roster'   => 'seconds',
 5739:                 );
 5740:     my %defaulttimes = (
 5741:                      'passback' => '7',
 5742:                      'roster'   => '300',
 5743:                    );
 5744:     foreach my $extra ('passback','roster') {
 5745:         my $onclick = ' onclick="toggleLTITools(this.form,'."'$extra','add'".');"';
 5746:         $datatable .= '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{$extra}.'&nbsp;'.
 5747:                       '<label><input type="radio" name="ltitools_'.$extra.'_add" value="0" checked="checked"'.$onclick.' />'.
 5748:                       &mt('No').'</label></span>'.('&nbsp;'x2).'<span class="LC_nobreak">'.
 5749:                       '<label><input type="radio" name="ltitools_'.$extra.'_add" value="1"'.$onclick.' />'.
 5750:                       &mt('Yes').'</label></span></div>'.
 5751:                       '<div class="LC_floatleft" style="display:none;" id="ltitools_'.$extra.'time_add">'.
 5752:                       '<span class="LC_nobreak">'.
 5753:                       &mt("at least [_1] $units{$extra} after launch",
 5754:                           '<input type="text" name="ltitools_'.$extra.'valid_add" value="'.$defaulttimes{$extra}.'" />').
 5755:                       '</span></div><div style="padding:0;clear:both;margin:0;border:0"></div>';
 5756:     }
 5757:     $datatable .= '<span class="LC_nobreak">'.$lt{'icon'}.':&nbsp;'.
 5758:                   '('.&mt('if larger than 21x21 pixels, image will be scaled').')&nbsp;';
 5759:     if ($switchserver) {
 5760:         $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 5761:     } else {
 5762:         $datatable .= '<input type="file" name="ltitools_add_image" value="" />';
 5763:     }
 5764:     $datatable .= '</span></fieldset>'.
 5765:                   '<fieldset><legend>'.&mt('User data sent on launch').'</legend>'.
 5766:                   '<span class="LC_nobreak">';
 5767:     foreach my $field (@fields) {
 5768:         my ($id,$onclick,$spacer);
 5769:         if ($field eq 'user') {
 5770:             $id = ' id="ltitools_user_field_add"';
 5771:             $onclick = ' onclick="toggleLTITools(this.form,'."'$field','add'".')"';
 5772:         } else {
 5773:             $spacer = ('&nbsp;' x2);
 5774:         }
 5775:         $datatable .= '<label>'.
 5776:                       '<input type="checkbox" name="ltitools_add_fields" value="'.$field.'"'.$id.$onclick.' />'.
 5777:                       $lt{$field}.'</label>'.$spacer;
 5778:     }
 5779:     $datatable .= '</span>'.
 5780:                   '<div style="display:none;" id="ltitools_user_div_add">'.
 5781:                   '<span class="LC_nobreak"> : '.
 5782:                   '<select name="ltitools_userincdom_add">'.
 5783:                   '<option value="" selected="selected">'.&mt('Select').'</option>'.
 5784:                   '<option value="0">'.&mt('username').'</option>'.
 5785:                   '<option value="1">'.&mt('username:domain').'</option>'.
 5786:                   '</select></span></div></fieldset>';
 5787:     $datatable .= '<fieldset><legend>'.&mt('Role mapping').'</legend><table><tr>';
 5788:     foreach my $role (@courseroles) {
 5789:         my ($checked,$checkednone);
 5790:         $datatable .= '<td style="text-align: center">'.
 5791:                       &Apache::lonnet::plaintext($role,'Course').'<br />'.
 5792:                       '<select name="ltitools_add_roles_'.$role.'">'.
 5793:                       '<option value="" selected="selected">'.&mt('Select').'</option>';
 5794:         foreach my $ltirole (@ltiroles) {
 5795:             $datatable .= '<option value="'.$ltirole.'">'.$ltirole.'</option>';
 5796:         }
 5797:         $datatable .= '</select></td>';
 5798:     }
 5799:     $datatable .= '</tr></table></fieldset>'.
 5800:                   '<fieldset><legend>'.&mt('Configurable in course').'</legend><span class="LC_nobreak">';
 5801:     foreach my $item ('label','title','target','linktext','explanation','append') {
 5802:         $datatable .= '<label>'.
 5803:                       '<input type="checkbox" name="ltitools_courseconfig" value="'.$item.'" checked="checked" />'.
 5804:                       $lt{'crs'.$item}.'</label>'.('&nbsp;' x2)."\n";
 5805:     }
 5806:     $datatable .= '</span></fieldset>'.
 5807:                   '<fieldset><legend>'.&mt('Custom items sent on launch').'</legend>'.
 5808:                   '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>'.
 5809:                   '<tr><td><span class="LC_nobreak">'.
 5810:                   '<label><input type="checkbox" name="ltitools_add_custom" value="1" />'.
 5811:                   &mt('Add').'</label></span></td><td><input type="text" name="ltitools_add_custom_name" />'.
 5812:                   '</td><td><input type="text" name="ltitools_add_custom_value" /></td></tr>'.
 5813:                   '</table></fieldset>'."\n".
 5814:                   '</td>'."\n".
 5815:                   '</tr>'."\n";
 5816:     $itemcount ++;
 5817:     return $datatable;
 5818: }
 5819: 
 5820: sub ltitools_names {
 5821:     my %lt = &Apache::lonlocal::texthash(
 5822:                                           'title'          => 'Title',
 5823:                                           'version'        => 'Version',
 5824:                                           'msgtype'        => 'Message Type',
 5825:                                           'sigmethod'      => 'Signature Method',
 5826:                                           'url'            => 'URL',
 5827:                                           'key'            => 'Key',
 5828:                                           'lifetime'       => 'Nonce lifetime (s)',
 5829:                                           'secret'         => 'Secret',
 5830:                                           'icon'           => 'Icon',   
 5831:                                           'user'           => 'User',
 5832:                                           'fullname'       => 'Full Name',
 5833:                                           'firstname'      => 'First Name',
 5834:                                           'lastname'       => 'Last Name',
 5835:                                           'email'          => 'E-mail',
 5836:                                           'roles'          => 'Role',
 5837:                                           'window'         => 'Window',
 5838:                                           'tab'            => 'Tab',
 5839:                                           'iframe'         => 'iFrame',
 5840:                                           'height'         => 'Height',
 5841:                                           'width'          => 'Width',
 5842:                                           'linktext'       => 'Default Link Text',
 5843:                                           'explanation'    => 'Default Explanation',
 5844:                                           'passback'       => 'Tool can return grades:',
 5845:                                           'roster'         => 'Tool can retrieve roster:',
 5846:                                           'crstarget'      => 'Display target',
 5847:                                           'crslabel'       => 'Course label',
 5848:                                           'crstitle'       => 'Course title', 
 5849:                                           'crslinktext'    => 'Link Text',
 5850:                                           'crsexplanation' => 'Explanation',
 5851:                                           'crsappend'      => 'Provider URL',
 5852:                                         );
 5853:     return %lt;
 5854: }
 5855: 
 5856: sub print_proctoring {
 5857:     my ($dom,$settings,$rowtotal) = @_;
 5858:     my $itemcount = 1;
 5859:     my (%ordered,%providernames,%current,%currentdef);
 5860:     my $confname = $dom.'-domainconfig';
 5861:     my $switchserver = &check_switchserver($dom,$confname);
 5862:     if (ref($settings) eq 'HASH') {
 5863:         foreach my $item (keys(%{$settings})) {
 5864:             if (ref($settings->{$item}) eq 'HASH') {
 5865:                 my $num = $settings->{$item}{'order'};
 5866:                 $ordered{$num} = $item;
 5867:             }
 5868:         }
 5869:     } else {
 5870:         %ordered = (
 5871:                      1 => 'proctorio',
 5872:                      2 => 'examity',
 5873:                    );
 5874:     }
 5875:     %providernames = &proctoring_providernames();
 5876:     my $maxnum = scalar(keys(%ordered));
 5877:     my (%requserfields,%optuserfields,%defaults,%extended,%crsconf,@courseroles,@ltiroles);
 5878:     my ($requref,$opturef,$defref,$extref,$crsref,$rolesref,$ltiref) = &proctoring_data();
 5879:     if (ref($requref) eq 'HASH') {
 5880:         %requserfields = %{$requref};
 5881:     }
 5882:     if (ref($opturef) eq 'HASH') {
 5883:         %optuserfields = %{$opturef};
 5884:     }
 5885:     if (ref($defref) eq 'HASH') {
 5886:         %defaults = %{$defref};
 5887:     }
 5888:     if (ref($extref) eq 'HASH') {
 5889:         %extended = %{$extref};
 5890:     }
 5891:     if (ref($crsref) eq 'HASH') {
 5892:         %crsconf = %{$crsref};
 5893:     }
 5894:     if (ref($rolesref) eq 'ARRAY') {
 5895:         @courseroles = @{$rolesref};
 5896:     }
 5897:     if (ref($ltiref) eq 'ARRAY') {
 5898:         @ltiroles = @{$ltiref};
 5899:     }
 5900:     my $datatable;
 5901:     my $css_class;
 5902:     if (keys(%ordered)) {
 5903:         my @items = sort { $a <=> $b } keys(%ordered);
 5904:         for (my $i=0; $i<@items; $i++) {
 5905:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5906:             my $provider = $ordered{$items[$i]};
 5907:             my $optionsty = 'none';
 5908:             my ($available,$version,$lifetime,$imgsrc,$userincdom,$showroles,
 5909:                 %checkedfields,%rolemaps,%inuse,%crsconfig,%current);
 5910:             if (ref($settings) eq 'HASH') {
 5911:                 if (ref($settings->{$provider}) eq 'HASH') {
 5912:                     %current = %{$settings->{$provider}};
 5913:                     if ($current{'available'}) {
 5914:                         $optionsty = 'block';
 5915:                         $available = 1;
 5916:                     }
 5917:                     if ($current{'lifetime'} =~ /^\d+$/) {
 5918:                         $lifetime = $current{'lifetime'};
 5919:                     }
 5920:                     if ($current{'version'} =~ /^\d+\.\d+$/) {
 5921:                         $version = $current{'version'};
 5922:                     }
 5923:                     if ($current{'image'} ne '') {
 5924:                         $imgsrc = '<img src="'.$current{'image'}.'" alt="'.&mt('Proctoring service icon').'" />';
 5925:                     }
 5926:                     if (ref($current{'fields'}) eq 'ARRAY') {
 5927:                         map { $checkedfields{$_} = 1; } @{$current{'fields'}};
 5928:                     }
 5929:                     $userincdom = $current{'incdom'};
 5930:                     if (ref($current{'roles'}) eq 'HASH') {
 5931:                         %rolemaps = %{$current{'roles'}};
 5932:                         $checkedfields{'roles'} = 1;
 5933:                     }
 5934:                     if (ref($current{'defaults'}) eq 'ARRAY') {
 5935:                         foreach my $val (@{$current{'defaults'}}) {
 5936:                             if (grep(/^\Q$val\E$/,@{$defaults{$provider}})) {
 5937:                                 $inuse{$val} = 1;
 5938:                             } else {
 5939:                                 foreach my $poss (keys(%{$extended{$provider}})) {
 5940:                                     if (ref($extended{$provider}{$poss}) eq 'ARRAY') {
 5941:                                         if (grep(/^\Q$val\E$/,@{$extended{$provider}{$poss}})) {
 5942:                                             $inuse{$poss} = $val;
 5943:                                             last;
 5944:                                         }
 5945:                                     }
 5946:                                 }
 5947:                             }
 5948:                         }
 5949:                     } elsif (ref($current{'defaults'}) eq 'HASH') {
 5950:                         foreach my $key (keys(%{$current{'defaults'}})) {
 5951:                             my $currval = $current{'defaults'}{$key}; 
 5952:                             if (grep(/^\Q$key\E$/,@{$defaults{$provider}})) {
 5953:                                 $inuse{$key} = 1;
 5954:                             } else {
 5955:                                 my $match;
 5956:                                 foreach my $poss (keys(%{$extended{$provider}})) {
 5957:                                     if (ref($extended{$provider}{$poss}) eq 'ARRAY') {
 5958:                                         if (grep(/^\Q$key\E$/,@{$extended{$provider}{$poss}})) {
 5959:                                             $inuse{$poss} = $key;
 5960:                                             last;
 5961:                                         }
 5962:                                     } elsif (ref($extended{$provider}{$poss}) eq 'HASH') {
 5963:                                         foreach my $inner (sort(keys(%{$extended{$provider}{$poss}}))) {
 5964:                                             if (ref($extended{$provider}{$poss}{$inner}) eq 'ARRAY') {
 5965:                                                 if (grep(/^\Q$currval\E$/,@{$extended{$provider}{$poss}{$inner}})) {
 5966:                                                     $currentdef{$inner} = $currval;
 5967:                                                     $match = 1;
 5968:                                                     last;
 5969:                                                 }
 5970:                                             } elsif ($inner eq $key) {
 5971:                                                 $currentdef{$key} = $currval;
 5972:                                                 $match = 1;
 5973:                                                 last;
 5974:                                             }
 5975:                                         }
 5976:                                     }
 5977:                                     last if ($match);
 5978:                                 }
 5979:                             }
 5980:                         }
 5981:                     }
 5982:                     if (ref($current{'crsconf'}) eq 'ARRAY') {
 5983:                         map { $crsconfig{$_} = 1; } @{$current{'crsconf'}};
 5984:                     }
 5985:                 }
 5986:             }
 5987:             my %lt = &proctoring_titles($provider);
 5988:             my %fieldtitles = &proctoring_fieldtitles($provider);
 5989:             my $onclickavailable = ' onclick="toggleProctoring(this.form,'."'$provider'".');"';
 5990:             my %checkedavailable = (
 5991:                                    yes => '',
 5992:                                    no  => ' checked="checked"',
 5993:                                  );
 5994:             if ($available) {
 5995:                 $checkedavailable{'yes'} = $checkedavailable{'no'};
 5996:                 $checkedavailable{'no'} = '';
 5997:             }
 5998:             my $chgstr = ' onchange="javascript:reorderProctoring(this.form,'."'proctoring_pos_".$provider."'".');"';
 5999:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 6000:                          .'<select name="proctoring_pos_'.$provider.'"'.$chgstr.'>';
 6001:             for (my $k=0; $k<$maxnum; $k++) {
 6002:                 my $vpos = $k+1;
 6003:                 my $selstr;
 6004:                 if ($k == $i) {
 6005:                     $selstr = ' selected="selected" ';
 6006:                 }
 6007:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 6008:             }
 6009:             if ($version eq '') {
 6010:                 if ($provider eq 'proctorio') {
 6011:                     $version = '1.0';
 6012:                 } elsif ($provider eq 'examity') {
 6013:                     $version = '1.1';
 6014:                 }
 6015:             }
 6016:             if ($lifetime eq '') {
 6017:                 $lifetime = '300';
 6018:             }
 6019:             $datatable .=
 6020:                 '</select>'.('&nbsp;'x2).'<b>'.$providernames{$provider}.'</b></span><br />'.
 6021:                 '<span class="LC_nobreak">'.$lt{'avai'}.'&nbsp;'.
 6022:                 '<label><input type="radio" name="proctoring_available_'.$provider.'" value="1"'.$onclickavailable.$checkedavailable{yes}.' />'.&mt('Yes').'</label>&nbsp;'."\n".
 6023:                 '<label><input type="radio" name="proctoring_available_'.$provider.'" value="0"'.$onclickavailable.$checkedavailable{no}.' />'.&mt('No').'</label></span>'."\n".
 6024:                 '</td>'.
 6025:                 '<td colspan="2">'.
 6026:                 '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'"><legend>'.$lt{'base'}.'</legend>'.
 6027:                 '<span class="LC_nobreak">'.$lt{'version'}.':<select name="proctoring_'.$provider.'_version">'.
 6028:                 '<option value="'.$version.'" selected="selected">'.$version.'</option></select></span> '."\n".
 6029:                 ('&nbsp;'x2).
 6030:                 '<span class="LC_nobreak">'.$lt{'sigmethod'}.':<select name="proctoring_'.$provider.'_sigmethod">'.
 6031:                 '<option value="HMAC-SHA1" selected="selected">HMAC-SHA1</option>'.
 6032:                 '<option value="HMAC-SHA256">HMAC-SHA256</option></select></span>'.
 6033:                 ('&nbsp;'x2).
 6034:                 '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" size="5" name="proctoring_'.$provider.'_lifetime" value="'.$lifetime.'" /></span> '."\n".
 6035:                 '<br />'.
 6036:                 '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="40" name="proctoring_'.$provider.'_url" value="'.$current{'url'}.'" /></span> '."\n".
 6037:                 '<br />'.
 6038:                 '<span class="LC_nobreak">'.$lt{'key'}.':<input type="text" size="25" name="proctoring_'.$provider.'_key" value="'.$current{'key'}.'" /></span> '."\n".
 6039:                 ('&nbsp;'x2).
 6040:                 '<span class="LC_nobreak">'.$lt{'secret'}.':<input type="password" size="20" name="proctoring_'.$provider.'_secret" value="'.$current{'secret'}.'" />'.
 6041:                 '<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.proctoring_'.$provider.'_secret.type='."'text'".' } else { this.form.proctoring_'.$provider.'_secret.type='."'password'".' }" />'.$lt{'visible'}.'</label></span><br />'."\n";
 6042:             $datatable .= '<span class="LC_nobreak">'.$lt{'icon'}.':&nbsp;';
 6043:             if ($imgsrc) {
 6044:                 $datatable .= $imgsrc.
 6045:                               '<label><input type="checkbox" name="proctoring_image_del"'.
 6046:                               ' value="'.$provider.'" />'.&mt('Delete?').'</label></span> '.
 6047:                               '<span class="LC_nobreak">&nbsp;'.&mt('Replace:');
 6048:             }
 6049:             $datatable .= '&nbsp;';
 6050:             if ($switchserver) {
 6051:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 6052:             } else {
 6053:                 $datatable .= '<input type="file" name="proctoring_image_'.$provider.'" value="" />';
 6054:             }
 6055:             unless ($imgsrc) {
 6056:                 $datatable .= '<br />('.&mt('if larger than 21x21 pixels, image will be scaled').')';
 6057:             }
 6058:             $datatable .= '</fieldset>'."\n";
 6059:             if (ref($requserfields{$provider}) eq 'ARRAY') {
 6060:                 if (@{$requserfields{$provider}} > 0) {
 6061:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'"><legend>'.$lt{'requ'}.'</legend>';
 6062:                     foreach my $field (@{$requserfields{$provider}}) {
 6063:                         $datatable .= '<span class="LC_nobreak">'.
 6064:                                       '<label><input type="checkbox" name="proctoring_reqd_'.$provider.'" value="'.$field.'" checked="checked" disabled="disabled" />'.
 6065:                                       $lt{$field}.'</label>';
 6066:                         if ($field eq 'user') {
 6067:                             my $seluserdom = '';
 6068:                             my $unseluserdom = ' selected="selected"';
 6069:                             if ($userincdom) {
 6070:                                 $seluserdom = $unseluserdom;
 6071:                                 $unseluserdom = '';
 6072:                             }
 6073:                             $datatable .= ':&nbsp;'.
 6074:                                 '<select name="proctoring_userincdom_'.$provider.'">'.
 6075:                                 '<option value="0"'.$unseluserdom.'>'.$lt{'username'}.'</option>'.
 6076:                                 '<option value="1"'.$seluserdom.'>'.$lt{'uname:dom'}.'</option>'.
 6077:                                 '</select>&nbsp;';
 6078:                         } else {
 6079:                             $datatable .= '&nbsp;';
 6080:                             if ($field eq 'roles') {
 6081:                                 $showroles = 1; 
 6082:                             } 
 6083:                         }
 6084:                         $datatable .= '</span> ';
 6085:                     }
 6086:                 }
 6087:                 $datatable .= '</fieldset>'."\n";
 6088:             }
 6089:             if (ref($optuserfields{$provider}) eq 'ARRAY') {
 6090:                 if (@{$optuserfields{$provider}} > 0) {
 6091:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'"><legend>'.$lt{'optu'}.'</legend>'; 
 6092:                     foreach my $field (@{$optuserfields{$provider}}) {
 6093:                         my $checked;
 6094:                         if ($checkedfields{$field}) {
 6095:                             $checked = ' checked="checked"';
 6096:                         }
 6097:                         $datatable .= '<span class="LC_nobreak">'.
 6098:                                       '<label><input type="checkbox" name="proctoring_optional_'.$provider.'" value="'.$field.'"'.$checked.' />'.$lt{$field}.'</label></span>&nbsp; ';
 6099:                     }
 6100:                     $datatable .= '</fieldset>'."\n";
 6101:                 }
 6102:             }
 6103:             if (ref($defaults{$provider}) eq 'ARRAY') {
 6104:                 if (@{$defaults{$provider}}) {
 6105:                     my (%options,@selectboxes);
 6106:                     if (ref($extended{$provider}) eq 'HASH') {
 6107:                         %options = %{$extended{$provider}};
 6108:                     }
 6109:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'"><legend>'.$lt{'defa'}.'</legend>';
 6110:                     my ($rem,$numinrow,$dropdowns);
 6111:                     if ($provider eq 'proctorio') { 
 6112:                         $datatable .= '<table>';
 6113:                         $numinrow = 4;
 6114:                     }
 6115:                     my $i = 0;
 6116:                     foreach my $field (@{$defaults{$provider}}) {
 6117:                         my $checked;
 6118:                         if ($inuse{$field}) {
 6119:                             $checked = ' checked="checked"';
 6120:                         }
 6121:                         if ($provider eq 'examity') {
 6122:                             if ($field eq 'display') {
 6123:                                 $datatable .= '<span class="LC_nobreak">'.&mt('Display target:');
 6124:                                 foreach my $option ('iframe','tab','window') {
 6125:                                     my $checkdisp;
 6126:                                     if ($currentdef{'target'} eq $option) {
 6127:                                         $checkdisp = ' checked="checked"';
 6128:                                     }
 6129:                                     $datatable .= '<label><input type="radio" name="proctoring_target_'.$provider.'" value="'.$option.'"'.$checkdisp.' />'.
 6130:                                     $fieldtitles{$option}.'</label>'.('&nbsp;'x2);
 6131:                                 }
 6132:                                 $datatable .= ('&nbsp;'x4);
 6133:                                 foreach my $dimen ('width','height') {
 6134:                                     $datatable .= '<label>'.$fieldtitles{$dimen}.'&nbsp;'.
 6135:                                                   '<input type="text" name="proctoring_'.$dimen.'_'.$provider.'" size="5" '.
 6136:                                                   'value="'.$currentdef{$dimen}.'" /></label>'.
 6137:                                                   ('&nbsp;'x2);
 6138:                                 }
 6139:                                 $datatable .= '</span><br />'.
 6140:                                               '<div class="LC_left_float">'.$fieldtitles{'linktext'}.'<br />'.
 6141:                                               '<input type="text" name="proctoring_linktext_'.$provider.'" '.
 6142:                                               'size="25" value="'.$currentdef{'linktext'}.'" /></div>'.
 6143:                                               '<div class="LC_left_float">'.$fieldtitles{'explanation'}.'<br />'.
 6144:                                               '<textarea name="proctoring_explanation_'.$provider.'" rows="5" cols="40">'.
 6145:                                               $currentdef{'explanation'}.
 6146:                                               '</textarea></div><div style=""></div><br />';
 6147:                             }
 6148:                         } else {
 6149:                             if ((exists($options{$field})) && (ref($options{$field}) eq 'ARRAY')) {
 6150:                                 my ($output,$selnone);
 6151:                                 unless ($checked) {
 6152:                                     $selnone = ' selected="selected"';
 6153:                                 }
 6154:                                 $output .= '<span class="LC_nobreak">'.$fieldtitles{$field}.': '.
 6155:                                            '<select name="proctoring_defaults_'.$field.'_'.$provider.'">'.
 6156:                                            '<option value=""'.$selnone.'>'.&mt('Not in use').'</option>'; 
 6157:                                 foreach my $option (@{$options{$field}}) {
 6158:                                     my $sel; 
 6159:                                     if ($inuse{$field} eq $option) {
 6160:                                         $sel = ' selected="selected"';
 6161:                                     }
 6162:                                     $output .= '<option value="'.$option.'"'.$sel.'>'.$fieldtitles{$option}.'</option>';
 6163:                                 }
 6164:                                 $output .= '</select></span>';
 6165:                                 push(@selectboxes,$output);
 6166:                             } else {
 6167:                                 $rem = $i%($numinrow);
 6168:                                 if ($rem == 0) {
 6169:                                     if ($i > 0) {
 6170:                                         $datatable .= '</tr>';
 6171:                                     }
 6172:                                     $datatable .= '<tr>';
 6173:                                 }
 6174:                                 $datatable .= '<td class="LC_left_item">'.
 6175:                                               '<span class="LC_nobreak">'.
 6176:                                               '<label><input type="checkbox" name="proctoring_defaults_'.$provider.'" value="'.$field.'"'.$checked.' />'.
 6177:                                               $fieldtitles{$field}.'</label></span></td>';
 6178:                                 $i++;
 6179:                             }
 6180:                         }
 6181:                     }
 6182:                     if ($provider eq 'proctorio') {
 6183:                         if ($numinrow) {
 6184:                             $rem = $i%$numinrow;
 6185:                         }
 6186:                         my $colsleft = $numinrow - $rem;
 6187:                         if ($colsleft > 1) {
 6188:                             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 6189:                         } else {
 6190:                             $datatable .= '<td class="LC_left_item">';
 6191:                         }
 6192:                         $datatable .= '&nbsp;'.
 6193:                                       '</td></tr></table>';
 6194:                         if (@selectboxes) {
 6195:                             $datatable .= '<hr /><table>';
 6196:                             $numinrow = 2;
 6197:                             for (my $i=0; $i<@selectboxes; $i++) {
 6198:                                 $rem = $i%($numinrow);
 6199:                                 if ($rem == 0) {
 6200:                                     if ($i > 0) {
 6201:                                         $datatable .= '</tr>';
 6202:                                     }
 6203:                                     $datatable .= '<tr>';
 6204:                                 }
 6205:                                 $datatable .= '<td class="LC_left_item">'.
 6206:                                               $selectboxes[$i].'</td>';
 6207:                             }
 6208:                             if ($numinrow) {
 6209:                                 $rem = $i%$numinrow;
 6210:                             }
 6211:                             $colsleft = $numinrow - $rem;
 6212:                             if ($colsleft > 1) {
 6213:                                 $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 6214:                             } else {
 6215:                                 $datatable .= '<td class="LC_left_item">';
 6216:                             }
 6217:                             $datatable .= '&nbsp;'.
 6218:                                           '</td></tr></table>';
 6219:                         }
 6220:                     }
 6221:                     $datatable .= '</fieldset>';
 6222:                 }
 6223:                 if (ref($crsconf{$provider}) eq 'ARRAY') {
 6224:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'">'.
 6225:                                   '<legend>'.&mt('Configurable in course').'</legend>';
 6226:                     my ($rem,$numinrow);
 6227:                     if ($provider eq 'proctorio') {
 6228:                         $datatable .= '<table>';
 6229:                         $numinrow = 4;
 6230:                     }
 6231:                     my $i = 0;
 6232:                     foreach my $item (@{$crsconf{$provider}}) {
 6233:                         my $name;
 6234:                         if ($provider eq 'examity') {
 6235:                             $name = $lt{'crs'.$item};
 6236:                         } elsif ($provider eq 'proctorio') {
 6237:                             $name = $fieldtitles{$item};
 6238:                             $rem = $i%($numinrow);
 6239:                             if ($rem == 0) {
 6240:                                 if ($i > 0) {
 6241:                                     $datatable .= '</tr>';
 6242:                                 }
 6243:                                 $datatable .= '<tr>';
 6244:                             }
 6245:                             $datatable .= '<td class="LC_left_item>';
 6246:                         }
 6247:                         my $checked;
 6248:                         if ($crsconfig{$item}) {
 6249:                             $checked = ' checked="checked"';
 6250:                         }
 6251:                         $datatable .= '<span class="LC_nobreak"><label>'.
 6252:                                       '<input type="checkbox" name="proctoring_crsconf_'.$provider.'" value="'.$item.'"'.$checked.' />'.
 6253:                                       $name.'</label></span>';
 6254:                         if ($provider eq 'examity') {
 6255:                             $datatable .= '&nbsp; ';
 6256:                         }
 6257:                         $datatable .= "\n";
 6258:                         $i++;
 6259:                     }
 6260:                     if ($provider eq 'proctorio') {
 6261:                         if ($numinrow) {
 6262:                             $rem = $i%$numinrow;
 6263:                         }
 6264:                         my $colsleft = $numinrow - $rem;
 6265:                         if ($colsleft > 1) {
 6266:                             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 6267:                         } else {
 6268:                             $datatable .= '<td class="LC_left_item">';
 6269:                         }
 6270:                         $datatable .= '&nbsp;'.
 6271:                                       '</td></tr></table>';
 6272:                     }
 6273:                     $datatable .= '</fieldset>';
 6274:                 }
 6275:                 if ($showroles) {
 6276:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'">'.
 6277:                                   '<legend>'.&mt('Role mapping').'</legend><table><tr>';
 6278:                     foreach my $role (@courseroles) {
 6279:                         my ($selected,$selectnone);
 6280:                         if (!$rolemaps{$role}) {
 6281:                             $selectnone = ' selected="selected"';
 6282:                         }
 6283:                         $datatable .= '<td style="text-align: center">'.
 6284:                                       &Apache::lonnet::plaintext($role,'Course').'<br />'.
 6285:                                       '<select name="proctoring_roles_'.$role.'_'.$provider.'">'.
 6286:                                       '<option value=""'.$selectnone.'>'.&mt('Select').'</option>';
 6287:                         foreach my $ltirole (@ltiroles) {
 6288:                             unless ($selectnone) {
 6289:                                 if ($rolemaps{$role} eq $ltirole) {
 6290:                                     $selected = ' selected="selected"';
 6291:                                 } else {
 6292:                                     $selected = '';
 6293:                                 }
 6294:                             }
 6295:                             $datatable .= '<option value="'.$ltirole.'"'.$selected.'>'.$ltirole.'</option>';
 6296:                         }
 6297:                         $datatable .= '</select></td>';
 6298:                     }
 6299:                     $datatable .= '</tr></table></fieldset>'.
 6300:                                   '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'">'.
 6301:                                   '<legend>'.&mt('Custom items sent on launch').'</legend>'.
 6302:                                   '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>'.
 6303:                                   '<tr><td></td><td>lms</td>'.
 6304:                                   '<td><input type="text" name="proctoring_customval_lms_'.$provider.'"'.
 6305:                                   ' value="Loncapa" disabled="disabled"/></td></tr>';
 6306:                     if ((ref($settings) eq 'HASH') && (ref($settings->{$provider}) eq 'HASH') &&
 6307:                         (ref($settings->{$provider}->{'custom'}) eq 'HASH')) {
 6308:                         my %custom = %{$settings->{$provider}->{'custom'}};
 6309:                         if (keys(%custom) > 0) {
 6310:                             foreach my $key (sort(keys(%custom))) {
 6311:                                 next if ($key eq 'lms');
 6312:                                 $datatable .= '<tr><td><span class="LC_nobreak">'.
 6313:                                               '<label><input type="checkbox" name="proctoring_customdel_'.$provider.'" value="'.
 6314:                                               $key.'" />'.&mt('Delete').'</label></span></td><td>'.$key.'</td>'.
 6315:                                               '<td><input type="text" name="proctoring_customval_'.$key.'_'.$provider.'"'.
 6316:                                               ' value="'.$custom{$key}.'" /></td></tr>';
 6317:                             }
 6318:                         }
 6319:                     }
 6320:                     $datatable .= '<tr><td><span class="LC_nobreak">'.
 6321:                                   '<label><input type="checkbox" name="proctoring_customadd" value="'.$provider.'" />'.
 6322:                                   &mt('Add more').'</label></span></td><td><input type="text" name="proctoring_custom_name_'.$provider.'" />'.
 6323:                                   '</td><td><input type="text" name="proctoring_custom_value_'.$provider.'" /></td></tr>'.
 6324:                                   '</table></fieldset></td></tr>'."\n";
 6325:                 }
 6326:                 $datatable .= '</td></tr>';
 6327:             }
 6328:             $itemcount ++;
 6329:         }
 6330:     }
 6331:     return $datatable;
 6332: }
 6333: 
 6334: sub proctoring_data {
 6335:     my $requserfields = {
 6336:                       proctorio => ['user'],
 6337:                       examity   => ['roles','user'],
 6338:                      };
 6339:     my $optuserfields = {
 6340:                         proctorio => ['fullname'],
 6341:                         examity   => ['fullname','firstname','lastname','email'],
 6342:                      };
 6343:     my $defaults = {
 6344:                   proctorio => ['recordvideo','recordaudio','recordscreen','recordwebtraffic',
 6345:                                 'recordroomstart','verifyvideo','verifyaudio','verifydesktop',
 6346:                                 'verifyid','verifysignature','fullscreen','clipboard','tabslinks',
 6347:                                 'closetabs','onescreen','print','downloads','cache','rightclick',
 6348:                                 'reentry','calculator','whiteboard'],
 6349:                   examity   => ['display'],
 6350:                 };
 6351:     my $extended = { 
 6352:                   proctorio => {
 6353:                                  verifyid => ['verifyidauto','verifyidlive'],
 6354:                                  fullscreen => ['fullscreenlenient','fullscreenmoderate','fullscreensever'],
 6355:                                  tabslinks => ['notabs','linksonly'],
 6356:                                  reentry => ['noreentry','agentreentry'],
 6357:                                  calculator => ['calculatorbasic','calculatorsci'],
 6358:                                },
 6359:                   examity => {
 6360:                                display => {
 6361:                                            target      => ['iframe','tab','window'],
 6362:                                            width       => '',
 6363:                                            height      => '',
 6364:                                            linktext    => '',
 6365:                                            explanation => '',
 6366:                                           },
 6367:                              },
 6368:                 };
 6369:     my $crsconf = {
 6370:                  proctorio => ['recordvideo','recordaudio','recordscreen','recordwebtraffic',
 6371:                                'recordroomstart','verifyvideo','verifyaudio','verifydesktop',
 6372:                                'verifyid','verifysignature','fullscreen','clipboard','tabslinks',
 6373:                                'closetabs','onescreen','print','downloads','cache','rightclick',
 6374:                                'reentry','calculator','whiteboard'],
 6375:                  examity => ['label','title','target','linktext','explanation','append'],
 6376:                };
 6377:     my $courseroles = ['cc','in','ta','ep','st'];
 6378:     my $ltiroles = ['Instructor','ContentDeveloper','TeachingAssistant','Learner'];
 6379:     return ($requserfields,$optuserfields,$defaults,$extended,$crsconf,$courseroles,$ltiroles);
 6380: }
 6381: 
 6382: sub proctoring_titles {
 6383:     my ($item) = @_;
 6384:     my (%common_lt,%custom_lt);
 6385:     %common_lt = &Apache::lonlocal::texthash (
 6386:                      'avai'      => 'Available?',
 6387:                      'base'      => 'Basic Settings',
 6388:                      'requ'      => 'User data required to be sent on launch',
 6389:                      'optu'      => 'User data optionally sent on launch',
 6390:                      'udsl'      => 'User data sent on launch',
 6391:                      'defa'      => 'Defaults for items configurable in course',
 6392:                      'sigmethod' => 'Signature Method',
 6393:                      'key'       => 'Key',
 6394:                      'lifetime'  => 'Nonce lifetime (s)',
 6395:                      'secret'    => 'Secret',
 6396:                      'icon'      => 'Icon',
 6397:                      'fullname'  => 'Full Name',
 6398:                      'visible'   => 'Visible input',
 6399:                      'username'  => 'username',
 6400:                      'user'      => 'User',
 6401:                  );
 6402:     if ($item eq 'proctorio') {
 6403:         %custom_lt = &Apache::lonlocal::texthash (
 6404:                          'version'        => 'OAuth version',
 6405:                          'url'            => 'API URL',
 6406:                          'uname:dom'      => 'username-domain',
 6407:         );
 6408:     } elsif ($item eq 'examity') {
 6409:         %custom_lt = &Apache::lonlocal::texthash (
 6410:                          'version'        => 'LTI Version',
 6411:                          'url'            => 'URL',
 6412:                          'uname:dom'      => 'username:domain',
 6413:                          'msgtype'        => 'Message Type',
 6414:                          'firstname'      => 'First Name',
 6415:                          'lastname'       => 'Last Name',
 6416:                          'email'          => 'E-mail',
 6417:                          'roles'          => 'Role',
 6418:                          'crstarget'      => 'Display target',
 6419:                          'crslabel'       => 'Course label',
 6420:                          'crstitle'       => 'Course title', 
 6421:                          'crslinktext'    => 'Link Text',
 6422:                          'crsexplanation' => 'Explanation',
 6423:                          'crsappend'      => 'Provider URL',
 6424:         );
 6425:     }
 6426:     my %lt = (%common_lt,%custom_lt);
 6427:     return %lt;
 6428: }
 6429: 
 6430: sub proctoring_fieldtitles {
 6431:     my ($item) = @_;
 6432:     if ($item eq 'proctorio') {
 6433:         return &Apache::lonlocal::texthash (
 6434:                   'recordvideo' => 'Record video',
 6435:                   'recordaudio' => 'Record audio',
 6436:                   'recordscreen' => 'Record screen',
 6437:                   'recordwebtraffic' => 'Record web traffic',
 6438:                   'recordroomstart' => 'Record room scan',
 6439:                   'verifyvideo' => 'Verify webcam',
 6440:                   'verifyaudio' => 'Verify microphone',
 6441:                   'verifydesktop' => 'Verify desktop recording',
 6442:                   'verifyid' => 'Photo ID verification',
 6443:                   'verifysignature' => 'Require signature',
 6444:                   'fullscreen' => 'Fullscreen',
 6445:                   'clipboard' => 'Disable copy/paste',
 6446:                   'tabslinks' => 'New tabs/windows',
 6447:                   'closetabs' => 'Close other tabs',
 6448:                   'onescreen' => 'Limit to single screen',
 6449:                   'print' => 'Disable Printing',
 6450:                   'downloads' => 'Disable Downloads',
 6451:                   'cache' => 'Empty cache after exam',
 6452:                   'rightclick' => 'Disable right click',
 6453:                   'reentry' => 'Re-entry to exam',
 6454:                   'calculator' => 'Onscreen calculator',
 6455:                   'whiteboard' => 'Onscreen whiteboard',
 6456:                   'verifyidauto' => 'Automated verification',
 6457:                   'verifyidlive' => 'Live agent verification',
 6458:                   'fullscreenlenient' => 'Forced, but can navigate away for up to 30s',
 6459:                   'fullscreenmoderate' => 'Forced, but can navigate away for up to 15s',
 6460:                   'fullscreensever' => 'Forced, navigation away ends exam',
 6461:                   'notabs' => 'Disaallowed',
 6462:                   'linksonly' => 'Allowed from links in exam',
 6463:                   'noreentry' => 'Disallowed',
 6464:                   'agentreentry' => 'Agent required for re-entry',
 6465:                   'calculatorbasic' => 'Basic',
 6466:                   'calculatorsci' => 'Scientific',
 6467:         );
 6468:     } elsif ($item eq 'examity') {
 6469:         return &Apache::lonlocal::texthash (
 6470:                 'target'         => 'Display target',   
 6471:                 'window'         => 'Window',
 6472:                 'tab'            => 'Tab',
 6473:                 'iframe'         => 'iFrame',
 6474:                 'height'         => 'Height (pixels)',
 6475:                 'width'          => 'Width (pixels)',
 6476:                 'linktext'       => 'Default Link Text',
 6477:                 'explanation'    => 'Default Explanation',
 6478:                 'append'         => 'Provider URL',
 6479:         );
 6480:     }
 6481: }
 6482: 
 6483: sub proctoring_providernames {
 6484:     return (
 6485:              proctorio => 'Proctorio',
 6486:              examity   => 'Examity',
 6487:            );
 6488: }
 6489: 
 6490: sub print_lti {
 6491:     my ($position,$dom,$settings,$rowtotal) = @_;
 6492:     my $itemcount = 1;
 6493:     my ($datatable,$css_class);
 6494:     my (%rules,%encrypt,%privkeys,%linkprot);
 6495:     if (ref($settings) eq 'HASH') {
 6496:         if ($position eq 'top') {
 6497:             if (exists($settings->{'encrypt'})) {
 6498:                 if (ref($settings->{'encrypt'}) eq 'HASH') {
 6499:                     foreach my $key (keys(%{$settings->{'encrypt'}})) {
 6500:                         if ($key eq 'consumers') {
 6501:                             $encrypt{'ltisec_'.$key} = $settings->{'encrypt'}{$key};
 6502:                         } else {
 6503:                             $encrypt{'ltisec_'.$key.'linkprot'} = $settings->{'encrypt'}{$key};
 6504:                         }
 6505:                     }
 6506:                 }
 6507:             }
 6508:             if (exists($settings->{'private'})) {
 6509:                 if (ref($settings->{'private'}) eq 'HASH') {
 6510:                     if (ref($settings->{'private'}) eq 'HASH') {
 6511:                         if (ref($settings->{'private'}{'keys'}) eq 'ARRAY') {
 6512:                             map { $privkeys{$_} = 1; } (@{$settings->{'private'}{'keys'}});
 6513:                         }
 6514:                     }
 6515:                 }
 6516:             }
 6517:         } elsif ($position eq 'middle') {
 6518:             if (exists($settings->{'rules'})) {
 6519:                 if (ref($settings->{'rules'}) eq 'HASH') {
 6520:                     %rules = %{$settings->{'rules'}};
 6521:                 }
 6522:             }
 6523:         } elsif ($position eq 'lower') {
 6524:             if (exists($settings->{'linkprot'})) {
 6525:                 if (ref($settings->{'linkprot'}) eq 'HASH') {
 6526:                     %linkprot = %{$settings->{'linkprot'}};
 6527:                     if ($linkprot{'lock'}) {
 6528:                         delete($linkprot{'lock'});
 6529:                     }
 6530:                 }
 6531:             }
 6532:         } else {
 6533:             foreach my $key ('encrypt','private','rules','linkprot') {
 6534:                 if (exists($settings->{$key})) {
 6535:                     delete($settings->{$key});
 6536:                 }
 6537:             }
 6538:         }
 6539:     }
 6540:     if ($position eq 'top') {
 6541:         my @ids=&Apache::lonnet::current_machine_ids();
 6542:         my %servers = &Apache::lonnet::get_servers($dom,'library');
 6543:         my $primary = &Apache::lonnet::domain($dom,'primary');
 6544:         my ($extra,$numshown);
 6545:         foreach my $hostid (sort(keys(%servers))) {
 6546:             my ($showextra,$divsty,$switch);
 6547:             if ($hostid eq $primary) {
 6548:                 if (($encrypt{'ltisec_consumers'}) || ($encrypt{'ltisec_domlinkprot'})) {
 6549:                     $showextra = 1;
 6550:                 }
 6551:             }
 6552:             if ($encrypt{'ltisec_crslinkprot'}) {
 6553:                 $showextra = 1;
 6554:             }
 6555:             unless (grep(/^\Q$hostid\E$/,@ids)) {
 6556:                 $switch = 1;
 6557:             }
 6558:             if ($showextra) {
 6559:                 $numshown ++;
 6560:                 $divsty = 'display:inline-block'; 
 6561:             } else {
 6562:                 $divsty = 'display:none';
 6563:             } 
 6564:             $extra .= '<fieldset id="ltisec_info_'.$hostid.'" style="'.$divsty.'">'.
 6565:                       '<legend>'.$hostid.'</legend>';
 6566:             if ($switch) {
 6567:                 my $switchserver = '<a href="/adm/switchserver?otherserver='.$hostid.'&amp;role='.
 6568:                                    &HTML::Entities::encode($env{'request.role'},'\'<>"&').
 6569:                                    '&amp;destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
 6570:                 if (exists($privkeys{$hostid})) {
 6571:                     $extra .= '<div id="ltisec_divcurrprivkey_'.$hostid.'" style="display:inline-block" />'.
 6572:                               '<span class="LC_nobreak">'.
 6573:                               &mt('Encryption Key').': ['.&mt('not shown').'] '.('&nbsp;'x2).'</span></div>'.
 6574:                               '<span class="LC_nobreak">'.&mt('Change?').
 6575:                               '<label><input type="radio" value="0" name="ltisec_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$hostid'".');" checked="checked" />'.&mt('No').'</label>'.
 6576:                               ('&nbsp;'x2).
 6577:                               '<label><input type="radio" value="1" name="ltisec_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$hostid'".');" />'.&mt('Yes').
 6578:                               '</label>&nbsp;&nbsp;</span><div id="ltisec_divchgprivkey_'.$hostid.'" style="display:none" />'.
 6579:                               '<span class="LC_nobreak"> - '.&mt('submit from server ([_1]): [_2].',$hostid,$switchserver).
 6580:                               '</span></div>';
 6581:                 } else {
 6582:                     $extra .= '<span class="LC_nobreak">'.
 6583:                               &mt('Key required').' - '.&mt('submit from server ([_1]): [_2].',$hostid,$switchserver).
 6584:                               '</span>'."\n";
 6585:                 }
 6586:             } elsif (exists($privkeys{$hostid})) {
 6587:                 $extra .= '<div id="ltisec_divcurrprivkey_'.$hostid.'" style="display:inline-block" /><span class="LC_nobreak">'.
 6588:                           &mt('Encryption Key').': ['.&mt('not shown').'] '.('&nbsp;'x2).'</span></div>'.
 6589:                           '<span class="LC_nobreak">'.&mt('Change?').
 6590:                           '<label><input type="radio" value="0" name="ltisec_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$hostid'".');" checked="checked" />'.&mt('No').'</label>'.
 6591:                           ('&nbsp;'x2).
 6592:                           '<label><input type="radio" value="1" name="ltisec_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$hostid'".');" />'.&mt('Yes').
 6593:                           '</label>&nbsp;&nbsp;</span><div id="ltisec_divchgprivkey_'.$hostid.'" style="display:none" />'.
 6594:                           '<span class="LC_nobreak">'.&mt('New Key').':'.
 6595:                           '<input type="password" size="20" name="ltisec_privkey_'.$hostid.'" value="" autocomplete="new-password" />'.
 6596:                           '<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.ltisec_privkey_'.$hostid.'.type='."'text'".' } else { this.form.ltisec_privkey_'.$hostid.'.type='."'password'".' }" />'.&mt('Visible input').'</label>'.
 6597:                           '</span></div>';
 6598:             } else {
 6599:                 $extra .= '<span class="LC_nobreak">'.&mt('Encryption Key').':'.
 6600:                           '<input type="password" size="20" name="ltisec_privkey_'.$hostid.'" value="" autocomplete="new-password" />'.
 6601:                           '<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.ltisec_privkey_'.$hostid.'.type='."'text'".' } else { this.form.ltisec_privkey_'.$hostid.'.type='."'password'".' }" />'.&mt('Visible input').'</label>';
 6602:             }
 6603:             $extra .= '</fieldset>';
 6604:         }
 6605:         my %choices = &Apache::lonlocal::texthash (
 6606:                                                       ltisec_crslinkprot => 'Encrypt stored link protection secrets defined in courses',
 6607:                                                       ltisec_domlinkprot => 'Encrypt stored link protection secrets defined in domain',
 6608:                                                       ltisec_consumers   => 'Encrypt stored consumer secrets defined in domain',
 6609:                                                   );
 6610:         my @toggles = qw(ltisec_crslinkprot ltisec_domlinkprot ltisec_consumers);
 6611:         my %defaultchecked = (
 6612:                                'ltisec_crslinkprot' => 'off',
 6613:                                'ltisec_domlinkprot' => 'off',
 6614:                                'ltisec_consumers'   => 'off',
 6615:                              );
 6616:         my ($onclick,$itemcount);
 6617:         $onclick = 'javascript:toggleLTIEncKey(this.form);';
 6618:         ($datatable,$itemcount) = &radiobutton_prefs(\%encrypt,\@toggles,\%defaultchecked,
 6619:                                                      \%choices,$itemcount,$onclick,'','left','no');
 6620: 
 6621:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6622:         my $noprivkeysty = 'display:inline-block';
 6623:         if ($numshown) {
 6624:             $noprivkeysty = 'display:none'; 
 6625:         }
 6626:         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.&mt('Encryption Key(s)').'</td>'.
 6627:                       '<td><div id="ltisec_noprivkey" style="'.$noprivkeysty.'" >'.
 6628:                       '<span class="LC_nobreak">'.&mt('Not in use').'</span></div>'.
 6629:                       $extra.
 6630:                       '</td></tr>';
 6631:         $itemcount ++;                
 6632:         $$rowtotal += $itemcount;
 6633:     } elsif ($position eq 'middle') {
 6634:         $datatable = &password_rules('secrets',\$itemcount,\%rules);
 6635:         $$rowtotal += $itemcount;
 6636:     } elsif ($position eq 'lower') {
 6637:          $datatable .= &Apache::courseprefs::print_linkprotection($dom,'',$settings,$rowtotal,'','','domain');
 6638:     } else {
 6639:         my $maxnum = 0;
 6640:         my %ordered;
 6641:         if (ref($settings) eq 'HASH') {
 6642:             foreach my $item (keys(%{$settings})) {
 6643:                 if (ref($settings->{$item}) eq 'HASH') {
 6644:                     my $num = $settings->{$item}{'order'};
 6645:                     if ($num eq '') {
 6646:                         $num = scalar(keys(%{$settings}));
 6647:                     }
 6648:                     $ordered{$num} = $item;
 6649:                 }
 6650:             }
 6651:         }
 6652:         $maxnum = scalar(keys(%ordered));
 6653:         my %lt = &lti_names();
 6654:         if (keys(%ordered)) {
 6655:             my @items = sort { $a <=> $b } keys(%ordered);
 6656:             for (my $i=0; $i<@items; $i++) {
 6657:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6658:                 my $item = $ordered{$items[$i]};
 6659:                 my ($key,$secret,$lifetime,$consumer,$requser,$crsinc,$current);
 6660:                 if (ref($settings->{$item}) eq 'HASH') {
 6661:                     $key = $settings->{$item}->{'key'};
 6662:                     $secret = $settings->{$item}->{'secret'};
 6663:                     $lifetime = $settings->{$item}->{'lifetime'};
 6664:                     $consumer = $settings->{$item}->{'consumer'};
 6665:                     $requser = $settings->{$item}->{'requser'};
 6666:                     $crsinc = $settings->{$item}->{'crsinc'};
 6667:                     $current = $settings->{$item};
 6668:                 }
 6669:                 my $onclickrequser = ' onclick="toggleLTI(this.form,'."'requser','$i'".');"';
 6670:                 my %checkedrequser = (
 6671:                                        yes => ' checked="checked"',
 6672:                                        no  => '',
 6673:                                      );
 6674:                 if (!$requser) {
 6675:                     $checkedrequser{'no'} = $checkedrequser{'yes'};
 6676:                     $checkedrequser{'yes'} = '';
 6677:                 }
 6678:                 my $onclickcrsinc = ' onclick="toggleLTI(this.form,'."'crsinc','$i'".');"';
 6679:                 my %checkedcrsinc = (
 6680:                                       yes => ' checked="checked"',
 6681:                                       no  => '',
 6682:                                     );
 6683:                 if (!$crsinc) {
 6684:                     $checkedcrsinc{'no'} = $checkedcrsinc{'yes'};
 6685:                     $checkedcrsinc{'yes'} = '';
 6686:                 }
 6687:                 my $chgstr = ' onchange="javascript:reorderLTI(this.form,'."'lti_pos_".$item."'".');"';
 6688:                 $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 6689:                              .'<select name="lti_pos_'.$item.'"'.$chgstr.'>';
 6690:                 for (my $k=0; $k<=$maxnum; $k++) {
 6691:                     my $vpos = $k+1;
 6692:                     my $selstr;
 6693:                     if ($k == $i) {
 6694:                         $selstr = ' selected="selected" ';
 6695:                     }
 6696:                     $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 6697:                 }
 6698:                 $datatable .= '</select>'.('&nbsp;'x2).
 6699:                     '<label><input type="checkbox" name="lti_del" value="'.$item.'" />'.
 6700:                     &mt('Delete?').'</label></span></td>'.
 6701:                     '<td colspan="2">'.
 6702:                     '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 6703:                     '<span class="LC_nobreak">'.$lt{'consumer'}.
 6704:                     ':<input type="text" size="15" name="lti_consumer_'.$i.'" value="'.$consumer.'" /></span> '.
 6705:                     ('&nbsp;'x2).
 6706:                     '<span class="LC_nobreak">'.$lt{'version'}.':<select name="lti_version_'.$i.'">'.
 6707:                     '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '.
 6708:                     ('&nbsp;'x2).
 6709:                     '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" name="lti_lifetime_'.$i.'"'.
 6710:                     'value="'.$lifetime.'" size="3" /></span>'.
 6711:                     ('&nbsp;'x2).
 6712:                     '<span class="LC_nobreak">'.$lt{'requser'}.':'.
 6713:                     '<label><input type="radio" name="lti_requser_'.$i.'" value="1"'.$onclickrequser.$checkedrequser{yes}.' />'.&mt('Yes').'</label>&nbsp;'."\n".
 6714:                     '<label><input type="radio" name="lti_requser_'.$i.'" value="0"'.$onclickrequser.$checkedrequser{no}.' />'.&mt('No').'</label></span>'."\n".
 6715:                     '<br /><br />'.
 6716:                     '<span class="LC_nobreak">'.$lt{'crsinc'}.':'.
 6717:                     '<label><input type="radio" name="lti_crsinc_'.$i.'" value="1"'.$onclickcrsinc.$checkedcrsinc{yes}.' />'.&mt('Yes').'</label>&nbsp;'."\n".
 6718:                     '<label><input type="radio" name="lti_crsinc_'.$i.'" value="0"'.$onclickcrsinc.$checkedcrsinc{no}.' />'.&mt('No').'</label></span>'."\n".
 6719:                     ('&nbsp;'x4).
 6720:                     '<span class="LC_nobreak">'.$lt{'key'}.
 6721:                     ':<input type="text" size="25" name="lti_key_'.$i.'" value="'.$key.'" /></span> '.
 6722:                     ('&nbsp;'x2).
 6723:                     '<span class="LC_nobreak">'.$lt{'secret'}.':'.
 6724:                     '<input type="password" size="20" name="lti_secret_'.$i.'" value="'.$secret.'" />'.
 6725:                     '<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.lti_secret_'.$i.'.type='."'text'".' } else { this.form.lti_secret_'.$i.'.type='."'password'".' }" />'.&mt('Visible input').'</label>'.
 6726:                     '<input type="hidden" name="lti_id_'.$i.'" value="'.$item.'" /></span>'.
 6727:                     '</fieldset>'.&lti_options($i,$current,$itemcount,%lt).'</td></tr>';
 6728:                 $itemcount ++;
 6729:             }
 6730:         }
 6731:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6732:         my $chgstr = ' onchange="javascript:reorderLTI(this.form,'."'lti_pos_add'".');"';
 6733:         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 6734:                       '<input type="hidden" name="lti_maxnum" value="'.$maxnum.'" />'."\n".
 6735:                       '<select name="lti_pos_add"'.$chgstr.'>';
 6736:         for (my $k=0; $k<$maxnum+1; $k++) {
 6737:             my $vpos = $k+1;
 6738:             my $selstr;
 6739:             if ($k == $maxnum) {
 6740:                 $selstr = ' selected="selected" ';
 6741:             }
 6742:             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 6743:         }
 6744:         $datatable .= '</select>&nbsp;'."\n".
 6745:                       '<input type="checkbox" name="lti_add" value="1" />'.&mt('Add').'</span></td>'."\n".
 6746:                       '<td colspan="2">'.
 6747:                       '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 6748:                       '<span class="LC_nobreak">'.$lt{'consumer'}.
 6749:                       ':<input type="text" size="15" name="lti_consumer_add" value="" /></span> '."\n".
 6750:                       ('&nbsp;'x2).
 6751:                       '<span class="LC_nobreak">'.$lt{'version'}.':<select name="lti_version_add">'.
 6752:                       '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '."\n".
 6753:                       ('&nbsp;'x2).
 6754:                       '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" size="3" name="lti_lifetime_add" value="300" /></span> '."\n".
 6755:                       ('&nbsp;'x2).
 6756:                       '<span class="LC_nobreak">'.$lt{'requser'}.':'.
 6757:                       '<label><input type="radio" name="lti_requser_add" value="1" onclick="toggleLTI(this.form,'."'requser','add'".');" checked="checked" />'.&mt('Yes').'</label>&nbsp;'."\n".
 6758:                       '<label><input type="radio" name="lti_requser_add" value="0" onclick="toggleLTI(this.form,'."'requser','add'".');" />'.&mt('No').'</label></span>'."\n".
 6759:                       '<br /><br />'.
 6760:                       '<span class="LC_nobreak">'.$lt{'crsinc'}.':'.
 6761:                       '<label><input type="radio" name="lti_crsinc_add" value="1" onclick="toggleLTI(this.form,'."'crsinc','add'".');" checked="checked" />'.&mt('Yes').'</label>&nbsp;'."\n".
 6762:                       '<label><input type="radio" name="lti_crsinc_add" value="0" onclick="toggleLTI(this.form,'."'crsinc','add'".');" />'.&mt('No').'</label></span>'."\n".
 6763:                       ('&nbsp;'x4).
 6764:                       '<span class="LC_nobreak">'.$lt{'key'}.':<input type="text" size="25" name="lti_key_add" value="" /></span> '."\n".
 6765:                       ('&nbsp;'x2).
 6766:                       '<span class="LC_nobreak">'.$lt{'secret'}.':<input type="password" size="20" name="lti_secret_add" value="" />'.
 6767:                       '<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.lti_secret_add.type='."'text'".' } else { this.form.lti_secret_add.type='."'password'".' }" />'.&mt('Visible input').'</label></span> '."\n".
 6768:                       '</fieldset>'.&lti_options('add',undef,$itemcount,%lt).
 6769:                       '</td>'."\n".
 6770:                       '</tr>'."\n";
 6771:         $itemcount ++;
 6772:     }
 6773:     $$rowtotal += $itemcount;
 6774:     return $datatable;
 6775: }
 6776: 
 6777: sub lti_names {
 6778:     my %lt = &Apache::lonlocal::texthash(
 6779:                                           'version'   => 'LTI Version',
 6780:                                           'url'       => 'URL',
 6781:                                           'key'       => 'Key',
 6782:                                           'lifetime'  => 'Nonce lifetime (s)',
 6783:                                           'consumer'  => 'Consumer',
 6784:                                           'secret'    => 'Secret',
 6785:                                           'requser'   => "User's identity sent",
 6786:                                           'crsinc'    => "Course's identity sent",
 6787:                                           'email'     => 'Email address',
 6788:                                           'sourcedid' => 'User ID',
 6789:                                           'other'     => 'Other',
 6790:                                           'passback'  => 'Can return grades to Consumer:',
 6791:                                           'roster'    => 'Can retrieve roster from Consumer:',
 6792:                                           'topmenu'   => 'Display LON-CAPA page header',
 6793:                                           'inlinemenu'=> 'Display LON-CAPA inline menu',
 6794:                                         );
 6795:     return %lt;
 6796: }
 6797: 
 6798: sub lti_options {
 6799:     my ($num,$current,$itemcount,%lt) = @_;
 6800:     my (%checked,%rolemaps,$crssecsrc,$userfield,$cidfield,$callback);
 6801:     $checked{'mapuser'}{'sourcedid'} = ' checked="checked"';
 6802:     $checked{'mapcrs'}{'course_offering_sourcedid'} = ' checked="checked"';
 6803:     $checked{'storecrs'}{'Y'} = ' checked="checked"';
 6804:     $checked{'makecrs'}{'N'} = ' checked="checked"';
 6805:     $checked{'mapcrstype'} = {};
 6806:     $checked{'makeuser'} = {};
 6807:     $checked{'selfenroll'} = {};
 6808:     $checked{'crssec'} = {};
 6809:     $checked{'crssecsrc'} = {};
 6810:     $checked{'lcauth'} = {};
 6811:     $checked{'menuitem'} = {};
 6812:     if ($num eq 'add') {
 6813:         $checked{'lcauth'}{'lti'} = ' checked="checked"';
 6814:     }
 6815:     my $userfieldsty = 'none';
 6816:     my $crsfieldsty = 'none';
 6817:     my $crssecfieldsty = 'none';
 6818:     my $secsrcfieldsty = 'none';
 6819:     my $callbacksty = 'none';
 6820:     my $passbacksty = 'none';
 6821:     my $optionsty = 'block';
 6822:     my $crssty = 'block';
 6823:     my $lcauthparm;
 6824:     my $lcauthparmstyle = 'display:none';
 6825:     my $lcauthparmtext;
 6826:     my $menusty;
 6827:     my $numinrow = 4;
 6828:     my %menutitles = &ltimenu_titles();
 6829: 
 6830:     if (ref($current) eq 'HASH') {
 6831:         if (!$current->{'requser'}) {
 6832:             $optionsty = 'none';
 6833:             $crssty = 'none';
 6834:         } elsif (!$current->{'crsinc'}) {
 6835:             $crssty = 'none';
 6836:         }
 6837:         if (($current->{'mapuser'} ne '') && ($current->{'mapuser'} ne 'lis_person_sourcedid')) {
 6838:             $checked{'mapuser'}{'sourcedid'} = '';
 6839:             if ($current->{'mapuser'} eq 'lis_person_contact_email_primary') {
 6840:                 $checked{'mapuser'}{'email'} = ' checked="checked"'; 
 6841:             } else {
 6842:                 $checked{'mapuser'}{'other'} = ' checked="checked"';
 6843:                 $userfield = $current->{'mapuser'};
 6844:                 $userfieldsty = 'inline-block';
 6845:             }
 6846:         }
 6847:         if (($current->{'mapcrs'} ne '') && ($current->{'mapcrs'} ne 'course_offering_sourcedid')) {
 6848:             $checked{'mapcrs'}{'course_offering_sourcedid'} = '';
 6849:             if ($current->{'mapcrs'} eq 'context_id') {
 6850:                 $checked{'mapcrs'}{'context_id'} = ' checked="checked"'; 
 6851:             } else {
 6852:                 $checked{'mapcrs'}{'other'} = ' checked="checked"';
 6853:                 $cidfield = $current->{'mapcrs'};
 6854:                 $crsfieldsty = 'inline-block';
 6855:             }
 6856:         }
 6857:         if (ref($current->{'mapcrstype'}) eq 'ARRAY') {
 6858:             foreach my $type (@{$current->{'mapcrstype'}}) {
 6859:                 $checked{'mapcrstype'}{$type} = ' checked="checked"';
 6860:             }
 6861:         }
 6862:         if (!$current->{'storecrs'}) {
 6863:             $checked{'storecrs'}{'N'} = $checked{'storecrs'}{'Y'};
 6864:             $checked{'storecrs'}{'Y'} = '';
 6865:         }
 6866:         if ($current->{'makecrs'}) {
 6867:             $checked{'makecrs'}{'Y'} = '  checked="checked"';
 6868:         }
 6869:         if (ref($current->{'makeuser'}) eq 'ARRAY') {
 6870:             foreach my $role (@{$current->{'makeuser'}}) {
 6871:                 $checked{'makeuser'}{$role} = ' checked="checked"';
 6872:             }
 6873:         }
 6874:         if ($current->{'lcauth'} =~ /^(internal|localauth|krb4|krb5|lti)$/) {
 6875:             $checked{'lcauth'}{$1} = ' checked="checked"';
 6876:             unless (($current->{'lcauth'} eq 'lti') || ($current->{'lcauth'} eq 'internal')) {
 6877:                 $lcauthparm = $current->{'lcauthparm'};
 6878:                 $lcauthparmstyle = 'display:table-row'; 
 6879:                 if ($current->{'lcauth'} eq 'localauth') {
 6880:                     $lcauthparmtext = &mt('Local auth argument');
 6881:                 } else {
 6882:                     $lcauthparmtext = &mt('Kerberos domain');
 6883:                 }
 6884:             }
 6885:         }
 6886:         if (ref($current->{'selfenroll'}) eq 'ARRAY') {
 6887:             foreach my $role (@{$current->{'selfenroll'}}) {
 6888:                 $checked{'selfenroll'}{$role} = ' checked="checked"';
 6889:             }
 6890:         }
 6891:         if (ref($current->{'maproles'}) eq 'HASH') {
 6892:             %rolemaps = %{$current->{'maproles'}};
 6893:         }
 6894:         if ($current->{'section'} ne '') {
 6895:             $checked{'crssec'}{'Y'} = '  checked="checked"'; 
 6896:             $crssecfieldsty = 'inline-block';
 6897:             if ($current->{'section'} eq 'course_section_sourcedid') {
 6898:                 $checked{'crssecsrc'}{'sourcedid'} = ' checked="checked"';
 6899:             } else {
 6900:                 $checked{'crssecsrc'}{'other'} = ' checked="checked"';
 6901:                 $crssecsrc = $current->{'section'};
 6902:                 $secsrcfieldsty = 'inline-block';
 6903:             }
 6904:         } else {
 6905:             $checked{'crssec'}{'N'} = ' checked="checked"';
 6906:         }
 6907:         if ($current->{'callback'} ne '') {
 6908:             $callback = $current->{'callback'};
 6909:             $checked{'callback'}{'Y'} = ' checked="checked"';
 6910:             $callbacksty = 'inline-block';
 6911:         } else {
 6912:             $checked{'callback'}{'N'} = ' checked="checked"';
 6913:         }
 6914:         if ($current->{'topmenu'}) {
 6915:             $checked{'topmenu'}{'Y'} = ' checked="checked"';
 6916:         } else {
 6917:             $checked{'topmenu'}{'N'} = ' checked="checked"';
 6918:         }
 6919:         if ($current->{'inlinemenu'}) {
 6920:             $checked{'inlinemenu'}{'Y'} = ' checked="checked"';
 6921:         } else {
 6922:             $checked{'inlinemenu'}{'N'} = ' checked="checked"';
 6923:         }
 6924:         if (($current->{'topmenu'}) || ($current->{'inlinemenu'})) {
 6925:             $menusty = 'inline-block';
 6926:             if (ref($current->{'lcmenu'}) eq 'ARRAY') {
 6927:                 foreach my $item (@{$current->{'lcmenu'}}) {
 6928:                     if (exists($menutitles{$item})) {
 6929:                         $checked{'menuitem'}{$item} = ' checked="checked"';
 6930:                     }
 6931:                 }
 6932:             }
 6933:         } else {
 6934:             $menusty = 'none';
 6935:         }
 6936:     } else {
 6937:         $checked{'makecrs'}{'N'} = ' checked="checked"';
 6938:         $checked{'crssec'}{'N'} = ' checked="checked"';
 6939:         $checked{'callback'}{'N'} = ' checked="checked"';
 6940:         $checked{'topmenu'}{'N'} = ' checked="checked"';
 6941:         $checked{'inlinemenu'}{'Y'} = ' checked="checked"'; 
 6942:         $checked{'menuitem'}{'grades'} = ' checked="checked"';
 6943:         $menusty = 'inline-block'; 
 6944:     }
 6945:     my @coursetypes = ('official','unofficial','community','textbook','placement','lti');
 6946:     my %coursetypetitles = &Apache::lonlocal::texthash (
 6947:                                official   => 'Official',
 6948:                                unofficial => 'Unofficial',
 6949:                                community  => 'Community',
 6950:                                textbook   => 'Textbook',
 6951:                                placement  => 'Placement Test',
 6952:                                lti        => 'LTI Provider',
 6953:     );
 6954:     my @authtypes = ('internal','krb4','krb5','localauth');
 6955:     my %shortauth = (
 6956:                      internal => 'int',
 6957:                      krb4 => 'krb4',
 6958:                      krb5 => 'krb5',
 6959:                      localauth  => 'loc'
 6960:                     );
 6961:     my %authnames = &authtype_names();
 6962:     my @ltiroles = qw(Learner Instructor ContentDeveloper TeachingAssistant Mentor Member Manager Administrator);
 6963:     my @lticourseroles = qw(Learner Instructor TeachingAssistant Mentor);
 6964:     my @courseroles = ('cc','in','ta','ep','st');
 6965:     my $onclickuser = ' onclick="toggleLTI(this.form,'."'user','$num'".');"';
 6966:     my $onclickcrs = ' onclick="toggleLTI(this.form,'."'crs','$num'".');"';
 6967:     my $onclicksec = ' onclick="toggleLTI(this.form,'."'sec','$num'".');"';
 6968:     my $onclickcallback = ' onclick="toggleLTI(this.form,'."'callback','$num'".');"';
 6969:     my $onclicksecsrc = ' onclick="toggleLTI(this.form,'."'secsrc','$num'".')"';
 6970:     my $onclicklcauth = ' onclick="toggleLTI(this.form,'."'lcauth','$num'".')"';
 6971:     my $onclickmenu = ' onclick="toggleLTI(this.form,'."'lcmenu','$num'".');"';
 6972:     my $output = '<fieldset class="ltioption_usr_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Logout options').'</legend>'.
 6973:                  '<div class="LC_floatleft"><span class="LC_nobreak">'.&mt('Callback to logout LON-CAPA on log out from Consumer').':&nbsp;'.
 6974:                  '<label><input type="radio" name="lti_callback_'.$num.'" value="0"'.
 6975:                  $checked{'callback'}{'N'}.$onclickcallback.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 6976:                  '<label><input type="radio" name="lti_callback_'.$num.'" value="1"'.
 6977:                  $checked{'callback'}{'Y'}.$onclickcallback.' />'.&mt('Yes').'</label></span></div>'.
 6978:                  '<div class="LC_floatleft" style="display:'.$callbacksty.';" id="lti_callbackfield_'.$num.'">'.
 6979:                  '<span class="LC_nobreak">'.&mt('Parameter').': '.
 6980:                  '<input type="text" name="lti_callbackparam_'.$num.'" value="'.$callback.'" /></span>'.
 6981:                  '</div><div style="padding:0;clear:both;margin:0;border:0"></div></fieldset>'.
 6982:                  '<fieldset class="ltioption_usr_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Mapping users').'</legend>'.
 6983:                  '<div class="LC_floatleft"><span class="LC_nobreak">'.&mt('LON-CAPA username').':&nbsp;';
 6984:     foreach my $option ('sourcedid','email','other') {
 6985:         $output .= '<label><input type="radio" name="lti_mapuser_'.$num.'" value="'.$option.'"'.
 6986:                    $checked{'mapuser'}{$option}.$onclickuser.' />'.$lt{$option}.'</label>'.
 6987:                    ($option eq 'other' ? '' : ('&nbsp;'x2) );
 6988:     }
 6989:     $output .= '</span></div>'.
 6990:                '<div class="LC_floatleft" style="display:'.$userfieldsty.';" id="lti_userfield_'.$num.'">'.
 6991:                '<input type="text" name="lti_customuser_'.$num.'" '.
 6992:                'value="'.$userfield.'" /></div></fieldset>'.
 6993:                '<fieldset class="ltioption_usr_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Roles which may create user accounts').'</legend>';
 6994:     foreach my $ltirole (@ltiroles) {
 6995:         $output .= '<span class="LC_nobreak"><label><input type="checkbox" name="lti_makeuser_'.$num.'" value="'.$ltirole.'"'.
 6996:                    $checked{'makeuser'}{$ltirole}.' />'.$ltirole.'</label>&nbsp;</span> ';     
 6997:     }
 6998:     $output .= '</fieldset>'.
 6999:                '<fieldset class="ltioption_usr_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('New user accounts created for LTI users').'</legend>'.
 7000:                '<table>'.
 7001:                &modifiable_userdata_row('lti','instdata_'.$num,$current,$numinrow,$itemcount).
 7002:                '</table>'.
 7003:                '<table class="LC_nested"><tr><td class="LC_left_item">LON-CAPA Authentication</td>'.
 7004:                '<td class="LC_left_item">';
 7005:     foreach my $auth ('lti',@authtypes) {
 7006:         my $authtext;
 7007:         if ($auth eq 'lti') {
 7008:             $authtext = &mt('None');
 7009:         } else {
 7010:             $authtext = $authnames{$shortauth{$auth}};
 7011:         }
 7012:         $output .= '<span class="LC_nobreak"><label><input type="radio" name="lti_lcauth_'.$num.
 7013:                    '" value="'.$auth.'"'.$checked{'lcauth'}{$auth}.$onclicklcauth.' />'.
 7014:                    $authtext.'</label></span> &nbsp;';
 7015:     }
 7016:     $output .= '</td></tr>'.
 7017:                '<tr id="lti_lcauth_parmrow_'.$num.'" style="'.$lcauthparmstyle.'">'.
 7018:                '<td class="LC_right_item" colspan="2"><span class="LC_nobreak">'.
 7019:                '<span id="lti_lcauth_parmtext_'.$num.'">'.$lcauthparmtext.'</span>'.
 7020:                '<input type="text" name="lti_lcauthparm_'.$num.'" value="" /></span></td></tr>'.
 7021:                '</table></fieldset>'.
 7022:                '<fieldset class="ltioption_usr_'.$num.'" style="display:'.$optionsty.'"><legend>'.
 7023:                &mt('LON-CAPA menu items (Course Coordinator can override)').'</legend>'.
 7024:                '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{'topmenu'}.':&nbsp;'.
 7025:                '<label><input type="radio" name="lti_topmenu_'.$num.'" value="0"'.
 7026:                $checked{'topmenu'}{'N'}.$onclickmenu.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 7027:                '<label><input type="radio" name="lti_topmenu_'.$num.'" value="1"'.
 7028:                $checked{'topmenu'}{'Y'}.$onclickmenu.' />'.&mt('Yes').'</label></span></div>'.
 7029:                '<div style="padding:0;clear:both;margin:0;border:0"></div>'.
 7030:                '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{'inlinemenu'}.':&nbsp;'.
 7031:                '<label><input type="radio" name="lti_inlinemenu_'.$num.'" value="0"'.
 7032:                $checked{'inlinemenu'}{'N'}.$onclickmenu.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 7033:                '<label><input type="radio" name="lti_inlinemenu_'.$num.'" value="1"'.
 7034:                $checked{'inlinemenu'}{'Y'}.$onclickmenu.' />'.&mt('Yes').'</label></span></div>';
 7035:      $output .='<div style="padding:0;clear:both;margin:0;border:0"></div>'.
 7036:                '<div class="LC_floatleft" style="display:'.$menusty.';" id="lti_menufield_'.$num.'">'.
 7037:                '<span class="LC_nobreak">'.&mt('Menu items').':&nbsp;';
 7038:     foreach my $type ('fullname','coursetitle','role','logout','grades') {
 7039:         $output .= '<label><input type="checkbox" name="lti_menuitem_'.$num.'" value="'.$type.'"'.
 7040:                    $checked{'menuitem'}{$type}.' />'.$menutitles{$type}.'</label>'.
 7041:                    ('&nbsp;'x2);
 7042:     }
 7043:     $output .= '</span></div></fieldset>'.
 7044:                '<fieldset class="ltioption_crs_'.$num.'" style="display:'.$crssty.'"><legend>'.&mt('Mapping courses').'</legend>'.
 7045:                '<div class="LC_floatleft"><span class="LC_nobreak">'.
 7046:                &mt('Unique course identifier').':&nbsp;';
 7047:     foreach my $option ('course_offering_sourcedid','context_id','other') {
 7048:         $output .= '<label><input type="radio" name="lti_mapcrs_'.$num.'" value="'.$option.'"'.
 7049:                    $checked{'mapcrs'}{$option}.$onclickcrs.' />'.$option.'</label>'.
 7050:                    ($option eq 'other' ? '' : ('&nbsp;'x2) );
 7051:     }
 7052:     $output .= '</span></div><div class="LC_floatleft" style="display:'.$crsfieldsty.';" id="lti_crsfield_'.$num.'">'.
 7053:                '<input type="text" name="lti_mapcrsfield_'.$num.'" value="'.$cidfield.'" />'.
 7054:                '</div><div style="padding:0;clear:both;margin:0;border:0"></div>'.
 7055:                '<span class="LC_nobreak">'.&mt('LON-CAPA course type(s)').':&nbsp;';
 7056:     foreach my $type (@coursetypes) {
 7057:         $output .= '<label><input type="checkbox" name="lti_mapcrstype_'.$num.'" value="'.$type.'"'.
 7058:                    $checked{'mapcrstype'}{$type}.' />'.$coursetypetitles{$type}.'</label>'.
 7059:                    ('&nbsp;'x2);
 7060:     }
 7061:     $output .= '</span><br /><br />'.
 7062:                '<span class="LC_nobreak">'.&mt('Store mapping of course identifier to LON-CAPA CourseID').':&nbsp;'.
 7063:                '<label><input type="radio" name="lti_storecrs_'.$num.'" value="0"'.
 7064:                $checked{'storecrs'}{'N'}.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 7065:                '<label><input type="radio" name="lti_storecrs_'.$num.'" value="1"'.
 7066:                $checked{'storecrs'}{'Y'}.' />'.&mt('Yes').'</label></span>'.
 7067:                '</fieldset>'.
 7068:                '<fieldset class="ltioption_crs_'.$num.'" style="display:'.$crssty.'"><legend>'.&mt('Mapping course roles').'</legend><table><tr>';
 7069:     foreach my $ltirole (@lticourseroles) {
 7070:         my ($selected,$selectnone);
 7071:         if ($rolemaps{$ltirole} eq '') {
 7072:             $selectnone = ' selected="selected"';
 7073:         }
 7074:         $output .= '<td style="text-align: center">'.$ltirole.'<br />'.
 7075:                    '<select name="lti_maprole_'.$ltirole.'_'.$num.'">'.
 7076:                    '<option value=""'.$selectnone.'>'.&mt('Select').'</option>';
 7077:         foreach my $role (@courseroles) {
 7078:             unless ($selectnone) {
 7079:                 if ($rolemaps{$ltirole} eq $role) {
 7080:                     $selected = ' selected="selected"';
 7081:                 } else {
 7082:                     $selected = '';
 7083:                 }
 7084:             }
 7085:             $output .= '<option value="'.$role.'"'.$selected.'>'.
 7086:                        &Apache::lonnet::plaintext($role,'Course').
 7087:                        '</option>';
 7088:         }
 7089:         $output .= '</select></td>';
 7090:     }
 7091:     $output .= '</tr></table></fieldset>'.
 7092:                '<fieldset class="ltioption_crs_'.$num.'" style="display:'.$crssty.'"><legend>'.&mt('Creating courses').'</legend>'.
 7093:                '<span class="LC_nobreak">'.&mt('Course created (if absent) on Instructor access').':&nbsp;'.
 7094:                '<label><input type="radio" name="lti_makecrs_'.$num.'" value="0"'.
 7095:                $checked{'makecrs'}{'N'}.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 7096:                '<label><input type="radio" name="lti_makecrs_'.$num.'" value="1"'.
 7097:                $checked{'makecrs'}{'Y'}.' />'.&mt('Yes').'</label></span>'.
 7098:                '</fieldset>'.
 7099:                '<fieldset class="ltioption_crs_'.$num.'" style="display:'.$crssty.'"><legend>'.&mt('Roles which may self-enroll').'</legend>';
 7100:     foreach my $lticrsrole (@lticourseroles) {
 7101:         $output .= '<span class="LC_nobreak"><label><input type="checkbox" name="lti_selfenroll_'.$num.'" value="'.$lticrsrole.'"'.
 7102:                    $checked{'selfenroll'}{$lticrsrole}.' />'.$lticrsrole.'</label>&nbsp;</span> ';
 7103:     }
 7104:     $output .= '</fieldset>'.
 7105:                '<fieldset class="ltioption_crs_'.$num.'" style="display:'.$crssty.'"><legend>'.&mt('Course options').'</legend>'.
 7106:                '<div class="LC_floatleft"><span class="LC_nobreak">'.&mt('Assign users to sections').':&nbsp;'.
 7107:                '<label><input type="radio" name="lti_crssec_'.$num.'" value="0"'.
 7108:                $checked{'crssec'}{'N'}.$onclicksec.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 7109:                '<label><input type="radio" name="lti_crssec_'.$num.'" value="1"'.
 7110:                $checked{'crssec'}{'Y'}.$onclicksec.' />'.&mt('Yes').'</label></span></div>'.
 7111:                '<div class="LC_floatleft" style="display:'.$crssecfieldsty.';" id="lti_crssecfield_'.$num.'">'.
 7112:                '<span class="LC_nobreak">'.&mt('From').':<label>'.
 7113:                '<input type="radio" name="lti_crssecsrc_'.$num.'" value="course_section_sourcedid"'.
 7114:                $checked{'crssecsrc'}{'sourcedid'}.$onclicksecsrc.' />'.
 7115:                &mt('Standard field').'</label>'.('&nbsp;'x2).
 7116:                '<label><input type="radio" name="lti_crssecsrc_'.$num.'" value="other"'.
 7117:                $checked{'crssecsrc'}{'other'}.$onclicksecsrc.' />'.&mt('Other').
 7118:                '</label></span></div><div class="LC_floatleft" style="display:'.$secsrcfieldsty.';" id="lti_secsrcfield_'.$num.'">'.
 7119:                '<input type="text" name="lti_customsection_'.$num.'" value="'.$crssecsrc.'" />'.
 7120:                '</div><div style="padding:0;clear:both;margin:0;border:0"></div>';
 7121:     my ($pb1p1chk,$pb1p0chk,$onclickpb);
 7122:     foreach my $extra ('roster','passback') {
 7123:         my $checkedon = '';
 7124:         my $checkedoff = ' checked="checked"';
 7125:         if ($extra eq 'passback') {
 7126:             $pb1p1chk = ' checked="checked"';
 7127:             $pb1p0chk = '';
 7128:             $onclickpb = ' onclick="toggleLTI(this.form,'."'passback','$num'".');"'; 
 7129:         } else {
 7130:             $onclickpb = ''; 
 7131:         }
 7132:         if (ref($current) eq 'HASH') {
 7133:             if (($current->{$extra})) {
 7134:                 $checkedon = $checkedoff;
 7135:                 $checkedoff = '';
 7136:                 if ($extra eq 'passback') {
 7137:                     $passbacksty = 'inline-block';
 7138:                 }
 7139:                 if ($current->{'passbackformat'} eq '1.0') {
 7140:                     $pb1p0chk =  ' checked="checked"';
 7141:                     $pb1p1chk = '';
 7142:                 }
 7143:             }
 7144:         }
 7145:         $output .= $lt{$extra}.'&nbsp;'.
 7146:                    '<label><input type="radio" name="lti_'.$extra.'_'.$num.'" value="0"'.$checkedoff.$onclickpb.' />'.
 7147:                    &mt('No').'</label>'.('&nbsp;'x2).
 7148:                    '<label><input type="radio" name="lti_'.$extra.'_'.$num.'" value="1"'.$checkedon.$onclickpb.' />'.
 7149:                    &mt('Yes').'</label><br />';
 7150:     }
 7151:     $output .= '<div class="LC_floatleft" style="display:'.$passbacksty.';" id="lti_passback_'.$num.'">'.
 7152:                '<span class="LC_nobreak">'.&mt('Grade format').
 7153:                '<label><input type="radio" name="lti_passbackformat_'.$num.'" value="1.1"'.$pb1p1chk.' />'.
 7154:                &mt('Outcomes Service (1.1)').'</label>'.('&nbsp;'x2).
 7155:                '<label><input type="radio" name="lti_passbackformat_'.$num.'" value="1.0"'.$pb1p0chk.'/>'.
 7156:                &mt('Outcomes Extension (1.0)').'</label></span></div>'.
 7157:                '<div style="padding:0;clear:both;margin:0;border:0"></div></fieldset>';
 7158:     $output .= '</span></div></fieldset>';
 7159: #        '<fieldset><legend>'.&mt('Assigning author roles').'</legend>';
 7160: #
 7161: #    $output .= '</fieldset>'.
 7162: #        '<fieldset><legend>'.&mt('Assigning domain roles').'</legend>';
 7163:     return $output;
 7164: }
 7165: 
 7166: sub ltimenu_titles {
 7167:     return &Apache::lonlocal::texthash(
 7168:                                         fullname    => 'Full name',
 7169:                                         coursetitle => 'Course title',
 7170:                                         role        => 'Role',
 7171:                                         logout      => 'Logout',
 7172:                                         grades      => 'Grades',
 7173:     );
 7174: }
 7175: 
 7176: sub check_switchserver {
 7177:     my ($home) = @_;
 7178:     my $switchserver;
 7179:     if ($home ne '') {
 7180:         my $allowed;
 7181:         my @ids=&Apache::lonnet::current_machine_ids();
 7182:         foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
 7183:         if (!$allowed) {
 7184:             $switchserver='<a href="/adm/switchserver?otherserver='.$home.'&amp;role='.
 7185:                           &HTML::Entities::encode($env{'request.role'},'\'<>"&').
 7186:                           '&amp;destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
 7187:         }
 7188:     }
 7189:     return $switchserver;
 7190: }
 7191: 
 7192: sub print_coursedefaults {
 7193:     my ($position,$dom,$settings,$rowtotal) = @_;
 7194:     my ($css_class,$datatable,%checkedon,%checkedoff,%defaultchecked,@toggles);
 7195:     my $itemcount = 1;
 7196:     my %choices =  &Apache::lonlocal::texthash (
 7197:         canuse_pdfforms      => 'Course/Community users can create/upload PDF forms',
 7198:         uploadquota          => 'Default quota for files uploaded directly to course/community using Course Editor (MB)',
 7199:         anonsurvey_threshold => 'Responder count needed before showing submissions for anonymous surveys',
 7200:         coursecredits        => 'Credits can be specified for courses',
 7201:         uselcmath            => 'Math preview uses LON-CAPA previewer (javascript) in place of DragMath (Java)',
 7202:         usejsme              => 'Molecule editor uses JSME (HTML5) in place of JME (Java)',
 7203:         inline_chem          => 'Use inline previewer for chemical reaction response in place of pop-up',
 7204:         texengine            => 'Default method to display mathematics',
 7205:         postsubmit           => 'Disable submit button/keypress following student submission',
 7206:         canclone             => "People who may clone a course (besides course's owner and coordinators)",
 7207:         mysqltables          => 'Lifetime (s) of "Temporary" MySQL tables (student performance data) on homeserver',
 7208:         ltiauth              => 'Student username in LTI launch of deep-linked URL can be accepted without re-authentication',
 7209:     );
 7210:     my %staticdefaults = (
 7211:                            anonsurvey_threshold => 10,
 7212:                            uploadquota          => 500,
 7213:                            postsubmit           => 60,
 7214:                            mysqltables          => 172800,
 7215:                          );
 7216:     if ($position eq 'top') {
 7217:         %defaultchecked = (
 7218:                             'canuse_pdfforms' => 'off',
 7219:                             'uselcmath'       => 'on',
 7220:                             'usejsme'         => 'on',
 7221:                             'inline_chem'     => 'on',
 7222:                             'canclone'        => 'none',
 7223:                           );
 7224:         @toggles = ('canuse_pdfforms','uselcmath','usejsme','inline_chem');
 7225:         my $deftex = $Apache::lonnet::deftex;
 7226:         if (ref($settings) eq 'HASH') {
 7227:             if ($settings->{'texengine'}) {
 7228:                 if ($settings->{'texengine'} =~ /^(MathJax|mimetex|tth)$/) {
 7229:                     $deftex = $settings->{'texengine'};
 7230:                 }
 7231:             }
 7232:         }
 7233:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7234:         my $mathdisp = '<tr'.$css_class.'><td style="vertical-align: top">'.
 7235:                        '<span class="LC_nobreak">'.$choices{'texengine'}.
 7236:                        '</span></td><td class="LC_right_item">'.
 7237:                        '<select name="texengine">'."\n";
 7238:         my %texoptions = (
 7239:                             MathJax  => 'MathJax',
 7240:                             mimetex  => &mt('Convert to Images'),
 7241:                             tth      => &mt('TeX to HTML'),
 7242:                          );
 7243:         foreach my $renderer ('MathJax','mimetex','tth') {
 7244:             my $selected = '';
 7245:             if ($renderer eq $deftex) {
 7246:                 $selected = ' selected="selected"';
 7247:             }
 7248:             $mathdisp .= '<option value="'.$renderer.'"'.$selected.'>'.$texoptions{$renderer}.'</option>'."\n";
 7249:         }
 7250:         $mathdisp .= '</select></td></tr>'."\n";
 7251:         $itemcount ++;
 7252:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 7253:                                                      \%choices,$itemcount);
 7254:         $datatable = $mathdisp.$datatable;
 7255:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7256:         $datatable .=
 7257:             '<tr'.$css_class.'><td style="vertical-align: top">'.
 7258:             '<span class="LC_nobreak">'.$choices{'canclone'}.
 7259:             '</span></td><td class="LC_left_item">';
 7260:         my $currcanclone = 'none';
 7261:         my $onclick;
 7262:         my @cloneoptions = ('none','domain');
 7263:         my %clonetitles = &Apache::lonlocal::texthash (
 7264:                              none     => 'No additional course requesters',
 7265:                              domain   => "Any course requester in course's domain",
 7266:                              instcode => 'Course requests for official courses ...',
 7267:                           );
 7268:         my (%codedefaults,@code_order,@posscodes);
 7269:         if (&Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
 7270:                                                     \@code_order) eq 'ok') {
 7271:             if (@code_order > 0) {
 7272:                 push(@cloneoptions,'instcode');
 7273:                 $onclick = ' onclick="toggleDisplay(this.form,'."'cloneinstcode'".');"';
 7274:             }
 7275:         }
 7276:         if (ref($settings) eq 'HASH') {
 7277:             if ($settings->{'canclone'}) {
 7278:                 if (ref($settings->{'canclone'}) eq 'HASH') {
 7279:                     if (ref($settings->{'canclone'}{'instcode'}) eq 'ARRAY') {
 7280:                         if (@code_order > 0) {
 7281:                             $currcanclone = 'instcode';
 7282:                             @posscodes = @{$settings->{'canclone'}{'instcode'}};
 7283:                         }
 7284:                     }
 7285:                 } elsif ($settings->{'canclone'} eq 'domain') {
 7286:                     $currcanclone = $settings->{'canclone'};
 7287:                 }
 7288:             }
 7289:         }
 7290:         foreach my $option (@cloneoptions) {
 7291:             my ($checked,$additional);
 7292:             if ($currcanclone eq $option) {
 7293:                 $checked = ' checked="checked"';
 7294:             }
 7295:             if ($option eq 'instcode') {
 7296:                 if (@code_order) {
 7297:                     my $show = 'none';
 7298:                     if ($checked) {
 7299:                         $show = 'block';
 7300:                     }
 7301:                     $additional = '<div id="cloneinstcode" style="display:'.$show.';" />'.
 7302:                                   &mt('Institutional codes for new and cloned course have identical:').
 7303:                                   '<br />';
 7304:                     foreach my $item (@code_order) {
 7305:                         my $codechk;
 7306:                         if ($checked) {
 7307:                             if (grep(/^\Q$item\E$/,@posscodes)) {
 7308:                                 $codechk = ' checked="checked"';
 7309:                             }
 7310:                         }
 7311:                         $additional .= '<label>'.
 7312:                                        '<input type="checkbox" name="clonecode" value="'.$item.'"'.$codechk.' />'.
 7313:                                        $item.'</label>';
 7314:                     }
 7315:                     $additional .= ('&nbsp;'x2).'('.&mt('check as many as needed').')</div>';
 7316:                 }
 7317:             }
 7318:             $datatable .=
 7319:                 '<span class="LC_nobreak"><label><input type="radio" name="canclone"'.$checked.
 7320:                 ' value="'.$option.'"'.$onclick.' />'.$clonetitles{$option}.
 7321:                 '</label>&nbsp;'.$additional.'</span><br />';
 7322:         }
 7323:         $datatable .= '</td>'.
 7324:                       '</tr>';
 7325:         $itemcount ++;
 7326:     } else {
 7327:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7328:         my ($currdefresponder,%defcredits,%curruploadquota,%deftimeout,%currmysql);
 7329:         my $currusecredits = 0;
 7330:         my $postsubmitclient = 1;
 7331:         my $ltiauth = 0;
 7332:         my @types = ('official','unofficial','community','textbook','placement');
 7333:         if (ref($settings) eq 'HASH') {
 7334:             if ($settings->{'ltiauth'}) {
 7335:                 $ltiauth = 1;
 7336:             }
 7337:             $currdefresponder = $settings->{'anonsurvey_threshold'};
 7338:             if (ref($settings->{'uploadquota'}) eq 'HASH') {
 7339:                 foreach my $type (keys(%{$settings->{'uploadquota'}})) {
 7340:                     $curruploadquota{$type} = $settings->{'uploadquota'}{$type};
 7341:                 }
 7342:             }
 7343:             if (ref($settings->{'coursecredits'}) eq 'HASH') {
 7344:                 foreach my $type (@types) {
 7345:                     next if ($type eq 'community');
 7346:                     $defcredits{$type} = $settings->{'coursecredits'}->{$type};
 7347:                     if ($defcredits{$type} ne '') {
 7348:                         $currusecredits = 1;
 7349:                     }
 7350:                 }
 7351:             }
 7352:             if (ref($settings->{'postsubmit'}) eq 'HASH') {
 7353:                 if ($settings->{'postsubmit'}->{'client'} eq 'off') {
 7354:                     $postsubmitclient = 0;
 7355:                     foreach my $type (@types) {
 7356:                         $deftimeout{$type} = $staticdefaults{'postsubmit'};
 7357:                     }
 7358:                 } else {
 7359:                     foreach my $type (@types) {
 7360:                         if (ref($settings->{'postsubmit'}->{'timeout'}) eq 'HASH') {
 7361:                             if ($settings->{'postsubmit'}->{'timeout'}->{$type} =~ /^\d+$/) {
 7362:                                 $deftimeout{$type} = $settings->{'postsubmit'}->{'timeout'}->{$type};
 7363:                             } else {
 7364:                                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 7365:                             }
 7366:                         } else {
 7367:                             $deftimeout{$type} = $staticdefaults{'postsubmit'};
 7368:                         }
 7369:                     }
 7370:                 }
 7371:             } else {
 7372:                 foreach my $type (@types) {
 7373:                     $deftimeout{$type} = $staticdefaults{'postsubmit'};
 7374:                 }
 7375:             }
 7376:             if (ref($settings->{'mysqltables'}) eq 'HASH') {
 7377:                 foreach my $type (keys(%{$settings->{'mysqltables'}})) {
 7378:                     $currmysql{$type} = $settings->{'mysqltables'}{$type};
 7379:                 }
 7380:             } else {
 7381:                 foreach my $type (@types) {
 7382:                     $currmysql{$type} = $staticdefaults{'mysqltables'};
 7383:                 }
 7384:             }
 7385:         } else {
 7386:             foreach my $type (@types) {
 7387:                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 7388:             }
 7389:         }
 7390:         if (!$currdefresponder) {
 7391:             $currdefresponder = $staticdefaults{'anonsurvey_threshold'};
 7392:         } elsif ($currdefresponder < 1) {
 7393:             $currdefresponder = 1;
 7394:         }
 7395:         foreach my $type (@types) {
 7396:             if ($curruploadquota{$type} eq '') {
 7397:                 $curruploadquota{$type} = $staticdefaults{'uploadquota'};
 7398:             }
 7399:         }
 7400:         $datatable .=
 7401:                 '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 7402:                 $choices{'anonsurvey_threshold'}.
 7403:                 '</span></td>'.
 7404:                 '<td class="LC_right_item"><span class="LC_nobreak">'.
 7405:                 '<input type="text" name="anonsurvey_threshold"'.
 7406:                 ' value="'.$currdefresponder.'" size="5" /></span>'.
 7407:                 '</td></tr>'."\n";
 7408:         $itemcount ++;
 7409:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7410:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 7411:                       $choices{'uploadquota'}.
 7412:                       '</span></td>'.
 7413:                       '<td style="text-align: right" class="LC_right_item">'.
 7414:                       '<table><tr>';
 7415:         foreach my $type (@types) {
 7416:             $datatable .= '<td style="text-align: center">'.&mt($type).'<br />'.
 7417:                            '<input type="text" name="uploadquota_'.$type.'"'.
 7418:                            ' value="'.$curruploadquota{$type}.'" size="5" /></td>';
 7419:         }
 7420:         $datatable .= '</tr></table></td></tr>'."\n";
 7421:         $itemcount ++;
 7422:         my $onclick = "toggleDisplay(this.form,'credits');";
 7423:         my $display = 'none';
 7424:         if ($currusecredits) {
 7425:             $display = 'block';
 7426:         }
 7427:         my $additional = '<div id="credits" style="display: '.$display.'">'.
 7428:                          '<i>'.&mt('Default credits').'</i><br /><table><tr>';
 7429:         foreach my $type (@types) {
 7430:             next if ($type eq 'community');
 7431:             $additional .= '<td style="text-align: center">'.&mt($type).'<br />'.
 7432:                            '<input type="text" name="'.$type.'_credits"'.
 7433:                            ' value="'.$defcredits{$type}.'" size="3" /></td>';
 7434:         }
 7435:         $additional .= '</tr></table></div>'."\n";
 7436:         %defaultchecked = ('coursecredits' => 'off');
 7437:         @toggles = ('coursecredits');
 7438:         my $current = {
 7439:                         'coursecredits' => $currusecredits,
 7440:                       };
 7441:         (my $table,$itemcount) =
 7442:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 7443:                                \%choices,$itemcount,$onclick,$additional,'left');
 7444:         $datatable .= $table;
 7445:         $onclick = "toggleDisplay(this.form,'studentsubmission');";
 7446:         my $display = 'none';
 7447:         if ($postsubmitclient) {
 7448:             $display = 'block';
 7449:         }
 7450:         $additional = '<div id="studentsubmission" style="display: '.$display.'">'.
 7451:                       &mt('Number of seconds submit is disabled').'<br />'.
 7452:                       '<i>'.&mt('Enter 0 to remain disabled until page reload.').'</i><br />'.
 7453:                       '<table><tr>';
 7454:         foreach my $type (@types) {
 7455:             $additional .= '<td style="text-align: center">'.&mt($type).'<br />'.
 7456:                            '<input type="text" name="'.$type.'_timeout" value="'.
 7457:                            $deftimeout{$type}.'" size="5" /></td>';
 7458:         }
 7459:         $additional .= '</tr></table></div>'."\n";
 7460:         %defaultchecked = ('postsubmit' => 'on');
 7461:         @toggles = ('postsubmit');
 7462:         $current = {
 7463:                        'postsubmit' => $postsubmitclient,
 7464:                    };
 7465:         ($table,$itemcount) =
 7466:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 7467:                                \%choices,$itemcount,$onclick,$additional,'left');
 7468:         $datatable .= $table;
 7469:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7470:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 7471:                       $choices{'mysqltables'}.
 7472:                       '</span></td>'.
 7473:                       '<td style="text-align: right" class="LC_right_item">'.
 7474:                       '<table><tr>';
 7475:         foreach my $type (@types) {
 7476:             $datatable .= '<td style="text-align: center">'.&mt($type).'<br />'.
 7477:                            '<input type="text" name="mysqltables_'.$type.'"'.
 7478:                            ' value="'.$currmysql{$type}.'" size="8" /></td>';
 7479:         }
 7480:         $datatable .= '</tr></table></td></tr>'."\n";
 7481:         $itemcount ++;
 7482:         %defaultchecked = ('ltiauth' => 'off');
 7483:         @toggles = ('ltiauth');
 7484:         $current = {
 7485:                        'ltiauth' => $ltiauth,
 7486:                    };
 7487:         ($table,$itemcount) =
 7488:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 7489:                                \%choices,$itemcount,undef,undef,'left');
 7490:         $datatable .= $table;
 7491:         $itemcount ++;
 7492:     }
 7493:     $$rowtotal += $itemcount;
 7494:     return $datatable;
 7495: }
 7496: 
 7497: sub print_selfenrollment {
 7498:     my ($position,$dom,$settings,$rowtotal) = @_;
 7499:     my ($css_class,$datatable);
 7500:     my $itemcount = 1;
 7501:     my @types = ('official','unofficial','community','textbook','placement');
 7502:     if (($position eq 'top') || ($position eq 'middle')) {
 7503:         my ($rowsref,$titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
 7504:         my %descs = &Apache::lonuserutils::selfenroll_default_descs();
 7505:         my @rows;
 7506:         my $key;
 7507:         if ($position eq 'top') {
 7508:             $key = 'admin'; 
 7509:             if (ref($rowsref) eq 'ARRAY') {
 7510:                 @rows = @{$rowsref};
 7511:             }
 7512:         } elsif ($position eq 'middle') {
 7513:             $key = 'default';
 7514:             @rows = ('types','registered','approval','limit');
 7515:         }
 7516:         foreach my $row (@rows) {
 7517:             if (defined($titlesref->{$row})) {
 7518:                 $itemcount ++;
 7519:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7520:                 $datatable .= '<tr'.$css_class.'>'.
 7521:                               '<td>'.$titlesref->{$row}.'</td>'.
 7522:                               '<td class="LC_left_item">'.
 7523:                               '<table><tr>';
 7524:                 my (%current,%currentcap);
 7525:                 if (ref($settings) eq 'HASH') {
 7526:                     if (ref($settings->{$key}) eq 'HASH') {
 7527:                         foreach my $type (@types) {
 7528:                             if (ref($settings->{$key}->{$type}) eq 'HASH') {
 7529:                                 $current{$type} = $settings->{$key}->{$type}->{$row};
 7530:                             }
 7531:                             if (($row eq 'limit') && ($key eq 'default')) {
 7532:                                 if (ref($settings->{$key}->{$type}) eq 'HASH') {
 7533:                                     $currentcap{$type} = $settings->{$key}->{$type}->{'cap'};
 7534:                                 }
 7535:                             }
 7536:                         }
 7537:                     }
 7538:                 }
 7539:                 my %roles = (
 7540:                              '0' => &Apache::lonnet::plaintext('dc'),
 7541:                             ); 
 7542:             
 7543:                 foreach my $type (@types) {
 7544:                     unless (($row eq 'registered') && ($key eq 'default')) {
 7545:                         $datatable .= '<th>'.&mt($type).'</th>';
 7546:                     }
 7547:                 }
 7548:                 unless (($row eq 'registered') && ($key eq 'default')) {
 7549:                     $datatable .= '</tr><tr>';
 7550:                 }
 7551:                 foreach my $type (@types) {
 7552:                     if ($type eq 'community') {
 7553:                         $roles{'1'} = &mt('Community personnel');
 7554:                     } else {
 7555:                         $roles{'1'} = &mt('Course personnel');
 7556:                     }
 7557:                     $datatable .= '<td style="vertical-align: top">';
 7558:                     if ($position eq 'top') {
 7559:                         my %checked;
 7560:                         if ($current{$type} eq '0') {
 7561:                             $checked{'0'} = ' checked="checked"';
 7562:                         } else {
 7563:                             $checked{'1'} = ' checked="checked"';
 7564:                         }
 7565:                         foreach my $role ('1','0') {
 7566:                             $datatable .= '<span class="LC_nobreak"><label>'.
 7567:                                           '<input type="radio" name="selfenrolladmin_'.$row.'_'.$type.'" '.
 7568:                                           'value="'.$role.'"'.$checked{$role}.' />'.
 7569:                                           $roles{$role}.'</label></span> ';
 7570:                         }
 7571:                     } else {
 7572:                         if ($row eq 'types') {
 7573:                             my %checked;
 7574:                             if ($current{$type} =~ /^(all|dom)$/) {
 7575:                                 $checked{$1} = ' checked="checked"';
 7576:                             } else {
 7577:                                 $checked{''} = ' checked="checked"';
 7578:                             }
 7579:                             foreach my $val ('','dom','all') {
 7580:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 7581:                                               '<input type ="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 7582:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 7583:                             }
 7584:                         } elsif ($row eq 'registered') {
 7585:                             my %checked;
 7586:                             if ($current{$type} eq '1') {
 7587:                                 $checked{'1'} = ' checked="checked"';
 7588:                             } else {
 7589:                                 $checked{'0'} = ' checked="checked"';
 7590:                             }
 7591:                             foreach my $val ('0','1') {
 7592:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 7593:                                               '<input type ="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 7594:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 7595:                             }
 7596:                         } elsif ($row eq 'approval') {
 7597:                             my %checked;
 7598:                             if ($current{$type} =~ /^([12])$/) {
 7599:                                 $checked{$1} = ' checked="checked"';
 7600:                             } else {
 7601:                                 $checked{'0'} = ' checked="checked"';
 7602:                             }
 7603:                             for my $val (0..2) {
 7604:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 7605:                                               '<input type="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 7606:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 7607:                             }
 7608:                         } elsif ($row eq 'limit') {
 7609:                             my %checked;
 7610:                             if ($current{$type} =~ /^(allstudents|selfenrolled)$/) {
 7611:                                 $checked{$1} = ' checked="checked"';
 7612:                             } else {
 7613:                                 $checked{'none'} = ' checked="checked"';
 7614:                             }
 7615:                             my $cap;
 7616:                             if ($currentcap{$type} =~ /^\d+$/) {
 7617:                                 $cap = $currentcap{$type};
 7618:                             }
 7619:                             foreach my $val ('none','allstudents','selfenrolled') {
 7620:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 7621:                                               '<input type="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 7622:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 7623:                             }
 7624:                             $datatable .= '<br />'.
 7625:                                           '<span class="LC_nobreak">'.&mt('Maximum allowed: ').
 7626:                                           '<input type="text" name="selfenrolldefault_cap_'.$type.'" size = "5" value="'.$cap.'" />'.
 7627:                                           '</span>'; 
 7628:                         }
 7629:                     }
 7630:                     $datatable .= '</td>';
 7631:                 }
 7632:                 $datatable .= '</tr>';
 7633:             }
 7634:             $datatable .= '</table></td></tr>';
 7635:         }
 7636:     } elsif ($position eq 'bottom') {
 7637:         $datatable .= &print_validation_rows('selfenroll',$dom,$settings,\$itemcount);
 7638:     }
 7639:     $$rowtotal += $itemcount;
 7640:     return $datatable;
 7641: }
 7642: 
 7643: sub print_validation_rows {
 7644:     my ($caller,$dom,$settings,$rowtotal) = @_;
 7645:     my ($itemsref,$namesref,$fieldsref);
 7646:     if ($caller eq 'selfenroll') { 
 7647:         ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
 7648:     } elsif ($caller eq 'requestcourses') {
 7649:         ($itemsref,$namesref,$fieldsref) = &Apache::loncoursequeueadmin::requestcourses_validation_types();
 7650:     }
 7651:     my %currvalidation;
 7652:     if (ref($settings) eq 'HASH') {
 7653:         if (ref($settings->{'validation'}) eq 'HASH') {
 7654:             %currvalidation = %{$settings->{'validation'}};
 7655:         }
 7656:     }
 7657:     my $datatable;
 7658:     my $itemcount = 0;
 7659:     foreach my $item (@{$itemsref}) {
 7660:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7661:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 7662:                       $namesref->{$item}.
 7663:                       '</span></td>'.
 7664:                       '<td class="LC_left_item">';
 7665:         if (($item eq 'url') || ($item eq 'button')) {
 7666:             $datatable .= '<span class="LC_nobreak">'.
 7667:                           '<input type="text" name="'.$caller.'_validation_'.$item.'"'.
 7668:                           ' value="'.$currvalidation{$item}.'" size="50" /></span>';
 7669:         } elsif ($item eq 'fields') {
 7670:             my @currfields;
 7671:             if (ref($currvalidation{$item}) eq 'ARRAY') {
 7672:                 @currfields = @{$currvalidation{$item}};
 7673:             }
 7674:             foreach my $field (@{$fieldsref}) {
 7675:                 my $check = '';
 7676:                 if (grep(/^\Q$field\E$/,@currfields)) {
 7677:                     $check = ' checked="checked"';
 7678:                 }
 7679:                 $datatable .= '<span class="LC_nobreak"><label>'.
 7680:                               '<input type="checkbox" name="'.$caller.'_validation_fields"'.
 7681:                               ' value="'.$field.'"'.$check.' />'.$field.
 7682:                               '</label></span> ';
 7683:             }
 7684:         } elsif ($item eq 'markup') {
 7685:             $datatable .= '<textarea name="'.$caller.'_validation_markup" cols="50" rows="5">'.
 7686:                            $currvalidation{$item}.
 7687:                               '</textarea>';
 7688:         }
 7689:         $datatable .= '</td></tr>'."\n";
 7690:         if (ref($rowtotal)) {
 7691:             $itemcount ++;
 7692:         }
 7693:     }
 7694:     if ($caller eq 'requestcourses') {
 7695:         my %currhash;
 7696:         if (ref($settings) eq 'HASH') {
 7697:             if (ref($settings->{'validation'}) eq 'HASH') {
 7698:                 if ($settings->{'validation'}{'dc'} ne '') {
 7699:                     $currhash{$settings->{'validation'}{'dc'}} = 1;
 7700:                 }
 7701:             }
 7702:         }
 7703:         my $numinrow = 2;
 7704:         my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 7705:                                                        'validationdc',%currhash);
 7706:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7707:         $datatable .= '<tr'.$css_class.'><td>';
 7708:         if ($numdc > 1) {
 7709:             $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)');
 7710:         } else {
 7711:             $datatable .=  &mt('Course creation processed as: ');
 7712:         }
 7713:         $datatable .= '</td><td class="LC_left_item">'.$dctable.'</td></tr>';
 7714:         $itemcount ++;
 7715:     }
 7716:     if (ref($rowtotal)) {
 7717:         $$rowtotal += $itemcount;
 7718:     }
 7719:     return $datatable;
 7720: }
 7721: 
 7722: sub print_privacy {
 7723:     my ($position,$dom,$settings,$rowtotal) = @_;
 7724:     my ($datatable,$css_class,$numinrow,@items,%names,$othertitle,$usertypes,$types);
 7725:     my $itemcount = 0;
 7726:     if ($position eq 'top') {
 7727:         $numinrow = 2;
 7728:     } else {
 7729:         @items = ('domain','author','course','community');
 7730:         %names = &Apache::lonlocal::texthash (
 7731:                      domain => 'Assigned domain role(s)',
 7732:                      author => 'Assigned co-author role(s)',
 7733:                      course => 'Assigned course role(s)',
 7734:                      community => 'Assigned community role(s)',
 7735:                  );
 7736:         $numinrow = 4;
 7737:         ($othertitle,$usertypes,$types) =
 7738:             &Apache::loncommon::sorted_inst_types($dom);
 7739:     }
 7740:     if (($position eq 'top') || ($position eq 'middle')) {
 7741:         my (%by_ip,%by_location,@intdoms,@instdoms);
 7742:         &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 7743:         if ($position eq 'top') {
 7744:             my %curr;
 7745:             my @options = ('none','user','domain','auto');
 7746:             my %titles = &Apache::lonlocal::texthash (
 7747:                 none   => 'Not allowed',
 7748:                 user   => 'User authorizes',
 7749:                 domain => 'DC authorizes',
 7750:                 auto   => 'Unrestricted',
 7751:                 instdom => 'Other domain shares institution/provider',
 7752:                 extdom => 'Other domain has different institution/provider',
 7753:                 notify => 'Notify when role needs authorization',
 7754:             );
 7755:             my %names = &Apache::lonlocal::texthash (
 7756:                 domain => 'Domain role',
 7757:                 author => 'Co-author role',
 7758:                 course => 'Course role',
 7759:                 community => 'Community role',
 7760:             );
 7761:             my $primary_id = &Apache::lonnet::domain($dom,'primary');
 7762:             my $intdom = &Apache::lonnet::internet_dom($primary_id);
 7763:             foreach my $domtype ('instdom','extdom') {
 7764:                 my (%checked,$skip);
 7765:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7766:                 $datatable .= '<tr'.$css_class.'><td>'.$titles{$domtype}.'</td>'.
 7767:                               '<td class="LC_left_item">';
 7768:                 if ($domtype eq 'instdom') {
 7769:                     unless (@instdoms > 1) {
 7770:                         $datatable .= &mt('Nothing to set, as no domains besides [_1] are hosted by [_2]',$dom,$intdom);
 7771:                         $skip = 1;
 7772:                     }
 7773:                 } elsif ($domtype eq 'extdom') {
 7774:                     if (keys(%by_location) == 0) {
 7775:                         $datatable .= &mt('Nothing to set, as no other hosts besides [_1]',$intdom);
 7776:                         $skip = 1;
 7777:                     }
 7778:                 }
 7779:                 unless ($skip) {
 7780:                     foreach my $roletype ('domain','author','course','community') {
 7781:                         $checked{'auto'} = ' checked="checked"';
 7782:                         if (ref($settings) eq 'HASH') {
 7783:                             if (ref($settings->{approval}) eq 'HASH') {
 7784:                                 if (ref($settings->{approval}->{$domtype}) eq 'HASH') {
 7785:                                     if ($settings->{approval}->{$domtype}->{$roletype}=~ /^(none|user|domain)$/) {
 7786:                                         $checked{$1} = ' checked="checked"';
 7787:                                         $checked{'auto'} = '';
 7788:                                     }
 7789:                                 }
 7790:                             }
 7791:                         }
 7792:                         $datatable .= '<fieldset><legend>'.$names{$roletype}.'</legend>';
 7793:                         foreach my $option (@options) {
 7794:                             $datatable .= '<span class="LC_nobreak"><label>'.
 7795:                                           '<input type="radio" name="privacy_approval_'.$domtype.'_'.$roletype.'" '.
 7796:                                           'value="'.$option.'"'.$checked{$option}.' />'.$titles{$option}.
 7797:                                           '</label></span>&nbsp; ';
 7798:                         }
 7799:                         $datatable .= '</fieldset>';
 7800:                     }
 7801:                 }
 7802:                 $datatable .= '</td></tr>';
 7803:                 $itemcount ++;
 7804:             }
 7805:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7806:             $datatable .= '<tr'.$css_class.'><td>'.$titles{'notify'}.'</td>'.
 7807:                           '<td class="LC_left_item">';
 7808:             if ((@instdoms > 1) || (keys(%by_location) > 0)) {
 7809:                 my %curr;
 7810:                 if (ref($settings) eq 'HASH') {
 7811:                     if ($settings->{'notify'} ne '') {
 7812:                         map {$curr{$_}=1;} split(/,/,$settings->{'notify'});
 7813:                     }
 7814:                 }
 7815:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7816:                 my ($numdc,$table,$rows) = &active_dc_picker($dom,$numinrow,'checkbox',
 7817:                                                              'privacy_notify',%curr);
 7818:                 if ($numdc > 0) {
 7819:                     $datatable .= $table;
 7820:                 } else {
 7821:                     $datatable .= &mt('There are no active Domain Coordinators');
 7822:                 }
 7823:             } else {
 7824:                 $datatable .= &mt('Nothing to set here, as there are no other domains');
 7825:             }
 7826:             $datatable .='</td></tr>';
 7827:         } elsif ($position eq 'middle') {
 7828:             if ((@instdoms > 1) || (keys(%by_location) > 0)) {
 7829:                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7830:                     foreach my $item (@{$types}) {
 7831:                         $datatable .= &modifiable_userdata_row('privacy','othdom_'.$item,$settings,
 7832:                                                                $numinrow,$itemcount,'','','','','',
 7833:                                                                '',$usertypes->{$item});
 7834:                         $itemcount ++;
 7835:                     }
 7836:                 }
 7837:                 $datatable .= &modifiable_userdata_row('privacy','othdom_default',$settings,
 7838:                                                        $numinrow,$itemcount,'','','','','',
 7839:                                                        '',$othertitle);
 7840:                 $itemcount ++;
 7841:             } else {
 7842:                 my (@insttypes,%insttitles);
 7843:                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7844:                     @insttypes = @{$types};
 7845:                     %insttitles = %{$usertypes};
 7846:                 }
 7847:                 foreach my $item (@insttypes,'default') {
 7848:                     my $title;
 7849:                     if ($item eq 'default') {
 7850:                         $title = $othertitle;
 7851:                     } else {
 7852:                         $title = $insttitles{$item};
 7853:                     }
 7854:                     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7855:                     $datatable .= '<tr'.$css_class.'>'.
 7856:                                   '<td class="LC_left_item">'.$title.'</td>'.
 7857:                                   '<td class="LC_left_item">'.
 7858:                                   &mt('Nothing to set here, as there are no other domains').
 7859:                                   '</td></tr>';
 7860:                     $itemcount ++;
 7861:                 }
 7862:             }
 7863:         }
 7864:     } else {
 7865:         my $prefix;
 7866:         if ($position eq 'lower') {
 7867:             $prefix = 'priv';
 7868:         } else {
 7869:             $prefix = 'unpriv';
 7870:         }
 7871:         foreach my $item (@items) {
 7872:             $datatable .= &modifiable_userdata_row('privacy',$prefix.'_'.$item,$settings,
 7873:                                                    $numinrow,$itemcount,'','','','','',
 7874:                                                    '',$names{$item});
 7875:             $itemcount ++;
 7876:         }
 7877:     }
 7878:     if (ref($rowtotal)) {
 7879:         $$rowtotal += $itemcount;
 7880:     }
 7881:     return $datatable;
 7882: }
 7883: 
 7884: sub print_passwords {
 7885:     my ($position,$dom,$confname,$settings,$rowtotal) = @_;
 7886:     my ($datatable,$css_class);
 7887:     my $itemcount = 0;
 7888:     my %titles = &Apache::lonlocal::texthash (
 7889:         captcha        => '"Forgot Password" CAPTCHA validation',
 7890:         link           => 'Reset link expiration (hours)',
 7891:         case           => 'Case-sensitive usernames/e-mail',
 7892:         prelink        => 'Information required (form 1)',
 7893:         postlink       => 'Information required (form 2)',
 7894:         emailsrc       => 'LON-CAPA e-mail address type(s)',
 7895:         customtext     => 'Domain specific text (HTML)',
 7896:         intauth_cost   => 'Encryption cost for bcrypt (positive integer)',
 7897:         intauth_check  => 'Check bcrypt cost if authenticated',
 7898:         intauth_switch => 'Existing crypt-based switched to bcrypt on authentication',
 7899:         permanent      => 'Permanent e-mail address',
 7900:         critical       => 'Critical notification address',
 7901:         notify         => 'Notification address',
 7902:         min            => 'Minimum password length',
 7903:         max            => 'Maximum password length',
 7904:         chars          => 'Required characters',
 7905:         expire         => 'Password expiration (days)',
 7906:         numsaved       => 'Number of previous passwords to save and disallow reuse',
 7907:     );
 7908:     if ($position eq 'top') {
 7909:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 7910:         my $shownlinklife = 2;
 7911:         my $prelink = 'both';
 7912:         my (%casesens,%postlink,%emailsrc,$nostdtext,$customurl);
 7913:         if (ref($settings) eq 'HASH') {
 7914:             if ($settings->{resetlink} =~ /^\d+(|\.\d*)$/) {
 7915:                 $shownlinklife = $settings->{resetlink};
 7916:             }
 7917:             if (ref($settings->{resetcase}) eq 'ARRAY') {
 7918:                 map { $casesens{$_} = 1; } (@{$settings->{resetcase}});
 7919:             }
 7920:             if ($settings->{resetprelink} =~ /^(both|either)$/) {
 7921:                 $prelink = $settings->{resetprelink};
 7922:             }
 7923:             if (ref($settings->{resetpostlink}) eq 'HASH') {
 7924:                 %postlink = %{$settings->{resetpostlink}};
 7925:             }
 7926:             if (ref($settings->{resetemail}) eq 'ARRAY') {
 7927:                 map { $emailsrc{$_} = 1; } (@{$settings->{resetemail}});
 7928:             }
 7929:             if ($settings->{resetremove}) {
 7930:                 $nostdtext = 1;
 7931:             }
 7932:             if ($settings->{resetcustom}) {
 7933:                 $customurl = $settings->{resetcustom};
 7934:             }
 7935:         } else {
 7936:             if (ref($types) eq 'ARRAY') {
 7937:                 foreach my $item (@{$types}) {
 7938:                     $casesens{$item} = 1;
 7939:                     $postlink{$item} = ['username','email'];
 7940:                 }
 7941:             }
 7942:             $casesens{'default'} = 1;
 7943:             $postlink{'default'} = ['username','email'];
 7944:             $prelink = 'both';
 7945:             %emailsrc = (
 7946:                           permanent => 1,
 7947:                           critical  => 1,
 7948:                           notify    => 1,
 7949:             );
 7950:         }
 7951:         $datatable = &captcha_choice('passwords',$settings,$$rowtotal);
 7952:         $itemcount ++;
 7953:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7954:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'link'}.'</td>'.
 7955:                       '<td class="LC_left_item">'.
 7956:                       '<input type="textbox" value="'.$shownlinklife.'" '.
 7957:                       'name="passwords_link" size="3" /></td></tr>';
 7958:         $itemcount ++;
 7959:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7960:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'case'}.'</td>'.
 7961:                       '<td class="LC_left_item">';
 7962:         if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7963:             foreach my $item (@{$types}) {
 7964:                 my $checkedcase;
 7965:                 if ($casesens{$item}) {
 7966:                     $checkedcase = ' checked="checked"';
 7967:                 }
 7968:                 $datatable .= '<span class="LC_nobreak"><label>'.
 7969:                               '<input type="checkbox" name="passwords_case_sensitive" value="'.
 7970:                               $item.'"'.$checkedcase.' />'.$usertypes->{$item}.'</label>'.
 7971:                               '</span>&nbsp;&nbsp; ';
 7972:             }
 7973:         }
 7974:         my $checkedcase;
 7975:         if ($casesens{'default'}) {
 7976:             $checkedcase = ' checked="checked"';
 7977:         }
 7978:         $datatable .= '<span class="LC_nobreak"><label><input type="checkbox" '.
 7979:                       'name="passwords_case_sensitive" value="default"'.$checkedcase.' />'.
 7980:                       $othertitle.'</label></span></td>';
 7981:         $itemcount ++;
 7982:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7983:         my %checkedpre = (
 7984:                              both => ' checked="checked"',
 7985:                              either => '',
 7986:                          );
 7987:         if ($prelink eq 'either') {
 7988:             $checkedpre{either} = ' checked="checked"';
 7989:             $checkedpre{both} = '';
 7990:         }
 7991:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'prelink'}.'</td>'.
 7992:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 7993:                       '<label><input type="radio" name="passwords_prelink" value="both"'.$checkedpre{'both'}.' />'.
 7994:                       &mt('Both username and e-mail address').'</label></span>&nbsp;&nbsp; '.
 7995:                       '<span class="LC_nobreak"><label>'.
 7996:                       '<input type="radio" name="passwords_prelink" value="either"'.$checkedpre{'either'}.' />'.
 7997:                       &mt('Either username or e-mail address').'</label></span></td></tr>';
 7998:         $itemcount ++;
 7999:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8000:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'postlink'}.'</td>'.
 8001:                       '<td class="LC_left_item">';
 8002:         my %postlinked;
 8003:         if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 8004:             foreach my $item (@{$types}) {
 8005:                 undef(%postlinked);
 8006:                 $datatable .= '<fieldset style="display: inline-block;">'.
 8007:                               '<legend>'.$usertypes->{$item}.'</legend>';
 8008:                 if (ref($postlink{$item}) eq 'ARRAY') {
 8009:                     map { $postlinked{$_} = 1; } (@{$postlink{$item}});
 8010:                 }
 8011:                 foreach my $field ('email','username') {
 8012:                     my $checked;
 8013:                     if ($postlinked{$field}) {
 8014:                         $checked = ' checked="checked"';
 8015:                     }
 8016:                     $datatable .= '<span class="LC_nobreak"><label>'.
 8017:                                   '<input type="checkbox" name="passwords_postlink_'.$item.'" value="'.
 8018:                                   $field.'"'.$checked.' />'.$field.'</label>'.
 8019:                                   '<span>&nbsp;&nbsp; ';
 8020:                 }
 8021:                 $datatable .= '</fieldset>';
 8022:             }
 8023:         }
 8024:         if (ref($postlink{'default'}) eq 'ARRAY') {
 8025:             map { $postlinked{$_} = 1; } (@{$postlink{'default'}});
 8026:         }
 8027:         $datatable .= '<fieldset style="display: inline-block;">'.
 8028:                       '<legend>'.$othertitle.'</legend>';
 8029:         foreach my $field ('email','username') {
 8030:             my $checked;
 8031:             if ($postlinked{$field}) {
 8032:                 $checked = ' checked="checked"';
 8033:             }
 8034:             $datatable .= '<span class="LC_nobreak"><label>'.
 8035:                           '<input type="checkbox" name="passwords_postlink_default" value="'.
 8036:                           $field.'"'.$checked.' />'.$field.'</label>'.
 8037:                           '<span>&nbsp;&nbsp; ';
 8038:         }
 8039:         $datatable .= '</fieldset></td></tr>';
 8040:         $itemcount ++;
 8041:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8042:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'emailsrc'}.'</td>'.
 8043:                       '<td class="LC_left_item">';
 8044:         foreach my $type ('permanent','critical','notify') {
 8045:             my $checkedemail;
 8046:             if ($emailsrc{$type}) {
 8047:                 $checkedemail = ' checked="checked"';
 8048:             }
 8049:             $datatable .= '<span class="LC_nobreak"><label>'.
 8050:                           '<input type="checkbox" name="passwords_emailsrc" value="'.
 8051:                           $type.'"'.$checkedemail.' />'.$titles{$type}.'</label>'.
 8052:                           '<span>&nbsp;&nbsp; ';
 8053:         }
 8054:         $datatable .= '</td></tr>';
 8055:         $itemcount ++;
 8056:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8057:         my $switchserver = &check_switchserver($dom,$confname);
 8058:         my ($showstd,$noshowstd);
 8059:         if ($nostdtext) {
 8060:             $noshowstd = ' checked="checked"';
 8061:         } else {
 8062:             $showstd = ' checked="checked"';
 8063:         }
 8064:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'customtext'}.'</td>'.
 8065:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 8066:                       &mt('Retain standard text:').
 8067:                       '<label><input type="radio" name="passwords_stdtext" value="1"'.$showstd.' />'.
 8068:                       &mt('Yes').'</label>'.'&nbsp;'.
 8069:                       '<label><input type="radio" name="passwords_stdtext" value="0"'.$noshowstd.' />'.
 8070:                       &mt('No').'</label></span><br />'.
 8071:                       '<span class="LC_fontsize_small">'.
 8072:                       &mt('(If you use the same account ...  reset a password from this page.)').'</span><br /><br />'.
 8073:                       &mt('Include custom text:');
 8074:         if ($customurl) {
 8075:             my $link =  &Apache::loncommon::modal_link($customurl,&mt('custom text'),600,500,
 8076:                                                        undef,undef,undef,undef,'background-color:#ffffff');
 8077:             $datatable .= '<span class="LC_nobreak">&nbsp;'.$link.
 8078:                           '<label><input type="checkbox" name="passwords_custom_del"'.
 8079:                           ' value="1" />'.&mt('Delete?').'</label></span>'.
 8080:                           ' <span class="LC_nobreak">&nbsp;'.&mt('Replace:').'</span>';
 8081:         }
 8082:         if ($switchserver) {
 8083:             $datatable .= '<span class="LC_nobreak">&nbsp;'.&mt('Upload to library server: [_1]',$switchserver).'</span>';
 8084:         } else {
 8085:             $datatable .='<span class="LC_nobreak">&nbsp;'.
 8086:                          '<input type="file" name="passwords_customfile" /></span>';
 8087:         }
 8088:         $datatable .= '</td></tr>';
 8089:     } elsif ($position eq 'middle') {
 8090:         my %domconf = &Apache::lonnet::get_dom('configuration',['defaults'],$dom);
 8091:         my @items = ('intauth_cost','intauth_check','intauth_switch');
 8092:         my %defaults;
 8093:         if (ref($domconf{'defaults'}) eq 'HASH') {
 8094:             %defaults = %{$domconf{'defaults'}};
 8095:             if ($defaults{'intauth_cost'} !~ /^\d+$/) {
 8096:                 $defaults{'intauth_cost'} = 10;
 8097:             }
 8098:             if ($defaults{'intauth_check'} !~ /^(0|1|2)$/) {
 8099:                 $defaults{'intauth_check'} = 0;
 8100:             }
 8101:             if ($defaults{'intauth_switch'} !~ /^(0|1|2)$/) {
 8102:                 $defaults{'intauth_switch'} = 0;
 8103:             }
 8104:         } else {
 8105:             %defaults = (
 8106:                           'intauth_cost'   => 10,
 8107:                           'intauth_check'  => 0,
 8108:                           'intauth_switch' => 0,
 8109:                         );
 8110:         }
 8111:         foreach my $item (@items) {
 8112:             if ($itemcount%2) {
 8113:                 $css_class = '';
 8114:             } else {
 8115:                 $css_class = ' class="LC_odd_row" ';
 8116:             }
 8117:             $datatable .= '<tr'.$css_class.'>'.
 8118:                           '<td><span class="LC_nobreak">'.$titles{$item}.
 8119:                           '</span></td><td class="LC_left_item" colspan="3">';
 8120:             if ($item eq 'intauth_switch') {
 8121:                 my @options = (0,1,2);
 8122:                 my %optiondesc = &Apache::lonlocal::texthash (
 8123:                                    0 => 'No',
 8124:                                    1 => 'Yes',
 8125:                                    2 => 'Yes, and copy existing passwd file to passwd.bak file',
 8126:                                  );
 8127:                 $datatable .= '<table width="100%">';
 8128:                 foreach my $option (@options) {
 8129:                     my $checked = ' ';
 8130:                     if ($defaults{$item} eq $option) {
 8131:                         $checked = ' checked="checked"';
 8132:                     }
 8133:                     $datatable .= '<tr><td class="LC_left_item"><span class="LC_nobreak">'.
 8134:                                   '<label><input type="radio" name="'.$item.
 8135:                                   '" value="'.$option.'"'.$checked.' />'.
 8136:                                   $optiondesc{$option}.'</label></span></td></tr>';
 8137:                 }
 8138:                 $datatable .= '</table>';
 8139:             } elsif ($item eq 'intauth_check') {
 8140:                 my @options = (0,1,2);
 8141:                 my %optiondesc = &Apache::lonlocal::texthash (
 8142:                                    0 => 'No',
 8143:                                    1 => 'Yes, allow login then update passwd file using default cost (if higher)',
 8144:                                    2 => 'Yes, disallow login if stored cost is less than domain default',
 8145:                                  );
 8146:                 $datatable .= '<table width="100%">';
 8147:                 foreach my $option (@options) {
 8148:                     my $checked = ' ';
 8149:                     my $onclick;
 8150:                     if ($defaults{$item} eq $option) {
 8151:                         $checked = ' checked="checked"';
 8152:                     }
 8153:                     if ($option == 2) {
 8154:                         $onclick = ' onclick="javascript:warnIntAuth(this);"';
 8155:                     }
 8156:                     $datatable .= '<tr><td class="LC_left_item"><span class="LC_nobreak">'.
 8157:                                   '<label><input type="radio" name="'.$item.
 8158:                                   '" value="'.$option.'"'.$checked.$onclick.' />'.
 8159:                                   $optiondesc{$option}.'</label></span></td></tr>';
 8160:                 }
 8161:                 $datatable .= '</table>';
 8162:             } else {
 8163:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
 8164:                               $defaults{$item}.'" size="3" onblur="javascript:warnIntAuth(this);" />';
 8165:             }
 8166:             $datatable .= '</td></tr>';
 8167:             $itemcount ++;
 8168:         }
 8169:     } elsif ($position eq 'lower') {
 8170:         $datatable .= &password_rules('passwords',\$itemcount,$settings);
 8171:     } else {
 8172:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 8173:         my %ownerchg = (
 8174:                           by  => {},
 8175:                           for => {},
 8176:                        );
 8177:         my %ownertitles = &Apache::lonlocal::texthash (
 8178:                             by  => 'Course owner status(es) allowed',
 8179:                             for => 'Student status(es) allowed',
 8180:                           );
 8181:         if (ref($settings) eq 'HASH') {
 8182:             if (ref($settings->{crsownerchg}) eq 'HASH') {
 8183:                 if (ref($settings->{crsownerchg}{'by'}) eq 'ARRAY') {
 8184:                     map { $ownerchg{by}{$_} = 1; } (@{$settings->{crsownerchg}{'by'}});
 8185:                 }
 8186:                 if (ref($settings->{crsownerchg}{'for'}) eq 'ARRAY') {
 8187:                     map { $ownerchg{for}{$_} = 1; } (@{$settings->{crsownerchg}{'for'}});
 8188:                 }
 8189:             }
 8190:         }
 8191:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8192:         $datatable .= '<tr '.$css_class.'>'.
 8193:                       '<td>'.
 8194:                       &mt('Requirements').'<ul>'.
 8195:                       '<li>'.&mt("Course 'type' is not a Community or Placement Test").'</li>'.
 8196:                       '<li>'.&mt('User is Course Coordinator and also course owner').'</li>'.
 8197:                       '<li>'.&mt("Student's only active roles are student role(s) in course(s) owned by this user").'</li>'.
 8198:                       '<li>'.&mt('User, course, and student share same domain').'</li>'.
 8199:                       '</ul>'.
 8200:                       '</td>'.
 8201:                       '<td class="LC_left_item">';
 8202:         foreach my $item ('by','for') {
 8203:             $datatable .= '<fieldset style="display: inline-block;">'.
 8204:                           '<legend>'.$ownertitles{$item}.'</legend>';
 8205:             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 8206:                 foreach my $type (@{$types}) {
 8207:                     my $checked;
 8208:                     if ($ownerchg{$item}{$type}) {
 8209:                         $checked = ' checked="checked"';
 8210:                     }
 8211:                     $datatable .= '<span class="LC_nobreak"><label>'.
 8212:                                   '<input type="checkbox" name="passwords_crsowner_'.$item.'" value="'.
 8213:                                   $type.'"'.$checked.' />'.$usertypes->{$type}.'</label>'.
 8214:                                   '</span>&nbsp;&nbsp; ';
 8215:                 }
 8216:             }
 8217:             my $checked;
 8218:             if ($ownerchg{$item}{'default'}) {
 8219:                 $checked = ' checked="checked"';
 8220:             }
 8221:             $datatable .= '<span class="LC_nobreak"><label><input type="checkbox" '.
 8222:                           'name="passwords_crsowner_'.$item.'" value="default"'.$checked.' />'.
 8223:                           $othertitle.'</label></span></fieldset>';
 8224:         }
 8225:         $datatable .= '</td></tr>';
 8226:     }
 8227:     return $datatable;
 8228: }
 8229: 
 8230: sub password_rules {
 8231:     my ($prefix,$itemcountref,$settings) = @_;
 8232:     my ($min,$max,%chars,$expire,$numsaved,$numinrow);
 8233:     my %titles;
 8234:     if ($prefix eq 'passwords') {
 8235:         %titles = &Apache::lonlocal::texthash (
 8236:             min            => 'Minimum password length',
 8237:             max            => 'Maximum password length',
 8238:             chars          => 'Required characters',
 8239:         );
 8240:     } elsif ($prefix eq 'secrets') {
 8241:         %titles = &Apache::lonlocal::texthash (
 8242:             min            => 'Minimum secret length',
 8243:             max            => 'Maximum secret length',
 8244:             chars          => 'Required characters',
 8245:         );
 8246:     }
 8247:     $min = $Apache::lonnet::passwdmin;
 8248:     my $datatable;
 8249:     my $itemcount;
 8250:     if (ref($itemcountref)) {
 8251:         $itemcount = $$itemcountref;
 8252:     }
 8253:     if (ref($settings) eq 'HASH') {
 8254:         if ($settings->{min}) {
 8255:             $min = $settings->{min};
 8256:         }
 8257:         if ($settings->{max}) {
 8258:             $max = $settings->{max};
 8259:         }
 8260:         if (ref($settings->{chars}) eq 'ARRAY') {
 8261:             map { $chars{$_} = 1; } (@{$settings->{chars}});
 8262:         }
 8263:         if ($prefix eq 'passwords') { 
 8264:             if ($settings->{expire}) {
 8265:                 $expire = $settings->{expire};
 8266:             }
 8267:             if ($settings->{numsaved}) {
 8268:                 $numsaved = $settings->{numsaved};
 8269:             }
 8270:         }
 8271:     }
 8272:     my %rulenames = &Apache::lonlocal::texthash(
 8273:                                                  uc => 'At least one upper case letter',
 8274:                                                  lc => 'At least one lower case letter',
 8275:                                                  num => 'At least one number',
 8276:                                                  spec => 'At least one non-alphanumeric',
 8277:                                                );
 8278:     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8279:     $datatable .= '<tr'.$css_class.'><td>'.$titles{'min'}.'</td>'.
 8280:                   '<td class="LC_left_item"><span class="LC_nobreak">'.
 8281:                   '<input type="text" name="'.$prefix.'_min" value="'.$min.'" size="3" '.
 8282:                   'onblur="javascript:warnInt'.$prefix.'(this);" />'.
 8283:                   '<span class="LC_fontsize_small"> '.&mt('(Enter an integer: 7 or larger)').'</span>'.
 8284:                   '</span></td></tr>';
 8285:     $itemcount ++;
 8286:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8287:     $datatable .= '<tr'.$css_class.'><td>'.$titles{'max'}.'</td>'.
 8288:                   '<td class="LC_left_item"><span class="LC_nobreak">'.
 8289:                   '<input type="text" name="'.$prefix.'_max" value="'.$max.'" size="3" '.
 8290:                   'onblur="javascript:warnInt'.$prefix.'(this);" />'.
 8291:                   '<span class="LC_fontsize_small"> '.&mt('(Leave blank for no maximum)').'</span>'.
 8292:                   '</span></td></tr>';
 8293:     $itemcount ++;
 8294:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8295:     $datatable .= '<tr'.$css_class.'><td>'.$titles{'chars'}.'<br />'.
 8296:                   '<span class="LC_nobreak LC_fontsize_small">'.&mt('(Leave unchecked if not required)').
 8297:                   '</span></td>';
 8298:     my $numinrow = 2;
 8299:     my @possrules = ('uc','lc','num','spec');
 8300:     $datatable .= '<td class="LC_left_item"><table>';
 8301:     for (my $i=0; $i<@possrules; $i++) {
 8302:         my ($rem,$checked);
 8303:         if ($chars{$possrules[$i]}) {
 8304:             $checked = ' checked="checked"';
 8305:         }
 8306:         $rem = $i%($numinrow);
 8307:         if ($rem == 0) {
 8308:             if ($i > 0) {
 8309:                 $datatable .= '</tr>';
 8310:             }
 8311:             $datatable .= '<tr>';
 8312:         }
 8313:         $datatable .= '<td><span class="LC_nobreak"><label>'.
 8314:                       '<input type="checkbox" name="'.$prefix.'_chars" value="'.$possrules[$i].'"'.$checked.' />'.
 8315:                       $rulenames{$possrules[$i]}.'</label></span></td>';
 8316:     }
 8317:     my $rem = @possrules%($numinrow);
 8318:     my $colsleft = $numinrow - $rem;
 8319:     if ($colsleft > 1 ) {
 8320:         $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 8321:                       '&nbsp;</td>';
 8322:     } elsif ($colsleft == 1) {
 8323:         $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 8324:     }
 8325:     $datatable .='</table></td></tr>';
 8326:     $itemcount ++;
 8327:     if ($prefix eq 'passwords') {
 8328:         $titles{'expire'} = &mt('Password expiration (days)');
 8329:         $titles{'numsaved'} = &mt('Number of previous passwords to save and disallow reuse');
 8330:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8331:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'expire'}.'</td>'.
 8332:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 8333:                       '<input type="text" name="'.$prefix.'_expire" value="'.$expire.'" size="4" '.
 8334:                       'onblur="javascript:warnInt'.$prefix.'(this);" />'.
 8335:                       '<span class="LC_fontsize_small"> '.&mt('(Leave blank for no expiration)').'</span>'.
 8336:                       '</span></td></tr>';
 8337:         $itemcount ++;
 8338:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8339:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'numsaved'}.'</td>'.
 8340:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 8341:                       '<input type="text" name="'.$prefix.'_numsaved" value="'.$numsaved.'" size="3" '.
 8342:                       'onblur="javascript:warnInt'.$prefix.'(this);" />'.
 8343:                       '<span class="LC_fontsize_small"> '.&mt('(Leave blank to not save previous passwords)').'</span>'.
 8344:                       '</span></td></tr>';
 8345:         $itemcount ++;
 8346:     }
 8347:     if (ref($itemcountref)) {
 8348:         $$itemcountref += $itemcount;
 8349:     }
 8350:     return $datatable;
 8351: }
 8352: 
 8353: sub print_wafproxy {
 8354:     my ($position,$dom,$settings,$rowtotal) = @_;
 8355:     my $css_class;
 8356:     my $itemcount = 0;
 8357:     my $datatable;
 8358:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 8359:     my (%othercontrol,%otherdoms,%aliases,%saml,%values,$setdom,$showdom);
 8360:     my %lt = &wafproxy_titles();
 8361:     foreach my $server (sort(keys(%servers))) {
 8362:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
 8363:         next if ($serverhome eq '');
 8364:         my $serverdom;
 8365:         if ($serverhome ne $server) {
 8366:             $serverdom = &Apache::lonnet::host_domain($serverhome);
 8367:             if (($serverdom ne '') && (&Apache::lonnet::domain($serverdom) ne '')) {
 8368:                 $othercontrol{$server} = $serverdom;
 8369:             }
 8370:         } else {
 8371:             $serverdom = &Apache::lonnet::host_domain($server);
 8372:             next if (($serverdom eq '') || (&Apache::lonnet::domain($serverdom) eq ''));
 8373:             if ($serverdom ne $dom) {
 8374:                 $othercontrol{$server} = $serverdom;
 8375:             } else {
 8376:                 $setdom = 1;
 8377:                 if (ref($settings) eq 'HASH') {
 8378:                     if (ref($settings->{'alias'}) eq 'HASH') {
 8379:                         $aliases{$dom} = $settings->{'alias'};
 8380:                         if ($aliases{$dom} ne '') {
 8381:                             $showdom = 1;
 8382:                         }
 8383:                     }
 8384:                     if (ref($settings->{'saml'}) eq 'HASH') {
 8385:                         $saml{$dom} = $settings->{'saml'};
 8386:                     }
 8387:                 }
 8388:             }
 8389:         }
 8390:     }
 8391:     if ($setdom) {
 8392:         %{$values{$dom}} = ();
 8393:         if (ref($settings) eq 'HASH') {
 8394:             foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext') {
 8395:                 $values{$dom}{$item} = $settings->{$item};
 8396:             }
 8397:         }
 8398:     }
 8399:     if (keys(%othercontrol)) {
 8400:         %otherdoms = reverse(%othercontrol);
 8401:         foreach my $domain (keys(%otherdoms)) {
 8402:             %{$values{$domain}} = ();
 8403:             my %config = &Apache::lonnet::get_dom('configuration',['wafproxy'],$domain);
 8404:             if (ref($config{'wafproxy'}) eq 'HASH') {
 8405:                 $aliases{$domain} = $config{'wafproxy'}{'alias'};
 8406:                 if (exists($config{'wafproxy'}{'saml'})) { 
 8407:                     $saml{$domain} = $config{'wafproxy'}{'saml'};
 8408:                 }
 8409:                 foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext') {
 8410:                     $values{$domain}{$item} = $config{'wafproxy'}{$item};
 8411:                 }
 8412:             }
 8413:         }
 8414:     }
 8415:     if ($position eq 'top') {
 8416:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 8417:         my %aliasinfo;
 8418:         foreach my $server (sort(keys(%servers))) {
 8419:             $itemcount ++;
 8420:             my $dom_in_effect;
 8421:             my $aliasrows = '<tr>'.
 8422:                             '<td class="LC_left_item" style="vertical-align: baseline;">'.
 8423:                             &mt('Hostname').':&nbsp;'.
 8424:                             '<i>'.&Apache::lonnet::hostname($server).'</i></td><td>&nbsp;</td>';
 8425:             if ($othercontrol{$server}) {
 8426:                 $dom_in_effect = $othercontrol{$server};
 8427:                 my ($current,$forsaml);
 8428:                 if (ref($aliases{$dom_in_effect}) eq 'HASH') {
 8429:                     $current = $aliases{$dom_in_effect}{$server};
 8430:                 }
 8431:                 if (ref($saml{$dom_in_effect}) eq 'HASH') {
 8432:                     if ($saml{$dom_in_effect}{$server}) {
 8433:                         $forsaml = 1;
 8434:                     }
 8435:                 }
 8436:                 $aliasrows .= '<td class="LC_left_item" style="vertical-align: baseline;">'.
 8437:                               &mt('Alias').':&nbsp';
 8438:                 if ($current) {
 8439:                     $aliasrows .= $current;
 8440:                     if ($forsaml) {
 8441:                          $aliasrows .= '&nbsp;('.&mt('also for SSO Auth').')';
 8442:                     }
 8443:                 } else {
 8444:                     $aliasrows .= &mt('None');
 8445:                 }
 8446:                 $aliasrows .= '&nbsp;<span class="LC_small">('.
 8447:                               &mt('controlled by domain: [_1]',
 8448:                                   '<b>'.$dom_in_effect.'</b>').')</span></td>';
 8449:             } else {
 8450:                 $dom_in_effect = $dom;
 8451:                 my ($current,$samlon,$samloff);
 8452:                 $samloff = ' checked="checked"';
 8453:                 if (ref($aliases{$dom}) eq 'HASH') {
 8454:                     if ($aliases{$dom}{$server}) {
 8455:                         $current = $aliases{$dom}{$server};
 8456:                     }
 8457:                 }
 8458:                 if (ref($saml{$dom}) eq 'HASH') {
 8459:                     if ($saml{$dom}{$server}) {
 8460:                         $samlon = $samloff;
 8461:                         undef($samloff);
 8462:                     }
 8463:                 }
 8464:                 $aliasrows .= '<td class="LC_left_item" style="vertical-align: baseline;">'.
 8465:                               &mt('Alias').':&nbsp;'.
 8466:                               '<input type="text" name="wafproxy_alias_'.$server.'" '.
 8467:                               'value="'.$current.'" size="30" />'.
 8468:                               ('&nbsp;'x2).'<span class="LC_nobreak">'.
 8469:                               &mt('Alias used for SSO Auth').':&nbsp;<label>'.
 8470:                               '<input type="radio" value="0"'.$samloff.' name="wafproxy_alias_saml_'.$server.'" />'.
 8471:                               &mt('No').'</label>&nbsp;<label>'. 
 8472:                               '<input type="radio" value="1"'.$samlon.' name="wafproxy_alias_saml_'.$server.'" />'.
 8473:                               &mt('Yes').'</label></span>'.
 8474:                               '</td>'; 
 8475:             }
 8476:             $aliasrows .= '</tr>';
 8477:             $aliasinfo{$dom_in_effect} .= $aliasrows;
 8478:         }
 8479:         if ($aliasinfo{$dom}) {
 8480:             my ($onclick,$wafon,$wafoff,$showtable);
 8481:             $onclick = ' onclick="javascript:toggleWAF();"';
 8482:             $wafoff = ' checked="checked"';
 8483:             $showtable = ' style="display:none";';
 8484:             if ($showdom) {
 8485:                 $wafon = $wafoff;
 8486:                 $wafoff = '';
 8487:                 $showtable = ' style="display:inline;"';
 8488:             }
 8489:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8490:             $datatable = '<tr'.$css_class.'>'.
 8491:                          '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'<br />'.
 8492:                          '<span class="LC_nobreak">'.&mt('WAF in use?').'&nbsp;<label>'.
 8493:                          '<input type="radio" name="wafproxy_'.$dom.'" value="1"'.$wafon.$onclick.' />'.
 8494:                          &mt('Yes').'</label>'.('&nbsp;'x2).'<label>'.
 8495:                          '<input type="radio" name="wafproxy_'.$dom.'" value="0"'.$wafoff.$onclick.' />'.
 8496:                          &mt('No').'</label></span></td>'.
 8497:                          '<td class="LC_left_item">'.
 8498:                          '<table id="wafproxy_table"'.$showtable.'>'.$aliasinfo{$dom}.
 8499:                          '</table></td></tr>';
 8500:             $itemcount++;
 8501:         }
 8502:         if (keys(%otherdoms)) {
 8503:             foreach my $key (sort(keys(%otherdoms))) {
 8504:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8505:                 $datatable .= '<tr'.$css_class.'>'.
 8506:                               '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$key.'</b>').'</td>'.
 8507:                               '<td class="LC_left_item"><table>'.$aliasinfo{$key}.
 8508:                               '</table></td></tr>';
 8509:                 $itemcount++;
 8510:             }
 8511:         }
 8512:     } else {
 8513:         my %ip_methods = &remoteip_methods();
 8514:         if ($setdom) {
 8515:             $itemcount ++;
 8516:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8517:             my ($nowafstyle,$wafstyle,$curr_remotip,$currwafdisplay,$vpndircheck,$vpnaliascheck,
 8518:                 $currwafvpn,$wafrangestyle,$alltossl,$ssltossl);
 8519:             $wafstyle = ' style="display:none;"';
 8520:             $nowafstyle = ' style="display:table-row;"';
 8521:             $currwafdisplay = ' style="display: none"';
 8522:             $wafrangestyle = ' style="display: none"';
 8523:             $curr_remotip = 'n';
 8524:             $ssltossl = ' checked="checked"';
 8525:             if ($showdom) {
 8526:                 $wafstyle = ' style="display:table-row;"';
 8527:                 $nowafstyle =  ' style="display:none;"';
 8528:                 if (keys(%{$values{$dom}})) {
 8529:                     if ($values{$dom}{remoteip} =~ /^[nmh]$/) {
 8530:                         $curr_remotip = $values{$dom}{remoteip};
 8531:                     }
 8532:                     if ($curr_remotip eq 'h') {
 8533:                         $currwafdisplay = ' style="display:table-row"';
 8534:                         $wafrangestyle = ' style="display:inline-block;"';
 8535:                     }
 8536:                     if ($values{$dom}{'sslopt'}) {
 8537:                         $alltossl = ' checked="checked"';
 8538:                         $ssltossl = '';
 8539:                     }
 8540:                 }
 8541:                 if (($values{$dom}{'vpnint'} ne '') || ($values{$dom}{'vpnext'} ne '')) {
 8542:                     $vpndircheck = ' checked="checked"';
 8543:                     $currwafvpn = ' style="display:table-row;"';
 8544:                     $wafrangestyle = ' style="display:inline-block;"';
 8545:                 } else {
 8546:                     $vpnaliascheck = ' checked="checked"';
 8547:                     $currwafvpn = ' style="display:none;"';
 8548:                 }
 8549:             }
 8550:             $datatable .= '<tr'.$css_class.' id="nowafproxyrow_'.$dom.'"'.$wafstyle.'>'.
 8551:                           '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'</td>'.
 8552:                           '<td class="LC_right_item">'.&mt('WAF not in use, nothing to set').'</td>'.
 8553:                           '</tr>'.
 8554:                           '<tr'.$css_class.' id="wafproxyrow_'.$dom.'"'.$wafstyle.'>'.
 8555:                           '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'<br /><br />'.
 8556:                           '<div id="wafproxyranges_'.$dom.'">'.&mt('Format for comma separated IP ranges').':<br />'.
 8557:                           &mt('A.B.C.D/N or A.B.C.D-E.F.G.H').'<br />'.
 8558:                           &mt('Range(s) stored in CIDR notation').'</div></td>'.
 8559:                           '<td class="LC_left_item"><table>'.
 8560:                           '<tr>'.
 8561:                           '<td valign="top">'.$lt{'remoteip'}.':&nbsp;'.
 8562:                           '<select name="wafproxy_remoteip" id="wafproxy_remoteip" onchange="javascript:updateWAF();">';
 8563:             foreach my $option ('m','h','n') {
 8564:                 my $sel;
 8565:                 if ($option eq $curr_remotip) {
 8566:                    $sel = ' selected="selected"';
 8567:                 }
 8568:                 $datatable .= '<option value="'.$option.'"'.$sel.'>'.
 8569:                               $ip_methods{$option}.'</option>';
 8570:             }
 8571:             $datatable .= '</select></td></tr>'."\n".
 8572:                           '<tr id="wafproxy_header"'.$currwafdisplay.'><td>'.
 8573:                           $lt{'ipheader'}.':&nbsp;'.
 8574:                           '<input type="text" value="'.$values{$dom}{'ipheader'}.'" '.
 8575:                           'name="wafproxy_ipheader" />'.
 8576:                           '</td></tr>'."\n".
 8577:                           '<tr id="wafproxy_trust"'.$currwafdisplay.'><td>'.
 8578:                           $lt{'trusted'}.':<br />'.
 8579:                           '<textarea name="wafproxy_trusted" rows="3" cols="80">'.
 8580:                           $values{$dom}{'trusted'}.'</textarea>'.
 8581:                           '</td></tr>'."\n".
 8582:                           '<tr><td><hr /></td></tr>'."\n".
 8583:                           '<tr>'.
 8584:                           '<td valign="top">'.$lt{'vpnaccess'}.':<br /><span class="LC_nobreak">'.
 8585:                           '<label><input type="radio" name="wafproxy_vpnaccess"'.$vpndircheck.' value="1" onclick="javascript:checkWAF();" />'.
 8586:                           $lt{'vpndirect'}.'</label>'.('&nbsp;'x2).
 8587:                           '<label><input type="radio" name="wafproxy_vpnaccess"'.$vpnaliascheck.' value="0" onclick="javascript:checkWAF();" />'.
 8588:                           $lt{'vpnaliased'}.'</label></span></td></tr>';
 8589:             foreach my $item ('vpnint','vpnext') {
 8590:                 $datatable .= '<tr id="wafproxy_show_'.$item.'"'.$currwafvpn.'>'.
 8591:                               '<td valign="top">'.$lt{$item}.':<br />'.
 8592:                               '<textarea name="wafproxy_'.$item.'" rows="3" cols="80">'.
 8593:                               $values{$dom}{$item}.'</textarea>'.
 8594:                               '</td></tr>'."\n";
 8595:             }
 8596:             $datatable .= '<tr><td><hr /></td></tr>'."\n".
 8597:                           '<tr>'.
 8598:                           '<td valign="top">'.$lt{'sslopt'}.':<br /><span class="LC_nobreak">'.
 8599:                           '<label><input type="radio" name="wafproxy_sslopt"'.$alltossl.' value="1" />'.
 8600:                           $lt{'alltossl'}.'</label>'.('&nbsp;'x2).
 8601:                           '<label><input type="radio" name="wafproxy_sslopt"'.$ssltossl.' value="0" />'.
 8602:                           $lt{'ssltossl'}.'</label></span></td></tr>'."\n".
 8603:                           '</table></td></tr>';
 8604:         }
 8605:         if (keys(%otherdoms)) {
 8606:             foreach my $domain (sort(keys(%otherdoms))) {
 8607:                 $itemcount ++;
 8608:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8609:                 $datatable .= '<tr'.$css_class.'>'.
 8610:                               '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$domain.'</b>').'</td>'.
 8611:                               '<td class="LC_left_item"><table>';
 8612:                 foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
 8613:                     my $showval = &mt('None');
 8614:                     if ($item eq 'ssl') {
 8615:                         $showval = $lt{'ssltossl'};
 8616:                     }
 8617:                     if ($values{$domain}{$item}) {
 8618:                         $showval = $values{$domain}{$item};
 8619:                         if ($item eq 'ssl') {
 8620:                             $showval = $lt{'alltossl'};
 8621:                         } elsif ($item eq 'remoteip') {
 8622:                             $showval = $ip_methods{$values{$domain}{$item}};
 8623:                         }
 8624:                     }
 8625:                     $datatable .= '<tr>'.
 8626:                                   '<td>'.$lt{$item}.':&nbsp;'.$showval.'</td></tr>';
 8627:                 }
 8628:                 $datatable .= '</table></td></tr>';
 8629:             }
 8630:         }
 8631:     }
 8632:     $$rowtotal += $itemcount;
 8633:     return $datatable;
 8634: }
 8635: 
 8636: sub wafproxy_titles {
 8637:     return &Apache::lonlocal::texthash(
 8638:                remoteip   => "Method for determining user's IP",
 8639:                ipheader   => 'Request header containing remote IP',
 8640:                trusted    => 'Trusted IP range(s)',
 8641:                vpnaccess  => 'Access from institutional VPN',
 8642:                vpndirect  => 'via regular hostname (no WAF)',
 8643:                vpnaliased => 'via aliased hostname (WAF)',
 8644:                vpnint     => 'Internal IP Range(s) for VPN sessions',
 8645:                vpnext     => 'IP Range(s) for backend WAF connections',
 8646:                sslopt     => 'Forwarding http/https',
 8647:                alltossl   => 'WAF forwards both http and https requests to https',
 8648:                ssltossl   => 'WAF forwards http requests to http and https to https',
 8649:            );
 8650: }
 8651: 
 8652: sub remoteip_methods {
 8653:     return &Apache::lonlocal::texthash(
 8654:               m => 'Use Apache mod_remoteip',
 8655:               h => 'Use headers parsed by LON-CAPA',
 8656:               n => 'Not in use',
 8657:            );
 8658: }
 8659: 
 8660: sub print_usersessions {
 8661:     my ($position,$dom,$settings,$rowtotal) = @_;
 8662:     my ($css_class,$datatable,$itemcount,%checked,%choices);
 8663:     my (%by_ip,%by_location,@intdoms,@instdoms);
 8664:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 8665: 
 8666:     my @alldoms = &Apache::lonnet::all_domains();
 8667:     my %serverhomes = %Apache::lonnet::serverhomeIDs;
 8668:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 8669:     my %altids = &id_for_thisdom(%servers);
 8670:     if ($position eq 'top') {
 8671:         if (keys(%serverhomes) > 1) {
 8672:             my %spareid = &current_offloads_to($dom,$settings,\%servers);
 8673:             my ($curroffloadnow,$curroffloadoth);
 8674:             if (ref($settings) eq 'HASH') {
 8675:                 if (ref($settings->{'offloadnow'}) eq 'HASH') {
 8676:                     $curroffloadnow = $settings->{'offloadnow'};
 8677:                 }
 8678:                 if (ref($settings->{'offloadoth'}) eq 'HASH') {
 8679:                     $curroffloadoth = $settings->{'offloadoth'};
 8680:                 }
 8681:             }
 8682:             my $other_insts = scalar(keys(%by_location));
 8683:             $datatable .= &spares_row($dom,\%servers,\%spareid,\%serverhomes,\%altids,
 8684:                                       $other_insts,$curroffloadnow,$curroffloadoth,$rowtotal);
 8685:         } else {
 8686:             $datatable .= '<tr'.$css_class.'><td colspan="2">'.
 8687:                           &mt('Nothing to set here, as the cluster to which this domain belongs only contains one server.').
 8688:                           '</td></tr>';
 8689:         }
 8690:     } else {
 8691:         my %titles = &usersession_titles();
 8692:         my ($prefix,@types);
 8693:         if ($position eq 'bottom') {
 8694:             $prefix = 'remote';
 8695:             @types = ('version','excludedomain','includedomain');
 8696:         } else {
 8697:             $prefix = 'hosted';
 8698:             @types = ('excludedomain','includedomain');
 8699:         }
 8700:         ($datatable,$itemcount) = &rules_by_location($settings,$prefix,\%by_location,\%by_ip,\@types,\%titles);
 8701:     }
 8702:     $$rowtotal += $itemcount;
 8703:     return $datatable;
 8704: }
 8705: 
 8706: sub rules_by_location {
 8707:     my ($settings,$prefix,$by_location,$by_ip,$types,$titles) = @_; 
 8708:     my ($datatable,$itemcount,$css_class);
 8709:     if (keys(%{$by_location}) == 0) {
 8710:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8711:         $datatable = '<tr'.$css_class.'><td colspan="2">'.
 8712:                      &mt('Nothing to set here, as the cluster to which this domain belongs only contains one institution.').
 8713:                      '</td></tr>';
 8714:         $itemcount = 1;
 8715:     } else {
 8716:         $itemcount = 0;
 8717:         my $numinrow = 5;
 8718:         my (%current,%checkedon,%checkedoff);
 8719:         my @locations = sort(keys(%{$by_location}));
 8720:         foreach my $type (@{$types}) {
 8721:             $checkedon{$type} = '';
 8722:             $checkedoff{$type} = ' checked="checked"';
 8723:         }
 8724:         if (ref($settings) eq 'HASH') {
 8725:             if (ref($settings->{$prefix}) eq 'HASH') {
 8726:                 foreach my $key (keys(%{$settings->{$prefix}})) {
 8727:                     $current{$key} = $settings->{$prefix}{$key};
 8728:                     if ($key eq 'version') {
 8729:                         if ($current{$key} ne '') {
 8730:                             $checkedon{$key} = ' checked="checked"';
 8731:                             $checkedoff{$key} = '';
 8732:                         }
 8733:                     } elsif (ref($current{$key}) eq 'ARRAY') {
 8734:                         $checkedon{$key} = ' checked="checked"';
 8735:                         $checkedoff{$key} = '';
 8736:                     }
 8737:                 }
 8738:             }
 8739:         }
 8740:         foreach my $type (@{$types}) {
 8741:             next if ($type ne 'version' && !@locations);
 8742:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8743:             $datatable .= '<tr'.$css_class.'>
 8744:                            <td><span class="LC_nobreak">'.$titles->{$type}.'</span><br />
 8745:                            <span class="LC_nobreak">&nbsp;
 8746:                            <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedoff{$type}.' value="0" />'.&mt('Not in use').'</label>&nbsp;
 8747:                            <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedon{$type}.' value="1" />'.&mt('In use').'</label></span></td><td>';
 8748:             if ($type eq 'version') {
 8749:                 my @lcversions = &Apache::lonnet::all_loncaparevs();
 8750:                 my $selector = '<select name="'.$prefix.'_version">';
 8751:                 foreach my $version (@lcversions) {
 8752:                     my $selected = '';
 8753:                     if ($current{'version'} eq $version) {
 8754:                         $selected = ' selected="selected"';
 8755:                     }
 8756:                     $selector .= ' <option value="'.$version.'"'.
 8757:                                  $selected.'>'.$version.'</option>';
 8758:                 }
 8759:                 $selector .= '</select> ';
 8760:                 $datatable .= &mt('remote server must be version: [_1] or later',$selector);
 8761:             } else {
 8762:                 $datatable.= '<div><input type="button" value="'.&mt('check all').'" '.
 8763:                              'onclick="javascript:checkAll(document.display.'.$prefix.'_'.$type.')"'.
 8764:                              ' />'.('&nbsp;'x2).
 8765:                              '<input type="button" value="'.&mt('uncheck all').'" '.
 8766:                              'onclick="javascript:uncheckAll(document.display.'.$prefix.'_'.$type.')" />'.
 8767:                              "\n".
 8768:                              '</div><div><table>';
 8769:                 my $rem;
 8770:                 for (my $i=0; $i<@locations; $i++) {
 8771:                     my ($showloc,$value,$checkedtype);
 8772:                     if (ref($by_location->{$locations[$i]}) eq 'ARRAY') {
 8773:                         my $ip = $by_location->{$locations[$i]}->[0];
 8774:                         if (ref($by_ip->{$ip}) eq 'ARRAY') {
 8775:                             $value = join(':',@{$by_ip->{$ip}});
 8776:                             $showloc = join(', ',@{$by_ip->{$ip}});
 8777:                             if (ref($current{$type}) eq 'ARRAY') {
 8778:                                 foreach my $loc (@{$by_ip->{$ip}}) {
 8779:                                     if (grep(/^\Q$loc\E$/,@{$current{$type}})) {
 8780:                                         $checkedtype = ' checked="checked"';
 8781:                                         last;
 8782:                                     }
 8783:                                 }
 8784:                             }
 8785:                         }
 8786:                     }
 8787:                     $rem = $i%($numinrow);
 8788:                     if ($rem == 0) {
 8789:                         if ($i > 0) {
 8790:                             $datatable .= '</tr>';
 8791:                         }
 8792:                         $datatable .= '<tr>';
 8793:                     }
 8794:                     $datatable .= '<td class="LC_left_item">'.
 8795:                                   '<span class="LC_nobreak"><label>'.
 8796:                                   '<input type="checkbox" name="'.$prefix.'_'.$type.
 8797:                                   '" value="'.$value.'"'.$checkedtype.' />'.$showloc.
 8798:                                   '</label></span></td>';
 8799:                 }
 8800:                 $rem = @locations%($numinrow);
 8801:                 my $colsleft = $numinrow - $rem;
 8802:                 if ($colsleft > 1 ) {
 8803:                     $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 8804:                                   '&nbsp;</td>';
 8805:                 } elsif ($colsleft == 1) {
 8806:                     $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 8807:                 }
 8808:                 $datatable .= '</tr></table>';
 8809:             }
 8810:             $datatable .= '</td></tr>';
 8811:             $itemcount ++;
 8812:         }
 8813:     }
 8814:     return ($datatable,$itemcount);
 8815: }
 8816: 
 8817: sub print_ssl {
 8818:     my ($position,$dom,$settings,$rowtotal) = @_;
 8819:     my ($css_class,$datatable);
 8820:     my $itemcount = 1;
 8821:     if ($position eq 'top') {
 8822:         my $primary_id = &Apache::lonnet::domain($dom,'primary');
 8823:         my $intdom = &Apache::lonnet::internet_dom($primary_id);
 8824:         my $same_institution;
 8825:         if ($intdom ne '') {
 8826:             my $internet_names = &Apache::lonnet::get_internet_names($Apache::lonnet::perlvar{'lonHostID'});
 8827:             if (ref($internet_names) eq 'ARRAY') {
 8828:                 if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
 8829:                     $same_institution = 1;
 8830:                 }
 8831:             }
 8832:         }
 8833:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8834:         $datatable = '<tr'.$css_class.'><td colspan="2">';
 8835:         if ($same_institution) {
 8836:             my %domservers = &Apache::lonnet::get_servers($dom);
 8837:             $datatable .= &LONCAPA::SSL::print_certstatus(\%domservers,'web','domprefs');
 8838:         } else {
 8839:             $datatable .= &mt("You need to be logged into one of your own domain's servers to display information about the status of LON-CAPA SSL certificates.");
 8840:         }
 8841:         $datatable .= '</td></tr>';
 8842:         $itemcount ++;
 8843:     } else {
 8844:         my %titles = &ssl_titles();
 8845:         my (%by_ip,%by_location,@intdoms,@instdoms);
 8846:         &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 8847:         my @alldoms = &Apache::lonnet::all_domains();
 8848:         my %serverhomes = %Apache::lonnet::serverhomeIDs;
 8849:         my @domservers = &Apache::lonnet::get_servers($dom);
 8850:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 8851:         my %altids = &id_for_thisdom(%servers);
 8852:         if (($position eq 'connto') || ($position eq 'connfrom')) {
 8853:             my $legacy;
 8854:             unless (ref($settings) eq 'HASH') {
 8855:                 my $name;
 8856:                 if ($position eq 'connto') {
 8857:                     $name = 'loncAllowInsecure';
 8858:                 } else {
 8859:                     $name = 'londAllowInsecure';
 8860:                 }
 8861:                 my $primarylibserv = &Apache::lonnet::domain($dom,'primary');
 8862:                 my @ids=&Apache::lonnet::current_machine_ids();
 8863:                 if (($primarylibserv ne '') && (!grep(/^\Q$primarylibserv\E$/,@ids))) {
 8864:                     my %what = (
 8865:                                    $name => 1,
 8866:                                );
 8867:                     my ($result,$returnhash) =
 8868:                         &Apache::lonnet::get_remote_globals($primarylibserv,\%what);
 8869:                     if ($result eq 'ok') {
 8870:                         if (ref($returnhash) eq 'HASH') {
 8871:                             $legacy = $returnhash->{$name};
 8872:                         }
 8873:                     }
 8874:                 } else {
 8875:                     $legacy = $Apache::lonnet::perlvar{$name};
 8876:                 }
 8877:             }
 8878:             foreach my $type ('dom','intdom','other') {
 8879:                 my %checked;
 8880:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8881:                 $datatable .= '<tr'.$css_class.'><td>'.$titles{$type}.'</td>'.
 8882:                               '<td class="LC_right_item">';
 8883:                 my $skip; 
 8884:                 if ($type eq 'dom') {
 8885:                     unless (keys(%servers) > 1) {
 8886:                         $datatable .= &mt('Nothing to set here, as there are no other servers/VMs');    
 8887:                         $skip = 1;
 8888:                     }
 8889:                 }
 8890:                 if ($type eq 'intdom') {
 8891:                     unless (@instdoms > 1) {
 8892:                         $datatable .= &mt('Nothing to set here, as there are no other domains for this institution');
 8893:                         $skip = 1;
 8894:                     } 
 8895:                 } elsif ($type eq 'other') {
 8896:                     if (keys(%by_location) == 0) {
 8897:                         $datatable .= &mt('Nothing to set here, as there are no other institutions');
 8898:                         $skip = 1;
 8899:                     }
 8900:                 }
 8901:                 unless ($skip) {
 8902:                     $checked{'yes'} = ' checked="checked"'; 
 8903:                     if (ref($settings) eq 'HASH') {
 8904:                         if (ref($settings->{$position}) eq 'HASH') {
 8905:                             if ($settings->{$position}->{$type} =~ /^(no|req)$/) {
 8906:                                 $checked{$1} = $checked{'yes'};
 8907:                                 delete($checked{'yes'}); 
 8908:                             }
 8909:                         }
 8910:                     } else {
 8911:                         if ($legacy == 0) {
 8912:                             $checked{'req'} = $checked{'yes'};
 8913:                             delete($checked{'yes'});    
 8914:                         }
 8915:                     }
 8916:                     foreach my $option ('no','yes','req') {
 8917:                         $datatable .= '<span class="LC_nobreak"><label>'.
 8918:                                       '<input type="radio" name="'.$position.'_'.$type.'" '.
 8919:                                       'value="'.$option.'"'.$checked{$option}.' />'.$titles{$option}.
 8920:                                       '</label></span>'.('&nbsp;'x2);
 8921:                     }
 8922:                 }
 8923:                 $datatable .= '</td></tr>';
 8924:                 $itemcount ++; 
 8925:             }
 8926:         } else {
 8927:             my $prefix = 'replication';
 8928:             my @types = ('certreq','nocertreq');
 8929:             if (keys(%by_location) == 0) {
 8930:                 $datatable .= '<tr'.$css_class.'><td>'.
 8931:                               &mt('Nothing to set here, as there are no other institutions').
 8932:                               '</td></tr>';
 8933:                 $itemcount ++;
 8934:             } else {
 8935:                 ($datatable,$itemcount) = 
 8936:                     &rules_by_location($settings,$prefix,\%by_location,\%by_ip,\@types,\%titles);
 8937:             }
 8938:         }
 8939:     }
 8940:     $$rowtotal += $itemcount;
 8941:     return $datatable;
 8942: }
 8943: 
 8944: sub ssl_titles {
 8945:     return &Apache::lonlocal::texthash (
 8946:                dom           => 'LON-CAPA servers/VMs from same domain',
 8947:                intdom        => 'LON-CAPA servers/VMs from same "internet" domain',
 8948:                other         => 'External LON-CAPA servers/VMs',
 8949:                connto        => 'Connections to other servers',
 8950:                connfrom      => 'Connections from other servers',
 8951:                replication   => 'Replicating content to other institutions',
 8952:                certreq       => 'Client certificate required, but specific domains exempt',
 8953:                nocertreq     => 'No client certificate required, except for specific domains',
 8954:                no            => 'SSL not used',
 8955:                yes           => 'SSL Optional (used if available)',
 8956:                req           => 'SSL Required',
 8957:     );
 8958: }
 8959: 
 8960: sub print_trust {
 8961:     my ($prefix,$dom,$settings,$rowtotal) = @_;
 8962:     my ($css_class,$datatable,%checked,%choices);
 8963:     my (%by_ip,%by_location,@intdoms,@instdoms);
 8964:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 8965:     my $itemcount = 1;
 8966:     my %titles = &trust_titles();
 8967:     my @types = ('exc','inc');
 8968:     if ($prefix eq 'top') {
 8969:         $prefix = 'content';
 8970:     } elsif ($prefix eq 'bottom') {
 8971:         $prefix = 'msg';
 8972:     }
 8973:     ($datatable,$itemcount) = &rules_by_location($settings,$prefix,\%by_location,\%by_ip,\@types,\%titles);
 8974:     $$rowtotal += $itemcount;
 8975:     return $datatable;
 8976: }
 8977: 
 8978: sub trust_titles {
 8979:     return &Apache::lonlocal::texthash(
 8980:                content  => "Access to this domain's content by others",
 8981:                shared   => "Access to other domain's content by this domain",
 8982:                enroll   => "Enrollment in this domain's courses by others", 
 8983:                othcoau  => "Co-author roles in this domain for others",
 8984:                coaurem  => "Co-author roles for this domain's users elsewhere", 
 8985:                domroles => "Domain roles in this domain assignable to others",
 8986:                catalog  => "Course Catalog for this domain displayed elsewhere",
 8987:                reqcrs   => "Requests for creation of courses in this domain by others",
 8988:                msg      => "Users in other domains can send messages to this domain",
 8989:                exc      => "Allow all, but exclude specific domains",
 8990:                inc      => "Deny all, but include specific domains",
 8991:            );
 8992: } 
 8993: 
 8994: sub build_location_hashes {
 8995:     my ($intdoms,$by_ip,$by_location,$instdoms) = @_;
 8996:     return unless((ref($intdoms) eq 'ARRAY') && (ref($by_ip) eq 'HASH') &&
 8997:                   (ref($by_location) eq 'HASH') && (ref($instdoms) eq 'ARRAY'));
 8998:     my %iphost = &Apache::lonnet::get_iphost();
 8999:     my $primary_id = &Apache::lonnet::domain($env{'request.role.domain'},'primary');
 9000:     my $primary_ip = &Apache::lonnet::get_host_ip($primary_id);
 9001:     if (ref($iphost{$primary_ip}) eq 'ARRAY') {
 9002:         foreach my $id (@{$iphost{$primary_ip}}) {
 9003:             my $intdom = &Apache::lonnet::internet_dom($id);
 9004:             unless(grep(/^\Q$intdom\E$/,@{$intdoms})) {
 9005:                 push(@{$intdoms},$intdom);
 9006:             }
 9007:         }
 9008:     }
 9009:     foreach my $ip (keys(%iphost)) {
 9010:         if (ref($iphost{$ip}) eq 'ARRAY') {
 9011:             foreach my $id (@{$iphost{$ip}}) {
 9012:                 my $location = &Apache::lonnet::internet_dom($id);
 9013:                 if ($location) {
 9014:                     if (grep(/^\Q$location\E$/,@{$intdoms})) {
 9015:                         my $dom = &Apache::lonnet::host_domain($id);
 9016:                         unless (grep(/^\Q$dom\E/,@{$instdoms})) {
 9017:                             push(@{$instdoms},$dom);
 9018:                         }
 9019:                         next;
 9020:                     }
 9021:                     if (ref($by_ip->{$ip}) eq 'ARRAY') {
 9022:                         unless(grep(/^\Q$location\E$/,@{$by_ip->{$ip}})) {
 9023:                             push(@{$by_ip->{$ip}},$location);
 9024:                         }
 9025:                     } else {
 9026:                         $by_ip->{$ip} = [$location];
 9027:                     }
 9028:                 }
 9029:             }
 9030:         }
 9031:     }
 9032:     foreach my $ip (sort(keys(%{$by_ip}))) {
 9033:         if (ref($by_ip->{$ip}) eq 'ARRAY') {
 9034:             @{$by_ip->{$ip}} = sort(@{$by_ip->{$ip}});
 9035:             my $first = $by_ip->{$ip}->[0];
 9036:             if (ref($by_location->{$first}) eq 'ARRAY') {
 9037:                 unless (grep(/^\Q$ip\E$/,@{$by_location->{$first}})) {
 9038:                     push(@{$by_location->{$first}},$ip);
 9039:                 }
 9040:             } else {
 9041:                 $by_location->{$first} = [$ip];
 9042:             }
 9043:         }
 9044:     }
 9045:     return;
 9046: }
 9047: 
 9048: sub current_offloads_to {
 9049:     my ($dom,$settings,$servers) = @_;
 9050:     my (%spareid,%otherdomconfigs);
 9051:     if (ref($servers) eq 'HASH') {
 9052:         foreach my $lonhost (sort(keys(%{$servers}))) {
 9053:             my $gotspares;
 9054:             if (ref($settings) eq 'HASH') {
 9055:                 if (ref($settings->{'spares'}) eq 'HASH') {
 9056:                     if (ref($settings->{'spares'}{$lonhost}) eq 'HASH') {
 9057:                         $spareid{$lonhost}{'primary'} = $settings->{'spares'}{$lonhost}{'primary'};
 9058:                         $spareid{$lonhost}{'default'} = $settings->{'spares'}{$lonhost}{'default'};
 9059:                         $gotspares = 1;
 9060:                     }
 9061:                 }
 9062:             }
 9063:             unless ($gotspares) {
 9064:                 my $gotspares;
 9065:                 my $serverhomeID =
 9066:                     &Apache::lonnet::get_server_homeID($servers->{$lonhost});
 9067:                 my $serverhomedom =
 9068:                     &Apache::lonnet::host_domain($serverhomeID);
 9069:                 if ($serverhomedom ne $dom) {
 9070:                     if (ref($otherdomconfigs{$serverhomedom} eq 'HASH')) {
 9071:                         if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 9072:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 9073:                                 $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 9074:                                 $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 9075:                                 $gotspares = 1;
 9076:                             }
 9077:                         }
 9078:                     } else {
 9079:                         $otherdomconfigs{$serverhomedom} =
 9080:                             &Apache::lonnet::get_dom('configuration',['usersessions'],$serverhomedom);
 9081:                         if (ref($otherdomconfigs{$serverhomedom}) eq 'HASH') {
 9082:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 9083:                                 if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 9084:                                     if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{$lonhost}) eq 'HASH') {
 9085:                                         $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 9086:                                         $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 9087:                                         $gotspares = 1;
 9088:                                     }
 9089:                                 }
 9090:                             }
 9091:                         }
 9092:                     }
 9093:                 }
 9094:             }
 9095:             unless ($gotspares) {
 9096:                 if ($lonhost eq $Apache::lonnet::perlvar{'lonHostID'}) {
 9097:                     $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 9098:                     $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 9099:                } else {
 9100:                     my $server_hostname = &Apache::lonnet::hostname($lonhost);
 9101:                     my $server_homeID = &Apache::lonnet::get_server_homeID($server_hostname);
 9102:                     if ($server_homeID eq $Apache::lonnet::perlvar{'lonHostID'}) {
 9103:                         $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 9104:                         $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 9105:                     } else {
 9106:                         my %what = (
 9107:                              spareid => 1,
 9108:                         );
 9109:                         my ($result,$returnhash) = 
 9110:                             &Apache::lonnet::get_remote_globals($lonhost,\%what);
 9111:                         if ($result eq 'ok') { 
 9112:                             if (ref($returnhash) eq 'HASH') {
 9113:                                 if (ref($returnhash->{'spareid'}) eq 'HASH') {
 9114:                                     $spareid{$lonhost}{'primary'} = $returnhash->{'spareid'}->{'primary'};
 9115:                                     $spareid{$lonhost}{'default'} = $returnhash->{'spareid'}->{'default'};
 9116:                                 }
 9117:                             }
 9118:                         }
 9119:                     }
 9120:                 }
 9121:             }
 9122:         }
 9123:     }
 9124:     return %spareid;
 9125: }
 9126: 
 9127: sub spares_row {
 9128:     my ($dom,$servers,$spareid,$serverhomes,$altids,$other_insts,
 9129:         $curroffloadnow,$curroffloadoth,$rowtotal) = @_;
 9130:     my $css_class;
 9131:     my $numinrow = 4;
 9132:     my $itemcount = 1;
 9133:     my $datatable;
 9134:     my %typetitles = &sparestype_titles();
 9135:     if ((ref($servers) eq 'HASH') && (ref($spareid) eq 'HASH') && (ref($altids) eq 'HASH')) {
 9136:         foreach my $server (sort(keys(%{$servers}))) {
 9137:             my $serverhome = &Apache::lonnet::get_server_homeID($servers->{$server});
 9138:             my ($othercontrol,$serverdom);
 9139:             if ($serverhome ne $server) {
 9140:                 $serverdom = &Apache::lonnet::host_domain($serverhome);
 9141:                 $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 9142:             } else {
 9143:                 $serverdom = &Apache::lonnet::host_domain($server);
 9144:                 if ($serverdom ne $dom) {
 9145:                     $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 9146:                 }
 9147:             }
 9148:             next unless (ref($spareid->{$server}) eq 'HASH');
 9149:             my ($checkednow,$checkedoth);
 9150:             if (ref($curroffloadnow) eq 'HASH') {
 9151:                 if ($curroffloadnow->{$server}) {
 9152:                     $checkednow = ' checked="checked"';
 9153:                 }
 9154:             }
 9155:             if (ref($curroffloadoth) eq 'HASH') {
 9156:                 if ($curroffloadoth->{$server}) {
 9157:                     $checkedoth = ' checked="checked"';
 9158:                 }
 9159:             }
 9160:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 9161:             $datatable .= '<tr'.$css_class.'>
 9162:                            <td rowspan="2">
 9163:                             <span class="LC_nobreak">'.
 9164:                           &mt('[_1] when busy, offloads to:'
 9165:                               ,'<b>'.$server.'</b>').'</span><br />'.
 9166:                           '<span class="LC_nobreak">'."\n".
 9167:                           '<label><input type="checkbox" name="offloadnow" value="'.$server.'"'.$checkednow.' />'.
 9168:                           '&nbsp;'.&mt('Switch any active user on next access').'</label></span>'.
 9169:                           "\n";
 9170:             if ($other_insts) {
 9171:                 $datatable .= '<br />'.
 9172:                               '<span class="LC_nobreak">'."\n".
 9173:                           '<label><input type="checkbox" name="offloadoth" value="'.$server.'"'.$checkedoth.' />'.
 9174:                           '&nbsp;'.&mt('Switch other institutions on next access').'</label></span>'.
 9175:                           "\n";
 9176:             }
 9177:             my (%current,%canselect);
 9178:             my @choices = 
 9179:                 &possible_newspares($server,$spareid->{$server},$serverhomes,$altids);
 9180:             foreach my $type ('primary','default') {
 9181:                 if (ref($spareid->{$server}) eq 'HASH') {
 9182:                     if (ref($spareid->{$server}{$type}) eq 'ARRAY') {
 9183:                         my @spares = @{$spareid->{$server}{$type}};
 9184:                         if (@spares > 0) {
 9185:                             if ($othercontrol) {
 9186:                                 $current{$type} = join(', ',@spares);
 9187:                             } else {
 9188:                                 $current{$type} .= '<table>';
 9189:                                 my $numspares = scalar(@spares);
 9190:                                 for (my $i=0;  $i<@spares; $i++) {
 9191:                                     my $rem = $i%($numinrow);
 9192:                                     if ($rem == 0) {
 9193:                                         if ($i > 0) {
 9194:                                             $current{$type} .= '</tr>';
 9195:                                         }
 9196:                                         $current{$type} .= '<tr>';
 9197:                                     }
 9198:                                     $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;'.
 9199:                                                        $spareid->{$server}{$type}[$i].
 9200:                                                        '</label></td>'."\n";
 9201:                                 }
 9202:                                 my $rem = @spares%($numinrow);
 9203:                                 my $colsleft = $numinrow - $rem;
 9204:                                 if ($colsleft > 1 ) {
 9205:                                     $current{$type} .= '<td colspan="'.$colsleft.
 9206:                                                        '" class="LC_left_item">'.
 9207:                                                        '&nbsp;</td>';
 9208:                                 } elsif ($colsleft == 1) {
 9209:                                     $current{$type} .= '<td class="LC_left_item">&nbsp;</td>'."\n";
 9210:                                 }
 9211:                                 $current{$type} .= '</tr></table>';
 9212:                             }
 9213:                         }
 9214:                     }
 9215:                     if ($current{$type} eq '') {
 9216:                         $current{$type} = &mt('None specified');
 9217:                     }
 9218:                     if ($othercontrol) {
 9219:                         if ($type eq 'primary') {
 9220:                             $canselect{$type} = $othercontrol;
 9221:                         }
 9222:                     } else {
 9223:                         $canselect{$type} = 
 9224:                             &mt('Add new [_1]'.$type.'[_2]:','<i>','</i>').'&nbsp;'.
 9225:                             '<select name="newspare_'.$type.'_'.$server.'" '.
 9226:                             'id="newspare_'.$type.'_'.$server.'" onchange="checkNewSpares('."'$server','$type'".');">'."\n".
 9227:                             '<option value="" selected ="selected">'.&mt('Select').'</option>'."\n";
 9228:                         if (@choices > 0) {
 9229:                             foreach my $lonhost (@choices) {
 9230:                                 $canselect{$type} .= '<option value="'.$lonhost.'">'.$lonhost.'</option>'."\n";
 9231:                             }
 9232:                         }
 9233:                         $canselect{$type} .= '</select>'."\n";
 9234:                     }
 9235:                 } else {
 9236:                     $current{$type} = &mt('Could not be determined');
 9237:                     if ($type eq 'primary') {
 9238:                         $canselect{$type} =  $othercontrol;
 9239:                     }
 9240:                 }
 9241:                 if ($type eq 'default') {
 9242:                     $datatable .= '<tr'.$css_class.'>';
 9243:                 }
 9244:                 $datatable .= '<td><i>'.$typetitles{$type}.'</i></td>'."\n".
 9245:                               '<td>'.$current{$type}.'</td>'."\n".
 9246:                               '<td>'.$canselect{$type}.'</td></tr>'."\n";
 9247:             }
 9248:             $itemcount ++;
 9249:         }
 9250:     }
 9251:     $$rowtotal += $itemcount;
 9252:     return $datatable;
 9253: }
 9254: 
 9255: sub possible_newspares {
 9256:     my ($server,$currspares,$serverhomes,$altids) = @_;
 9257:     my $serverhostname = &Apache::lonnet::hostname($server);
 9258:     my %excluded;
 9259:     if ($serverhostname ne '') {
 9260:         %excluded = (
 9261:                        $serverhostname => 1,
 9262:                     );
 9263:     }
 9264:     if (ref($currspares) eq 'HASH') {
 9265:         foreach my $type (keys(%{$currspares})) {
 9266:             if (ref($currspares->{$type}) eq 'ARRAY') {
 9267:                 if (@{$currspares->{$type}} > 0) {
 9268:                     foreach my $curr (@{$currspares->{$type}}) {
 9269:                         my $hostname = &Apache::lonnet::hostname($curr);
 9270:                         $excluded{$hostname} = 1;
 9271:                     }
 9272:                 }
 9273:             }
 9274:         }
 9275:     }
 9276:     my @choices;
 9277:     if ((ref($serverhomes) eq 'HASH') && (ref($altids) eq 'HASH')) {
 9278:         if (keys(%{$serverhomes}) > 1) {
 9279:             foreach my $name (sort(keys(%{$serverhomes}))) {
 9280:                 unless ($excluded{$name}) {
 9281:                     if (exists($altids->{$serverhomes->{$name}})) {
 9282:                         push(@choices,$altids->{$serverhomes->{$name}});
 9283:                     } else {
 9284:                         push(@choices,$serverhomes->{$name});
 9285:                     }
 9286:                 }
 9287:             }
 9288:         }
 9289:     }
 9290:     return sort(@choices);
 9291: }
 9292: 
 9293: sub print_loadbalancing {
 9294:     my ($dom,$settings,$rowtotal) = @_;
 9295:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
 9296:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
 9297:     my $numinrow = 1;
 9298:     my $datatable;
 9299:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 9300:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
 9301:     if (ref($settings) eq 'HASH') {
 9302:         %existing = %{$settings};
 9303:     }
 9304:     if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
 9305:         &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
 9306:                                   \%currtargets,\%currrules,\%currcookies);
 9307:     } else {
 9308:         return;
 9309:     }
 9310:     my ($othertitle,$usertypes,$types) =
 9311:         &Apache::loncommon::sorted_inst_types($dom);
 9312:     my $rownum = 8;
 9313:     if (ref($types) eq 'ARRAY') {
 9314:         $rownum += scalar(@{$types});
 9315:     }
 9316:     my @css_class = ('LC_odd_row','LC_even_row');
 9317:     my $balnum = 0;
 9318:     my $islast;
 9319:     my (@toshow,$disabledtext);
 9320:     if (keys(%currbalancer) > 0) {
 9321:         @toshow = sort(keys(%currbalancer));
 9322:         if (scalar(@toshow) < scalar(keys(%servers)) + 1) {
 9323:             push(@toshow,'');
 9324:         }
 9325:     } else {
 9326:         @toshow = ('');
 9327:         $disabledtext = &mt('No existing load balancer');
 9328:     }
 9329:     foreach my $lonhost (@toshow) {
 9330:         if ($balnum == scalar(@toshow)-1) {
 9331:             $islast = 1;
 9332:         } else {
 9333:             $islast = 0;
 9334:         }
 9335:         my $cssidx = $balnum%2;
 9336:         my $targets_div_style = 'display: none';
 9337:         my $disabled_div_style = 'display: block';
 9338:         my $homedom_div_style = 'display: none';
 9339:         $datatable .= '<tr class="'.$css_class[$cssidx].'">'.
 9340:                       '<td rowspan="'.$rownum.'" style="vertical-align: top">'.
 9341:                       '<p>';
 9342:         if ($lonhost eq '') {
 9343:             $datatable .= '<span class="LC_nobreak">';
 9344:             if (keys(%currbalancer) > 0) {
 9345:                 $datatable .= &mt('Add balancer:');
 9346:             } else {
 9347:                 $datatable .= &mt('Enable balancer:');
 9348:             }
 9349:             $datatable .= '&nbsp;'.
 9350:                           '<select name="loadbalancing_lonhost_'.$balnum.'"'.
 9351:                           ' id="loadbalancing_lonhost_'.$balnum.'"'.
 9352:                           ' onchange="toggleTargets('."'$balnum'".');">'."\n".
 9353:                           '<option value="" selected="selected">'.&mt('None').
 9354:                           '</option>'."\n";
 9355:             foreach my $server (sort(keys(%servers))) {
 9356:                 next if ($currbalancer{$server});
 9357:                 $datatable .= '<option value="'.$server.'">'.$server.'</option>'."\n";
 9358:             }
 9359:             $datatable .=
 9360:                 '</select>'."\n".
 9361:                 '<input type="hidden" name="loadbalancing_prevlonhost_'.$balnum.'" id="loadbalancing_prevlonhost_'.$balnum.'" value="" />&nbsp;</span>'."\n";
 9362:         } else {
 9363:             $datatable .= '<i>'.$lonhost.'</i><br /><span class="LC_nobreak">'.
 9364:                           '<label><input type="checkbox" name="loadbalancing_delete" value="'.$balnum.'" id="loadbalancing_delete_'.$balnum.'" onclick="javascript:balancerDeleteChange('."'$balnum'".');" />&nbsp;'.
 9365:                            &mt('Stop balancing').'</label>'.
 9366:                            '<input type="hidden" name="loadbalancing_lonhost_'.$balnum.'" value="'.$lonhost.'" id="loadbalancing_lonhost_'.$balnum.'" /></span>';
 9367:             $targets_div_style = 'display: block';
 9368:             $disabled_div_style = 'display: none';
 9369:             if ($dom eq &Apache::lonnet::host_domain($lonhost)) {
 9370:                 $homedom_div_style = 'display: block';
 9371:             }
 9372:         }
 9373:         $datatable .= '</p></td><td rowspan="'.$rownum.'" style="vertical-align: top">'.
 9374:                   '<div id="loadbalancing_disabled_'.$balnum.'" style="'.
 9375:                   $disabled_div_style.'">'.$disabledtext.'</div>'."\n".
 9376:                   '<div id="loadbalancing_targets_'.$balnum.'" style="'.$targets_div_style.'">'.&mt('Offloads to:').'<br />';
 9377:         my ($numspares,@spares) = &count_servers($lonhost,%servers);
 9378:         my @sparestypes = ('primary','default');
 9379:         my %typetitles = &sparestype_titles();
 9380:         my %hostherechecked = (
 9381:                                   no => ' checked="checked"',
 9382:                               );
 9383:         my %balcookiechecked = (
 9384:                                   no => ' checked="checked"', 
 9385:                                );
 9386:         foreach my $sparetype (@sparestypes) {
 9387:             my $targettable;
 9388:             for (my $i=0; $i<$numspares; $i++) {
 9389:                 my $checked;
 9390:                 if (ref($currtargets{$lonhost}) eq 'HASH') {
 9391:                     if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 9392:                         if (grep(/^\Q$spares[$i]\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 9393:                             $checked = ' checked="checked"';
 9394:                         }
 9395:                     }
 9396:                 }
 9397:                 my ($chkboxval,$disabled);
 9398:                 if (($lonhost ne '') && (exists($servers{$lonhost}))) {
 9399:                     $chkboxval = $spares[$i];
 9400:                 }
 9401:                 if (exists($currbalancer{$spares[$i]})) {
 9402:                     $disabled = ' disabled="disabled"';
 9403:                 }
 9404:                 $targettable .=
 9405:                     '<td><span class="LC_nobreak"><label>'.
 9406:                     '<input type="checkbox" name="loadbalancing_target_'.$balnum.'_'.$sparetype.'"'.
 9407:                     $checked.$disabled.' value="'.$chkboxval.'" id="loadbalancing_target_'.$balnum.'_'.$sparetype.'_'.$i.'" onclick="checkOffloads('."this,'$balnum','$sparetype'".');" /><span id="loadbalancing_targettxt_'.$balnum.'_'.$sparetype.'_'.$i.'">&nbsp;'.$chkboxval.
 9408:                     '</span></label></span></td>';
 9409:                 my $rem = $i%($numinrow);
 9410:                 if ($rem == 0) {
 9411:                     if (($i > 0) && ($i < $numspares-1)) {
 9412:                         $targettable .= '</tr>';
 9413:                     }
 9414:                     if ($i < $numspares-1) {
 9415:                         $targettable .= '<tr>';
 9416:                     }
 9417:                 }
 9418:             }
 9419:             if ($targettable ne '') {
 9420:                 my $rem = $numspares%($numinrow);
 9421:                 my $colsleft = $numinrow - $rem;
 9422:                 if ($colsleft > 1 ) {
 9423:                     $targettable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 9424:                                     '&nbsp;</td>';
 9425:                 } elsif ($colsleft == 1) {
 9426:                     $targettable .= '<td class="LC_left_item">&nbsp;</td>';
 9427:                 }
 9428:                 $datatable .=  '<i>'.$typetitles{$sparetype}.'</i><br />'.
 9429:                                '<table><tr>'.$targettable.'</tr></table><br />';
 9430:             }
 9431:             $hostherechecked{$sparetype} = '';
 9432:             if (ref($currtargets{$lonhost}) eq 'HASH') {
 9433:                 if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 9434:                     if (grep(/^\Q$lonhost\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 9435:                         $hostherechecked{$sparetype} = ' checked="checked"';
 9436:                         $hostherechecked{'no'} = '';
 9437:                     }
 9438:                 }
 9439:             }
 9440:         }
 9441:         if ($currcookies{$lonhost}) {
 9442:             %balcookiechecked = (
 9443:                                     yes => ' checked="checked"',
 9444:                                 );
 9445:         }
 9446:         $datatable .= &mt('Hosting on balancer itself').'<br />'.
 9447:                       '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" value="no"'.
 9448:                       $hostherechecked{'no'}.' />'.&mt('No').'</label><br />';
 9449:         foreach my $sparetype (@sparestypes) {
 9450:             $datatable .= '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" '.
 9451:                           'value="'.$sparetype.'"'.$hostherechecked{$sparetype}.' /><i>'.$typetitles{$sparetype}.
 9452:                           '</i></label><br />';
 9453:         }
 9454:         $datatable .= &mt('Use balancer cookie').'<br />'.
 9455:                       '<label><input type="radio" name="loadbalancing_cookie_'.$balnum.'" value="1"'.
 9456:                       $balcookiechecked{'yes'}.' />'.&mt('Yes').'</label><br />'.
 9457:                       '<label><input type="radio" name="loadbalancing_cookie_'.$balnum.'" value="0"'.
 9458:                       $balcookiechecked{'no'}.' />'.&mt('No').'</label><br />'.
 9459:                       '</div></td></tr>'.
 9460:                       &loadbalancing_rules($dom,$intdom,$currrules{$lonhost},
 9461:                                            $othertitle,$usertypes,$types,\%servers,
 9462:                                            \%currbalancer,$lonhost,
 9463:                                            $targets_div_style,$homedom_div_style,
 9464:                                            $css_class[$cssidx],$balnum,$islast);
 9465:         $$rowtotal += $rownum;
 9466:         $balnum ++;
 9467:     }
 9468:     $datatable .= '<input type="hidden" name="loadbalancing_total" id="loadbalancing_total" value="'.$balnum.'" />';
 9469:     return $datatable;
 9470: }
 9471: 
 9472: sub get_loadbalancers_config {
 9473:     my ($servers,$existing,$currbalancer,$currtargets,$currrules,$currcookies) = @_;
 9474:     return unless ((ref($servers) eq 'HASH') &&
 9475:                    (ref($existing) eq 'HASH') && (ref($currbalancer) eq 'HASH') &&
 9476:                    (ref($currtargets) eq 'HASH') && (ref($currrules) eq 'HASH') &&
 9477:                    (ref($currcookies) eq 'HASH'));
 9478:     if (keys(%{$existing}) > 0) {
 9479:         my $oldlonhost;
 9480:         foreach my $key (sort(keys(%{$existing}))) {
 9481:             if ($key eq 'lonhost') {
 9482:                 $oldlonhost = $existing->{'lonhost'};
 9483:                 $currbalancer->{$oldlonhost} = 1;
 9484:             } elsif ($key eq 'targets') {
 9485:                 if ($oldlonhost) {
 9486:                     $currtargets->{$oldlonhost} = $existing->{'targets'};
 9487:                 }
 9488:             } elsif ($key eq 'rules') {
 9489:                 if ($oldlonhost) {
 9490:                     $currrules->{$oldlonhost} = $existing->{'rules'};
 9491:                 }
 9492:             } elsif (ref($existing->{$key}) eq 'HASH') {
 9493:                 $currbalancer->{$key} = 1;
 9494:                 $currtargets->{$key} = $existing->{$key}{'targets'};
 9495:                 $currrules->{$key} = $existing->{$key}{'rules'};
 9496:                 if ($existing->{$key}{'cookie'}) {
 9497:                     $currcookies->{$key} = 1;
 9498:                 }
 9499:             }
 9500:         }
 9501:     } else {
 9502:         my ($balancerref,$targetsref) =
 9503:                 &Apache::lonnet::get_lonbalancer_config($servers);
 9504:         if ((ref($balancerref) eq 'HASH') && (ref($targetsref) eq 'HASH')) {
 9505:             foreach my $server (sort(keys(%{$balancerref}))) {
 9506:                 $currbalancer->{$server} = 1;
 9507:                 $currtargets->{$server} = $targetsref->{$server};
 9508:             }
 9509:         }
 9510:     }
 9511:     return;
 9512: }
 9513: 
 9514: sub loadbalancing_rules {
 9515:     my ($dom,$intdom,$currrules,$othertitle,$usertypes,$types,$servers,
 9516:         $currbalancer,$lonhost,$targets_div_style,$homedom_div_style,
 9517:         $css_class,$balnum,$islast) = @_;
 9518:     my $output;
 9519:     my $num = 0;
 9520:     my ($alltypes,$othertypes,$titles) =
 9521:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
 9522:     if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH'))  {
 9523:         foreach my $type (@{$alltypes}) {
 9524:             $num ++;
 9525:             my $current;
 9526:             if (ref($currrules) eq 'HASH') {
 9527:                 $current = $currrules->{$type};
 9528:             }
 9529:             if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 9530:                 if ($dom ne &Apache::lonnet::host_domain($lonhost)) {
 9531:                     $current = '';
 9532:                 }
 9533:             }
 9534:             $output .= &loadbalance_rule_row($type,$titles->{$type},$current,
 9535:                                              $servers,$currbalancer,$lonhost,$dom,
 9536:                                              $targets_div_style,$homedom_div_style,
 9537:                                              $css_class,$balnum,$num,$islast);
 9538:         }
 9539:     }
 9540:     return $output;
 9541: }
 9542: 
 9543: sub loadbalancing_titles {
 9544:     my ($dom,$intdom,$usertypes,$types) = @_;
 9545:     my %othertypes = (
 9546:            '_LC_adv'         => &mt('Advanced users from [_1]',$dom),
 9547:            '_LC_author'      => &mt('Users from [_1] with author role',$dom),
 9548:            '_LC_internetdom' => &mt('Users not from [_1], but from [_2]',$dom,$intdom),
 9549:            '_LC_external'    => &mt('Users not from [_1]',$intdom),
 9550:            '_LC_ipchangesso' => &mt('SSO users from [_1], with IP mismatch',$dom),
 9551:            '_LC_ipchange'    => &mt('Non-SSO users with IP mismatch'),
 9552:                      );
 9553:     my @alltypes = ('_LC_adv','_LC_author','_LC_internetdom','_LC_external','_LC_ipchangesso','_LC_ipchange');
 9554:     my @available;
 9555:     if (ref($types) eq 'ARRAY') {
 9556:         @available = @{$types};
 9557:     }
 9558:     unless (grep(/^default$/,@available)) {
 9559:         push(@available,'default');
 9560:     }
 9561:     unshift(@alltypes,@available);
 9562:     my %titles;
 9563:     foreach my $type (@alltypes) {
 9564:         if ($type =~ /^_LC_/) {
 9565:             $titles{$type} = $othertypes{$type};
 9566:         } elsif ($type eq 'default') {
 9567:             $titles{$type} = &mt('All users from [_1]',$dom);
 9568:             if (ref($types) eq 'ARRAY') {
 9569:                 if (@{$types} > 0) {
 9570:                     $titles{$type} = &mt('Other users from [_1]',$dom);
 9571:                 }
 9572:             }
 9573:         } elsif (ref($usertypes) eq 'HASH') {
 9574:             $titles{$type} = $usertypes->{$type};
 9575:         }
 9576:     }
 9577:     return (\@alltypes,\%othertypes,\%titles);
 9578: }
 9579: 
 9580: sub loadbalance_rule_row {
 9581:     my ($type,$title,$current,$servers,$currbalancer,$lonhost,$dom,
 9582:         $targets_div_style,$homedom_div_style,$css_class,$balnum,$num,$islast) = @_;
 9583:     my @rulenames;
 9584:     my %ruletitles = &offloadtype_text();
 9585:     if (($type eq '_LC_ipchangesso') || ($type eq '_LC_ipchange')) {
 9586:         @rulenames = ('balancer','offloadedto','specific');
 9587:     } else {
 9588:         @rulenames = ('default','homeserver');
 9589:         if ($type eq '_LC_external') {
 9590:             push(@rulenames,'externalbalancer');
 9591:         } else {
 9592:             push(@rulenames,'specific');
 9593:         }
 9594:         push(@rulenames,'none');
 9595:     }
 9596:     my $style = $targets_div_style;
 9597:     if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 9598:         $style = $homedom_div_style;
 9599:     }
 9600:     my $space;
 9601:     if ($islast && $num == 1) {
 9602:         $space = '<div style="display:inline-block;">&nbsp;</div>';
 9603:     }
 9604:     my $output =
 9605:         '<tr class="'.$css_class.'" id="balanceruletr_'.$balnum.'_'.$num.'"><td style="vertical-align: top">'.$space.
 9606:         '<div id="balanceruletitle_'.$balnum.'_'.$type.'" style="'.$style.'">'.$title.'</div></td>'."\n".
 9607:         '<td valaign="top">'.$space.
 9608:         '<div id="balancerule_'.$balnum.'_'.$type.'" style="'.$style.'">'."\n";
 9609:     for (my $i=0; $i<@rulenames; $i++) {
 9610:         my $rule = $rulenames[$i];
 9611:         my ($checked,$extra);
 9612:         if ($rulenames[$i] eq 'default') {
 9613:             $rule = '';
 9614:         }
 9615:         if ($rulenames[$i] eq 'specific') {
 9616:             if (ref($servers) eq 'HASH') {
 9617:                 my $default;
 9618:                 if (($current ne '') && (exists($servers->{$current}))) {
 9619:                     $checked = ' checked="checked"';
 9620:                 }
 9621:                 unless ($checked) {
 9622:                     $default = ' selected="selected"';
 9623:                 }
 9624:                 $extra =
 9625:                     ':&nbsp;<select name="loadbalancing_singleserver_'.$balnum.'_'.$type.
 9626:                     '" id="loadbalancing_singleserver_'.$balnum.'_'.$type.
 9627:                     '" onchange="singleServerToggle('."'$balnum','$type'".')">'."\n".
 9628:                     '<option value=""'.$default.'></option>'."\n";
 9629:                 foreach my $server (sort(keys(%{$servers}))) {
 9630:                     if (ref($currbalancer) eq 'HASH') {
 9631:                         next if (exists($currbalancer->{$server}));
 9632:                     }
 9633:                     my $selected;
 9634:                     if ($server eq $current) {
 9635:                         $selected = ' selected="selected"';
 9636:                     }
 9637:                     $extra .= '<option value="'.$server.'"'.$selected.'>'.$server.'</option>';
 9638:                 }
 9639:                 $extra .= '</select>';
 9640:             }
 9641:         } elsif ($rule eq $current) {
 9642:             $checked = ' checked="checked"';
 9643:         }
 9644:         $output .= '<span class="LC_nobreak"><label>'.
 9645:                    '<input type="radio" name="loadbalancing_rules_'.$balnum.'_'.$type.
 9646:                    '" id="loadbalancing_rules_'.$balnum.'_'.$type.'_'.$i.'" value="'.
 9647:                    $rule.'" onclick="balanceruleChange('."this.form,'$balnum','$type'".
 9648:                    ')"'.$checked.' />&nbsp;';
 9649:         if (($rulenames[$i] eq 'specific') && ($type =~ /^_LC_ipchange/)) {
 9650:             $output .= $ruletitles{'particular'};
 9651:         } else {
 9652:             $output .= $ruletitles{$rulenames[$i]};
 9653:         }
 9654:         $output .= '</label>'.$extra.'</span><br />'."\n";
 9655:     }
 9656:     $output .= '</div></td></tr>'."\n";
 9657:     return $output;
 9658: }
 9659: 
 9660: sub offloadtype_text {
 9661:     my %ruletitles = &Apache::lonlocal::texthash (
 9662:            'default'          => 'Offloads to default destinations',
 9663:            'homeserver'       => "Offloads to user's home server",
 9664:            'externalbalancer' => "Offloads to Load Balancer in user's domain",
 9665:            'specific'         => 'Offloads to specific server',
 9666:            'none'             => 'No offload',
 9667:            'balancer'         => 'Session hosted on Load Balancer, after re-authentication',
 9668:            'offloadedto'      => 'Session hosted on offload server, after re-authentication',
 9669:            'particular'       => 'Session hosted (after re-auth) on server:',
 9670:     );
 9671:     return %ruletitles;
 9672: }
 9673: 
 9674: sub sparestype_titles {
 9675:     my %typestitles = &Apache::lonlocal::texthash (
 9676:                           'primary' => 'primary',
 9677:                           'default' => 'default',
 9678:                       );
 9679:     return %typestitles;
 9680: }
 9681: 
 9682: sub contact_titles {
 9683:     my %titles = &Apache::lonlocal::texthash (
 9684:                    'supportemail'    => 'Support E-mail address',
 9685:                    'adminemail'      => 'Default Server Admin E-mail address',
 9686:                    'errormail'       => 'Error reports to be e-mailed to',
 9687:                    'packagesmail'    => 'Package update alerts to be e-mailed to',
 9688:                    'helpdeskmail'    => "Helpdesk requests from all users in this domain",
 9689:                    'otherdomsmail'   => 'Helpdesk requests from users in other (unconfigured) domains',
 9690:                    'lonstatusmail'   => 'E-mail from nightly status check (warnings/errors)',
 9691:                    'requestsmail'    => 'E-mail from course requests requiring approval',
 9692:                    'updatesmail'     => 'E-mail from nightly check of LON-CAPA module integrity/updates',
 9693:                    'idconflictsmail' => 'E-mail from bi-nightly check for multiple users sharing same student/employee ID',
 9694:                    'hostipmail'      => 'E-mail from nightly check of hostname/IP network changes',
 9695:                    'errorthreshold'  => 'Error count threshold for status e-mail to admin(s)',
 9696:                    'errorsysmail'    => 'Error count threshold for e-mail to developer group',
 9697:                    'errorweights'    => 'Weights used to compute error count',
 9698:                    'errorexcluded'   => 'Servers with unsent updates excluded from count',
 9699:                  );
 9700:     my %short_titles = &Apache::lonlocal::texthash (
 9701:                            adminemail   => 'Admin E-mail address',
 9702:                            supportemail => 'Support E-mail',
 9703:                        );   
 9704:     return (\%titles,\%short_titles);
 9705: }
 9706: 
 9707: sub helpform_fields {
 9708:     my %titles =  &Apache::lonlocal::texthash (
 9709:                        'username'   => 'Name',
 9710:                        'user'       => 'Username/domain',
 9711:                        'phone'      => 'Phone',
 9712:                        'cc'         => 'Cc e-mail',
 9713:                        'course'     => 'Course Details',
 9714:                        'section'    => 'Sections',
 9715:                        'screenshot' => 'File upload',
 9716:     );
 9717:     my @fields = ('username','phone','user','course','section','cc','screenshot');
 9718:     my %possoptions = (
 9719:                         username     => ['yes','no','req'],
 9720:                         phone        => ['yes','no','req'],
 9721:                         user         => ['yes','no'],
 9722:                         cc           => ['yes','no'],
 9723:                         course       => ['yes','no'],
 9724:                         section      => ['yes','no'],
 9725:                         screenshot   => ['yes','no'],
 9726:                       );
 9727:     my %fieldoptions = &Apache::lonlocal::texthash (
 9728:                          'yes'  => 'Optional',
 9729:                          'req'  => 'Required',
 9730:                          'no'   => "Not shown",
 9731:     );
 9732:     return (\@fields,\%titles,\%fieldoptions,\%possoptions);
 9733: }
 9734: 
 9735: sub tool_titles {
 9736:     my %titles = &Apache::lonlocal::texthash (
 9737:                      aboutme    => 'Personal web page',
 9738:                      blog       => 'Blog',
 9739:                      webdav     => 'WebDAV',
 9740:                      portfolio  => 'Portfolio',
 9741:                      timezone   => 'Can set time zone',
 9742:                      official   => 'Official courses (with institutional codes)',
 9743:                      unofficial => 'Unofficial courses',
 9744:                      community  => 'Communities',
 9745:                      textbook   => 'Textbook courses',
 9746:                      placement  => 'Placement tests',
 9747:                  );
 9748:     return %titles;
 9749: }
 9750: 
 9751: sub courserequest_titles {
 9752:     my %titles = &Apache::lonlocal::texthash (
 9753:                                    official   => 'Official',
 9754:                                    unofficial => 'Unofficial',
 9755:                                    community  => 'Communities',
 9756:                                    textbook   => 'Textbook',
 9757:                                    placement  => 'Placement tests',
 9758:                                    lti        => 'LTI Provider',
 9759:                                    norequest  => 'Not allowed',
 9760:                                    approval   => 'Approval by DC',
 9761:                                    validate   => 'With validation',
 9762:                                    autolimit  => 'Numerical limit',
 9763:                                    unlimited  => '(blank for unlimited)',
 9764:                  );
 9765:     return %titles;
 9766: }
 9767: 
 9768: sub authorrequest_titles {
 9769:     my %titles = &Apache::lonlocal::texthash (
 9770:                                    norequest  => 'Not allowed',
 9771:                                    approval   => 'Approval by Dom. Coord.',
 9772:                                    automatic  => 'Automatic approval',
 9773:                  );
 9774:     return %titles;
 9775: }
 9776: 
 9777: sub courserequest_conditions {
 9778:     my %conditions = &Apache::lonlocal::texthash (
 9779:        approval    => '(Processing of request subject to approval by Domain Coordinator).',
 9780:        validate   => '(Processing of request subject to institutional validation).',
 9781:                  );
 9782:     return %conditions;
 9783: }
 9784: 
 9785: 
 9786: sub print_usercreation {
 9787:     my ($position,$dom,$settings,$rowtotal) = @_;
 9788:     my $numinrow = 4;
 9789:     my $datatable;
 9790:     if ($position eq 'top') {
 9791:         $$rowtotal ++;
 9792:         my $rowcount = 0;
 9793:         my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($dom,'username');
 9794:         if (ref($rules) eq 'HASH') {
 9795:             if (keys(%{$rules}) > 0) {
 9796:                 $datatable .= &user_formats_row('username',$settings,$rules,
 9797:                                                 $ruleorder,$numinrow,$rowcount);
 9798:                 $$rowtotal ++;
 9799:                 $rowcount ++;
 9800:             }
 9801:         }
 9802:         my ($idrules,$idruleorder) = &Apache::lonnet::inst_userrules($dom,'id');
 9803:         if (ref($idrules) eq 'HASH') {
 9804:             if (keys(%{$idrules}) > 0) {
 9805:                 $datatable .= &user_formats_row('id',$settings,$idrules,
 9806:                                                 $idruleorder,$numinrow,$rowcount);
 9807:                 $$rowtotal ++;
 9808:                 $rowcount ++;
 9809:             }
 9810:         }
 9811:         if ($rowcount == 0) {
 9812:             $datatable .= '<tr><td colspan="2">'.&mt('No format rules have been defined for usernames or IDs in this domain.').'</td></tr>';  
 9813:             $$rowtotal ++;
 9814:             $rowcount ++;
 9815:         }
 9816:     } elsif ($position eq 'middle') {
 9817:         my @creators = ('author','course','requestcrs');
 9818:         my ($rules,$ruleorder) =
 9819:             &Apache::lonnet::inst_userrules($dom,'username');
 9820:         my %lt = &usercreation_types();
 9821:         my %checked;
 9822:         if (ref($settings) eq 'HASH') {
 9823:             if (ref($settings->{'cancreate'}) eq 'HASH') {
 9824:                 foreach my $item (@creators) {
 9825:                     $checked{$item} = $settings->{'cancreate'}{$item};
 9826:                 }
 9827:             } elsif (ref($settings->{'cancreate'}) eq 'ARRAY') {
 9828:                 foreach my $item (@creators) {
 9829:                     if (grep(/^\Q$item\E$/,@{$settings->{'cancreate'}})) {
 9830:                         $checked{$item} = 'none';
 9831:                     }
 9832:                 }
 9833:             }
 9834:         }
 9835:         my $rownum = 0;
 9836:         foreach my $item (@creators) {
 9837:             $rownum ++;
 9838:             if ($checked{$item} eq '') {
 9839:                 $checked{$item} = 'any';
 9840:             }
 9841:             my $css_class;
 9842:             if ($rownum%2) {
 9843:                 $css_class = '';
 9844:             } else {
 9845:                 $css_class = ' class="LC_odd_row" ';
 9846:             }
 9847:             $datatable .= '<tr'.$css_class.'>'.
 9848:                          '<td><span class="LC_nobreak">'.$lt{$item}.
 9849:                          '</span></td><td style="text-align: right">';
 9850:             my @options = ('any');
 9851:             if (ref($rules) eq 'HASH') {
 9852:                 if (keys(%{$rules}) > 0) {
 9853:                     push(@options,('official','unofficial'));
 9854:                 }
 9855:             }
 9856:             push(@options,'none');
 9857:             foreach my $option (@options) {
 9858:                 my $type = 'radio';
 9859:                 my $check = ' ';
 9860:                 if ($checked{$item} eq $option) {
 9861:                     $check = ' checked="checked" ';
 9862:                 } 
 9863:                 $datatable .= '<span class="LC_nobreak"><label>'.
 9864:                               '<input type="'.$type.'" name="can_createuser_'.
 9865:                               $item.'" value="'.$option.'"'.$check.'/>&nbsp;'.
 9866:                               $lt{$option}.'</label>&nbsp;&nbsp;</span>';
 9867:             }
 9868:             $datatable .= '</td></tr>';
 9869:         }
 9870:     } else {
 9871:         my @contexts = ('author','course','domain');
 9872:         my @authtypes = ('int','krb4','krb5','loc','lti');
 9873:         my %checked;
 9874:         if (ref($settings) eq 'HASH') {
 9875:             if (ref($settings->{'authtypes'}) eq 'HASH') {
 9876:                 foreach my $item (@contexts) {
 9877:                     if (ref($settings->{'authtypes'}{$item}) eq 'HASH') {
 9878:                         foreach my $auth (@authtypes) {
 9879:                             if ($settings->{'authtypes'}{$item}{$auth}) {
 9880:                                 $checked{$item}{$auth} = ' checked="checked" ';
 9881:                             }
 9882:                         }
 9883:                     }
 9884:                 }
 9885:             }
 9886:         } else {
 9887:             foreach my $item (@contexts) {
 9888:                 foreach my $auth (@authtypes) {
 9889:                     $checked{$item}{$auth} = ' checked="checked" ';
 9890:                 }
 9891:             }
 9892:         }
 9893:         my %title = &context_names();
 9894:         my %authname = &authtype_names();
 9895:         my $rownum = 0;
 9896:         my $css_class; 
 9897:         foreach my $item (@contexts) {
 9898:             if ($rownum%2) {
 9899:                 $css_class = '';
 9900:             } else {
 9901:                 $css_class = ' class="LC_odd_row" ';
 9902:             }
 9903:             $datatable .=   '<tr'.$css_class.'>'.
 9904:                             '<td>'.$title{$item}.
 9905:                             '</td><td class="LC_left_item">'.
 9906:                             '<span class="LC_nobreak">';
 9907:             foreach my $auth (@authtypes) {
 9908:                 $datatable .= '<label>'. 
 9909:                               '<input type="checkbox" name="'.$item.'_auth" '.
 9910:                               $checked{$item}{$auth}.' value="'.$auth.'" />'.
 9911:                               $authname{$auth}.'</label>&nbsp;';
 9912:             }
 9913:             $datatable .= '</span></td></tr>';
 9914:             $rownum ++;
 9915:         }
 9916:         $$rowtotal += $rownum;
 9917:     }
 9918:     return $datatable;
 9919: }
 9920: 
 9921: sub print_selfcreation {
 9922:     my ($position,$dom,$settings,$rowtotal) = @_;
 9923:     my (@selfcreate,$createsettings,$processing,$emailoptions,$emailverified,
 9924:         $emaildomain,$datatable);
 9925:     if (ref($settings) eq 'HASH') {
 9926:         if (ref($settings->{'cancreate'}) eq 'HASH') {
 9927:             $createsettings = $settings->{'cancreate'};
 9928:             if (ref($createsettings) eq 'HASH') {
 9929:                 if (ref($createsettings->{'selfcreate'}) eq 'ARRAY') {
 9930:                     @selfcreate = @{$createsettings->{'selfcreate'}};
 9931:                 } elsif ($createsettings->{'selfcreate'} ne '') {
 9932:                     if ($settings->{'cancreate'}{'selfcreate'} eq 'any') {
 9933:                         @selfcreate = ('email','login','sso');
 9934:                     } elsif ($createsettings->{'selfcreate'} ne 'none') {
 9935:                         @selfcreate = ($createsettings->{'selfcreate'});
 9936:                     }
 9937:                 }
 9938:                 if (ref($createsettings->{'selfcreateprocessing'}) eq 'HASH') {
 9939:                     $processing = $createsettings->{'selfcreateprocessing'};
 9940:                 }
 9941:                 if (ref($createsettings->{'emailoptions'}) eq 'HASH') {
 9942:                     $emailoptions = $createsettings->{'emailoptions'};
 9943:                 }
 9944:                 if (ref($createsettings->{'emailverified'}) eq 'HASH') {
 9945:                     $emailverified = $createsettings->{'emailverified'};
 9946:                 }
 9947:                 if (ref($createsettings->{'emaildomain'}) eq 'HASH') {
 9948:                     $emaildomain = $createsettings->{'emaildomain'};
 9949:                 }
 9950:             }
 9951:         }
 9952:     }
 9953:     my %radiohash;
 9954:     my $numinrow = 4;
 9955:     map { $radiohash{'cancreate_'.$_} = 1; } @selfcreate;
 9956:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 9957:     if ($position eq 'top') {
 9958:         my %choices = &Apache::lonlocal::texthash (
 9959:                                                       cancreate_login      => 'Institutional Login',
 9960:                                                       cancreate_sso        => 'Institutional Single Sign On',
 9961:                                                   );
 9962:         my @toggles = sort(keys(%choices));
 9963:         my %defaultchecked = (
 9964:                                'cancreate_login' => 'off',
 9965:                                'cancreate_sso'   => 'off',
 9966:                              );
 9967:         my ($onclick,$itemcount);
 9968:         ($datatable,$itemcount) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 9969:                                                      \%choices,$itemcount,$onclick);
 9970:         $$rowtotal += $itemcount;
 9971:         
 9972:         if (ref($usertypes) eq 'HASH') {
 9973:             if (keys(%{$usertypes}) > 0) {
 9974:                 $datatable .= &insttypes_row($createsettings,$types,$usertypes,
 9975:                                              $dom,$numinrow,$othertitle,
 9976:                                              'statustocreate',$rowtotal);
 9977:                 $$rowtotal ++;
 9978:             }
 9979:         }
 9980:         my @fields = ('lastname','firstname','middlename','permanentemail','id','inststatus');
 9981:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 9982:         $fieldtitles{'inststatus'} = &mt('Institutional status');
 9983:         my $rem;
 9984:         my $numperrow = 2;
 9985:         my $css_class = $$rowtotal%2?' class="LC_odd_row"':'';
 9986:         $datatable .= '<tr'.$css_class.'>'.
 9987:                      '<td class="LC_left_item">'.&mt('Mapping of Shibboleth environment variable names to user data fields (SSO auth)').'</td>'.
 9988:                      '<td class="LC_left_item">'."\n".
 9989:                      '<table>'."\n";
 9990:         for (my $i=0; $i<@fields; $i++) {
 9991:             $rem = $i%($numperrow);
 9992:             if ($rem == 0) {
 9993:                 if ($i > 0) {
 9994:                     $datatable .= '</tr>';
 9995:                 }
 9996:                 $datatable .= '<tr>';
 9997:             }
 9998:             my $currval;
 9999:             if (ref($createsettings) eq 'HASH') {
10000:                 if (ref($createsettings->{'shibenv'}) eq 'HASH') {
10001:                     $currval = $createsettings->{'shibenv'}{$fields[$i]};
10002:                 }
10003:             }
10004:             $datatable .= '<td class="LC_left_item">'.
10005:                           '<span class="LC_nobreak">'.
10006:                           '<input type="text" name="shibenv_'.$fields[$i].'" '.
10007:                           'value="'.$currval.'" size="10" />&nbsp;'.
10008:                           $fieldtitles{$fields[$i]}.'</span></td>';
10009:         }
10010:         my $colsleft = $numperrow - $rem;
10011:         if ($colsleft > 1 ) {
10012:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
10013:                          '&nbsp;</td>';
10014:         } elsif ($colsleft == 1) {
10015:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
10016:         }
10017:         $datatable .= '</tr></table></td></tr>';
10018:         $$rowtotal ++;
10019:     } elsif ($position eq 'middle') {
10020:         my %domconf = &Apache::lonnet::get_dom('configuration',['usermodification'],$dom);
10021:         my @posstypes;
10022:         if (ref($types) eq 'ARRAY') {
10023:             @posstypes = @{$types};
10024:         }
10025:         unless (grep(/^default$/,@posstypes)) {
10026:             push(@posstypes,'default');
10027:         }
10028:         my %usertypeshash;
10029:         if (ref($usertypes) eq 'HASH') {
10030:             %usertypeshash = %{$usertypes};
10031:         }
10032:         $usertypeshash{'default'} = $othertitle;
10033:         foreach my $status (@posstypes) {
10034:             $datatable .= &modifiable_userdata_row('selfcreate',$status,$domconf{'usermodification'},
10035:                                                    $numinrow,$$rowtotal,\%usertypeshash);
10036:             $$rowtotal ++;
10037:         }
10038:     } else {
10039:         my %choices = &Apache::lonlocal::texthash (
10040:                           'cancreate_email' => 'Non-institutional username (via e-mail verification)',
10041:                                                   );
10042:         my @toggles = sort(keys(%choices));
10043:         my %defaultchecked = (
10044:                                'cancreate_email' => 'off',
10045:                              );
10046:         my $customclass = 'LC_selfcreate_email';
10047:         my $classprefix = 'LC_canmodify_emailusername_';
10048:         my $optionsprefix = 'LC_options_emailusername_';
10049:         my $display = 'none';
10050:         my $rowstyle = 'display:none';
10051:         if (grep(/^\Qemail\E$/,@selfcreate)) {
10052:             $display = 'block';
10053:             $rowstyle = 'display:table-row';
10054:         }
10055:         my $onclick = "toggleRows(this.form,'cancreate_email','selfassign','$customclass','$classprefix','$optionsprefix');";
10056:         ($datatable,$$rowtotal) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
10057:                                                      \%choices,$$rowtotal,$onclick);
10058:         $datatable .= &print_requestmail($dom,'selfcreation',$createsettings,$rowtotal,$customclass,
10059:                                          $rowstyle);
10060:         $$rowtotal ++;
10061:         $datatable .= &captcha_choice('cancreate',$createsettings,$$rowtotal,$customclass,
10062:                                       $rowstyle);
10063:         $$rowtotal ++;
10064:         my (@ordered,@posstypes,%usertypeshash);
10065:         my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
10066:         my ($emailrules,$emailruleorder) =
10067:             &Apache::lonnet::inst_userrules($dom,'email');
10068:         my $primary_id = &Apache::lonnet::domain($dom,'primary');
10069:         my $intdom = &Apache::lonnet::internet_dom($primary_id);
10070:         if (ref($types) eq 'ARRAY') {
10071:             @posstypes = @{$types};
10072:         }
10073:         if (@posstypes) {
10074:             unless (grep(/^default$/,@posstypes)) {
10075:                 push(@posstypes,'default');
10076:             }
10077:             if (ref($usertypes) eq 'HASH') {
10078:                 %usertypeshash = %{$usertypes};
10079:             }
10080:             my $currassign;
10081:             if (ref($domdefaults{'inststatusguest'}) eq 'ARRAY') {
10082:                 $currassign = {
10083:                                   selfassign => $domdefaults{'inststatusguest'},
10084:                               };
10085:                 @ordered = @{$domdefaults{'inststatusguest'}};
10086:             } else {
10087:                 $currassign = { selfassign => [] };
10088:             }
10089:             my $onclicktypes = "toggleDataRow(this.form,'selfassign','$customclass','$optionsprefix',);".
10090:                                "toggleDataRow(this.form,'selfassign','$customclass','$classprefix',1);";
10091:             $datatable .= &insttypes_row($currassign,$types,$usertypes,$dom,
10092:                                          $numinrow,$othertitle,'selfassign',
10093:                                          $rowtotal,$onclicktypes,$customclass,
10094:                                          $rowstyle);
10095:             $$rowtotal ++;
10096:             $usertypeshash{'default'} = $othertitle;
10097:             foreach my $status (@posstypes) {
10098:                 my $css_class;
10099:                 if ($$rowtotal%2) {
10100:                     $css_class = 'LC_odd_row ';
10101:                 }
10102:                 $css_class .= $customclass;
10103:                 my $rowid = $optionsprefix.$status;
10104:                 my $hidden = 1;
10105:                 my $currstyle = 'display:none';
10106:                 if (grep(/^\Q$status\E$/,@ordered)) {
10107:                     $currstyle = $rowstyle;
10108:                     $hidden = 0; 
10109:                 }
10110:                 $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
10111:                                              $emailrules,$emailruleorder,$settings,$status,$rowid,
10112:                                              $usertypeshash{$status},$css_class,$currstyle,$intdom);
10113:                 unless ($hidden) {
10114:                     $$rowtotal ++;
10115:                 }
10116:             }
10117:         } else {
10118:             my $css_class;
10119:             if ($$rowtotal%2) {
10120:                 $css_class = 'LC_odd_row ';
10121:             }
10122:             $css_class .= $customclass;
10123:             $usertypeshash{'default'} = $othertitle;
10124:             $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
10125:                                          $emailrules,$emailruleorder,$settings,'default','',
10126:                                          $othertitle,$css_class,$rowstyle,$intdom);
10127:             $$rowtotal ++;
10128:         }
10129:         my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
10130:         $numinrow = 1;
10131:         if (@posstypes) {
10132:             foreach my $status (@posstypes) {
10133:                 my $rowid = $classprefix.$status;
10134:                 my $datarowstyle = 'display:none';
10135:                 if (grep(/^\Q$status\E$/,@ordered)) { 
10136:                     $datarowstyle = $rowstyle; 
10137:                 }
10138:                 $datatable .= &modifiable_userdata_row('cancreate','emailusername_'.$status,$settings,
10139:                                                        $numinrow,$$rowtotal,\%usertypeshash,$infofields,
10140:                                                        $infotitles,$rowid,$customclass,$datarowstyle);
10141:                 unless ($datarowstyle eq 'display:none') {
10142:                     $$rowtotal ++;
10143:                 }
10144:             }
10145:         } else {
10146:             $datatable .= &modifiable_userdata_row('cancreate','emailusername_default',$settings,
10147:                                                    $numinrow,$$rowtotal,\%usertypeshash,$infofields,
10148:                                                    $infotitles,'',$customclass,$rowstyle);
10149:         }
10150:     }
10151:     return $datatable;
10152: }
10153: 
10154: sub selfcreate_javascript {
10155:     return <<"ENDSCRIPT";
10156: 
10157: <script type="text/javascript">
10158: // <![CDATA[
10159: 
10160: function toggleRows(form,radio,checkbox,target,prefix,altprefix) {
10161:     var x = document.getElementsByClassName(target);
10162:     var insttypes = 0;
10163:     var insttypeRegExp = new RegExp(prefix);
10164:     if ((x.length != undefined) && (x.length > 0)) {
10165:         if (form.elements[radio].length != undefined) {
10166:             for (var i=0; i<form.elements[radio].length; i++) {
10167:                 if (form.elements[radio][i].checked) {
10168:                     if (form.elements[radio][i].value == 1) {
10169:                         for (var j=0; j<x.length; j++) {
10170:                             if (x[j].id == 'undefined') {
10171:                                 x[j].style.display = 'table-row';
10172:                             } else if (insttypeRegExp.test(x[j].id)) {
10173:                                 insttypes ++;
10174:                             } else {
10175:                                 x[j].style.display = 'table-row';
10176:                             }
10177:                         }
10178:                     } else {
10179:                         for (var j=0; j<x.length; j++) {
10180:                             x[j].style.display = 'none';
10181:                         }
10182:                     }
10183:                     break;
10184:                 }
10185:             }
10186:             if (insttypes > 0) {
10187:                 toggleDataRow(form,checkbox,target,altprefix);
10188:                 toggleDataRow(form,checkbox,target,prefix,1);
10189:             }
10190:         }
10191:     }
10192:     return;
10193: }
10194: 
10195: function toggleDataRow(form,checkbox,target,prefix,docount) {
10196:     if (form.elements[checkbox].length != undefined) {
10197:         var count = 0;
10198:         if (docount) {
10199:             for (var i=0; i<form.elements[checkbox].length; i++) {
10200:                 if (form.elements[checkbox][i].checked) {
10201:                     count ++;
10202:                 }
10203:             }
10204:         }
10205:         for (var i=0; i<form.elements[checkbox].length; i++) {
10206:             var type = form.elements[checkbox][i].value;
10207:             if (document.getElementById(prefix+type)) {
10208:                 if (form.elements[checkbox][i].checked) {
10209:                     document.getElementById(prefix+type).style.display = 'table-row';
10210:                     if (count % 2 == 1) {
10211:                         document.getElementById(prefix+type).className = target+' LC_odd_row';
10212:                     } else {
10213:                         document.getElementById(prefix+type).className = target;
10214:                     }
10215:                     count ++;
10216:                 } else {
10217:                     document.getElementById(prefix+type).style.display = 'none';
10218:                 }
10219:             }
10220:         }
10221:     }
10222:     return;
10223: }
10224: 
10225: function toggleEmailOptions(form,radio,prefix,altprefix,status) {
10226:     var caller = radio+'_'+status;
10227:     if (form.elements[caller].length != undefined) {
10228:         for (var i=0; i<form.elements[caller].length; i++) {
10229:             if (form.elements[caller][i].checked) {
10230:                 if (document.getElementById(altprefix+'_inst_'+status)) {
10231:                     var curr = form.elements[caller][i].value;
10232:                     if (prefix) {
10233:                         document.getElementById(prefix+'_'+status).style.display = 'none';
10234:                     }
10235:                     document.getElementById(altprefix+'_inst_'+status).style.display = 'none';
10236:                     document.getElementById(altprefix+'_noninst_'+status).style.display = 'none';
10237:                     if (curr == 'custom') {
10238:                         if (prefix) { 
10239:                             document.getElementById(prefix+'_'+status).style.display = 'inline';
10240:                         }
10241:                     } else if (curr == 'inst') {
10242:                         document.getElementById(altprefix+'_inst_'+status).style.display = 'inline';
10243:                     } else if (curr == 'noninst') {
10244:                         document.getElementById(altprefix+'_noninst_'+status).style.display = 'inline';
10245:                     }
10246:                     break;
10247:                 }
10248:             }
10249:         }
10250:     }
10251: }
10252: 
10253: // ]]>
10254: </script>
10255: 
10256: ENDSCRIPT
10257: }
10258: 
10259: sub noninst_users {
10260:     my ($processing,$emailverified,$emailoptions,$emaildomain,$emailrules,
10261:         $emailruleorder,$settings,$type,$rowid,$typetitle,$css_class,$rowstyle,$intdom) = @_; 
10262:     my $class = 'LC_left_item';
10263:     if ($css_class) {
10264:         $css_class = ' class="'.$css_class.'"'; 
10265:     }
10266:     if ($rowid) {
10267:         $rowid = ' id="'.$rowid.'"';
10268:     }
10269:     if ($rowstyle) {
10270:         $rowstyle = ' style="'.$rowstyle.'"';
10271:     }
10272:     my ($output,$description);
10273:     if ($type eq 'default') {
10274:         $description = &mt('Requests for: [_1]',$typetitle);
10275:     } else {
10276:         $description = &mt('Requests for: [_1] (status self-reported)',$typetitle);
10277:     }
10278:     $output = '<tr'.$css_class.$rowid.$rowstyle.'>'.
10279:               "<td>$description</td>\n".           
10280:               '<td class="'.$class.'" colspan="2">'.
10281:               '<table><tr>';
10282:     my %headers = &Apache::lonlocal::texthash( 
10283:               approve  => 'Processing',
10284:               email    => 'E-mail',
10285:               username => 'Username',
10286:     );
10287:     foreach my $item ('approve','email','username') {
10288:         $output .= '<th>'.$headers{$item}.'</th>';
10289:     }
10290:     $output .= '</tr><tr>';
10291:     foreach my $item ('approve','email','username') {
10292:         $output .= '<td style="vertical-align: top">';
10293:         my (%choices,@options,$hashref,$defoption,$name,$onclick,$hascustom);
10294:         if ($item eq 'approve') {
10295:             %choices = &Apache::lonlocal::texthash (
10296:                                                      automatic => 'Automatically approved',
10297:                                                      approval  => 'Queued for approval',
10298:                                                    );
10299:             @options = ('automatic','approval');
10300:             $hashref = $processing;
10301:             $defoption = 'automatic';
10302:             $name = 'cancreate_emailprocess_'.$type;
10303:         } elsif ($item eq 'email') {
10304:             %choices = &Apache::lonlocal::texthash (
10305:                                                      any     => 'Any e-mail',
10306:                                                      inst    => 'Institutional only',
10307:                                                      noninst => 'Non-institutional only',
10308:                                                      custom  => 'Custom restrictions',
10309:                                                    );
10310:             @options = ('any','inst','noninst');
10311:             my $showcustom;
10312:             if (ref($emailrules) eq 'HASH') {
10313:                 if (keys(%{$emailrules}) > 0) {
10314:                     push(@options,'custom');
10315:                     $showcustom = 'cancreate_emailrule';
10316:                     if (ref($settings) eq 'HASH') {
10317:                         if (ref($settings->{'email_rule'}) eq 'ARRAY') {
10318:                             foreach my $rule (@{$settings->{'email_rule'}}) {
10319:                                 if (exists($emailrules->{$rule})) {
10320:                                     $hascustom ++;
10321:                                 }
10322:                             }
10323:                         } elsif (ref($settings->{'email_rule'}) eq 'HASH') {
10324:                             if (ref($settings->{'email_rule'}{$type}) eq 'ARRAY') {
10325:                                 foreach my $rule (@{$settings->{'email_rule'}{$type}}) {
10326:                                     if (exists($emailrules->{$rule})) {
10327:                                         $hascustom ++;
10328:                                     }
10329:                                 }
10330:                             }
10331:                         }
10332:                     }
10333:                 }
10334:             }
10335:             $onclick = ' onclick="toggleEmailOptions(this.form,'."'cancreate_emailoptions','$showcustom',".
10336:                                                      "'cancreate_emaildomain','$type'".');"';
10337:             $hashref = $emailoptions;
10338:             $defoption = 'any';
10339:             $name = 'cancreate_emailoptions_'.$type;
10340:         } elsif ($item eq 'username') {
10341:             %choices = &Apache::lonlocal::texthash (
10342:                                                      all    => 'Same as e-mail',
10343:                                                      first  => 'Omit @domain',
10344:                                                      free   => 'Free to choose',
10345:                                                    );
10346:             @options = ('all','first','free');
10347:             $hashref = $emailverified;
10348:             $defoption = 'all';
10349:             $name = 'cancreate_usernameoptions_'.$type;
10350:         }
10351:         foreach my $option (@options) {
10352:             my $checked;
10353:             if (ref($hashref) eq 'HASH') {
10354:                 if ($type eq '') {
10355:                     if (!exists($hashref->{'default'})) {
10356:                         if ($option eq $defoption) {
10357:                             $checked = ' checked="checked"';
10358:                         }
10359:                     } else {
10360:                         if ($hashref->{'default'} eq $option) {
10361:                             $checked = ' checked="checked"';
10362:                         }
10363:                     }
10364:                 } else {
10365:                     if (!exists($hashref->{$type})) {
10366:                         if ($option eq $defoption) {
10367:                             $checked = ' checked="checked"';
10368:                         }
10369:                     } else {
10370:                         if ($hashref->{$type} eq $option) {
10371:                             $checked = ' checked="checked"';
10372:                         }
10373:                     }
10374:                 }
10375:             } elsif (($item eq 'email') && ($hascustom)) {
10376:                 if ($option eq 'custom') {
10377:                     $checked = ' checked="checked"';
10378:                 }
10379:             } elsif ($option eq $defoption) {
10380:                 $checked = ' checked="checked"';
10381:             }
10382:             $output .= '<span class="LC_nobreak"><label>'.
10383:                        '<input type="radio" name="'.$name.'"'.
10384:                        $checked.' value="'.$option.'"'.$onclick.' />'.
10385:                        $choices{$option}.'</label></span><br />';
10386:             if ($item eq 'email') {
10387:                 if ($option eq 'custom') {
10388:                     my $id = 'cancreate_emailrule_'.$type;
10389:                     my $display = 'none';
10390:                     if ($checked) {
10391:                         $display = 'inline';
10392:                     }
10393:                     my $numinrow = 2;
10394:                     $output .= '<fieldset id="'.$id.'" style="display:'.$display.';">'.
10395:                                '<legend>'.&mt('Disallow').'</legend><table>'.
10396:                                &user_formats_row('email',$settings,$emailrules,
10397:                                                  $emailruleorder,$numinrow,'',$type);
10398:                               '</table></fieldset>';
10399:                 } elsif (($option eq 'inst') || ($option eq 'noninst')) {
10400:                     my %text = &Apache::lonlocal::texthash (
10401:                                                              inst    => 'must end:',
10402:                                                              noninst => 'cannot end:',
10403:                                                            );
10404:                     my $value;
10405:                     if (ref($emaildomain) eq 'HASH') {
10406:                         if (ref($emaildomain->{$type}) eq 'HASH') {
10407:                             $value = $emaildomain->{$type}->{$option}; 
10408:                         }
10409:                     }
10410:                     if ($value eq '') {
10411:                         $value = '@'.$intdom;
10412:                     }
10413:                     my $condition = 'cancreate_emaildomain_'.$option.'_'.$type;
10414:                     my $display = 'none';
10415:                     if ($checked) {
10416:                         $display = 'inline';
10417:                     }
10418:                     $output .= '<div id="'.$condition.'" style="display:'.$display.';">'.
10419:                                '<span class="LC_domprefs_email">'.$text{$option}.'</span> '.
10420:                                '<input type="text" name="'.$condition.'" value="'.$value.'" size="10" />'.
10421:                                '</div>';
10422:                 }
10423:             }
10424:         }
10425:         $output .= '</td>'."\n";
10426:     }
10427:     $output .= "</tr></table></td></tr>\n";
10428:     return $output;
10429: }
10430: 
10431: sub captcha_choice {
10432:     my ($context,$settings,$itemcount,$customcss,$rowstyle) = @_;
10433:     my ($keyentry,$currpub,$currpriv,%checked,$rowname,$pubtext,$privtext,
10434:         $vertext,$currver);
10435:     my %lt = &captcha_phrases();
10436:     $keyentry = 'hidden';
10437:     my $colspan=2;
10438:     if ($context eq 'cancreate') {
10439:         $rowname = &mt('CAPTCHA validation');
10440:     } elsif ($context eq 'login') {
10441:         $rowname =  &mt('"Contact helpdesk" CAPTCHA validation');
10442:     } elsif ($context eq 'passwords') {
10443:         $rowname = &mt('"Forgot Password" CAPTCHA validation');
10444:         $colspan=1;
10445:     }
10446:     if (ref($settings) eq 'HASH') {
10447:         if ($settings->{'captcha'}) {
10448:             $checked{$settings->{'captcha'}} = ' checked="checked"';
10449:         } else {
10450:             $checked{'original'} = ' checked="checked"';
10451:         }
10452:         if ($settings->{'captcha'} eq 'recaptcha') {
10453:             $pubtext = $lt{'pub'};
10454:             $privtext = $lt{'priv'};
10455:             $keyentry = 'text';
10456:             $vertext = $lt{'ver'};
10457:             $currver = $settings->{'recaptchaversion'};
10458:             if ($currver ne '2') {
10459:                 $currver = 1;
10460:             }
10461:         }
10462:         if (ref($settings->{'recaptchakeys'}) eq 'HASH') {
10463:             $currpub = $settings->{'recaptchakeys'}{'public'};
10464:             $currpriv = $settings->{'recaptchakeys'}{'private'};
10465:         }
10466:     } else {
10467:         $checked{'original'} = ' checked="checked"';
10468:     }
10469:     my $css_class;
10470:     if ($itemcount%2) {
10471:         $css_class = 'LC_odd_row';
10472:     }
10473:     if ($customcss) {
10474:         $css_class .= " $customcss";
10475:     }
10476:     $css_class =~ s/^\s+//;
10477:     if ($css_class) {
10478:         $css_class = ' class="'.$css_class.'"';
10479:     }
10480:     if ($rowstyle) {
10481:         $css_class .= ' style="'.$rowstyle.'"';
10482:     }
10483:     my $output = '<tr'.$css_class.'>'.
10484:                  '<td class="LC_left_item">'.$rowname.'</td><td class="LC_left_item" colspan="'.$colspan.'">'."\n".
10485:                  '<table><tr><td>'."\n";
10486:     foreach my $option ('original','recaptcha','notused') {
10487:         $output .= '<span class="LC_nobreak"><label><input type="radio" name="'.$context.'_captcha" value="'.
10488:                    $option.'" '.$checked{$option}.' onchange="javascript:updateCaptcha('."this,'$context'".');" />'.
10489:                    $lt{$option}.'</label></span>';
10490:         unless ($option eq 'notused') {
10491:             $output .= ('&nbsp;'x2)."\n";
10492:         }
10493:     }
10494: #
10495: # Note: If reCAPTCHA is to be used for LON-CAPA servers in a domain, a domain coordinator should visit:
10496: # https://www.google.com/recaptcha and generate a Public and Private key. For domains with multiple
10497: # servers a single key pair will be used for all servers, so the internet domain (e.g., yourcollege.edu)
10498: # specified for use with the key should be broad enough to accommodate all servers in the LON-CAPA domain.
10499: #
10500:     $output .= '</td></tr>'."\n".
10501:                '<tr><td class="LC_zero_height">'."\n".
10502:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchapubtxt">'.$pubtext.'</span>&nbsp;'."\n".
10503:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapub" name="'.$context.'_recaptchapub" value="'.
10504:                $currpub.'" size="40" /></span><br />'."\n".
10505:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchaprivtxt">'.$privtext.'</span>&nbsp;'."\n".
10506:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapriv" name="'.$context.'_recaptchapriv" value="'.
10507:                $currpriv.'" size="40" /></span><br />'.
10508:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchavertxt">'.$vertext.'</span>&nbsp;'."\n".
10509:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchaversion" name="'.$context.'_recaptchaversion" value="'.
10510:                $currver.'" size="3" /></span><br />'.
10511:                '</td></tr></table>'."\n".
10512:                '</td></tr>';
10513:     return $output;
10514: }
10515: 
10516: sub user_formats_row {
10517:     my ($type,$settings,$rules,$ruleorder,$numinrow,$rowcount,$status) = @_;
10518:     my $output;
10519:     my %text = (
10520:                    'username' => 'new usernames',
10521:                    'id'       => 'IDs',
10522:                );
10523:     unless (($type eq 'email') || ($type eq 'unamemap')) {
10524:         my $css_class = $rowcount%2?' class="LC_odd_row"':'';
10525:         $output = '<tr '.$css_class.'>'.
10526:                   '<td><span class="LC_nobreak">'.
10527:                   &mt("Format rules to check for $text{$type}: ").
10528:                   '</td><td class="LC_left_item" colspan="2"><table>';
10529:     }
10530:     my $rem;
10531:     if (ref($ruleorder) eq 'ARRAY') {
10532:         for (my $i=0; $i<@{$ruleorder}; $i++) {
10533:             if (ref($rules->{$ruleorder->[$i]}) eq 'HASH') {
10534:                 my $rem = $i%($numinrow);
10535:                 if ($rem == 0) {
10536:                     if ($i > 0) {
10537:                         $output .= '</tr>';
10538:                     }
10539:                     $output .= '<tr>';
10540:                 }
10541:                 my $check = ' ';
10542:                 if (ref($settings) eq 'HASH') {
10543:                     if (ref($settings->{$type.'_rule'}) eq 'ARRAY') {
10544:                         if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}})) {
10545:                             $check = ' checked="checked" ';
10546:                         }
10547:                     } elsif ((ref($settings->{$type.'_rule'}) eq 'HASH') && ($status ne '')) {
10548:                         if (ref($settings->{$type.'_rule'}->{$status}) eq 'ARRAY') {
10549:                             if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}->{$status}})) {
10550:                                 $check = ' checked="checked" ';
10551:                             }
10552:                         }
10553:                     }
10554:                 }
10555:                 my $name = $type.'_rule';
10556:                 if ($type eq 'email') {
10557:                     $name .= '_'.$status;
10558:                 }
10559:                 $output .= '<td class="LC_left_item">'.
10560:                            '<span class="LC_nobreak"><label>'.
10561:                            '<input type="checkbox" name="'.$name.'" '.
10562:                            'value="'.$ruleorder->[$i].'"'.$check.'/>'.
10563:                            $rules->{$ruleorder->[$i]}{'name'}.'</label></span></td>';
10564:             }
10565:         }
10566:         $rem = @{$ruleorder}%($numinrow);
10567:     }
10568:     my $colsleft;
10569:     if ($rem) {
10570:         $colsleft = $numinrow - $rem;
10571:     }
10572:     if ($colsleft > 1 ) {
10573:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
10574:                    '&nbsp;</td>';
10575:     } elsif ($colsleft == 1) {
10576:         $output .= '<td class="LC_left_item">&nbsp;</td>';
10577:     }
10578:     $output .= '</tr>';
10579:     unless (($type eq 'email') || ($type eq 'unamemap')) {
10580:         $output .= '</table></td></tr>';
10581:     }
10582:     return $output;
10583: }
10584: 
10585: sub usercreation_types {
10586:     my %lt = &Apache::lonlocal::texthash (
10587:                     author     => 'When adding a co-author',
10588:                     course     => 'When adding a user to a course',
10589:                     requestcrs => 'When requesting a course',
10590:                     any        => 'Any',
10591:                     official   => 'Institutional only ',
10592:                     unofficial => 'Non-institutional only',
10593:                     none       => 'None',
10594:     );
10595:     return %lt;
10596: }
10597: 
10598: sub selfcreation_types {
10599:     my %lt = &Apache::lonlocal::texthash (
10600:                     selfcreate => 'User creates own account',
10601:                     any        => 'Any',
10602:                     official   => 'Institutional only ',
10603:                     unofficial => 'Non-institutional only',
10604:                     email      => 'E-mail address',
10605:                     login      => 'Institutional Login',
10606:                     sso        => 'SSO',
10607:              );
10608: }
10609: 
10610: sub authtype_names {
10611:     my %lt = &Apache::lonlocal::texthash(
10612:                       int    => 'Internal',
10613:                       krb4   => 'Kerberos 4',
10614:                       krb5   => 'Kerberos 5',
10615:                       loc    => 'Local',
10616:                       lti    => 'LTI',
10617:                   );
10618:     return %lt;
10619: }
10620: 
10621: sub context_names {
10622:     my %context_title = &Apache::lonlocal::texthash(
10623:        author => 'Creating users when an Author',
10624:        course => 'Creating users when in a course',
10625:        domain => 'Creating users when a Domain Coordinator',
10626:     );
10627:     return %context_title;
10628: }
10629: 
10630: sub print_usermodification {
10631:     my ($position,$dom,$settings,$rowtotal) = @_;
10632:     my $numinrow = 4;
10633:     my ($context,$datatable,$rowcount);
10634:     if ($position eq 'top') {
10635:         $rowcount = 0;
10636:         $context = 'author'; 
10637:         foreach my $role ('ca','aa') {
10638:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
10639:                                                    $numinrow,$rowcount);
10640:             $$rowtotal ++;
10641:             $rowcount ++;
10642:         }
10643:     } elsif ($position eq 'bottom') {
10644:         $context = 'course';
10645:         $rowcount = 0;
10646:         foreach my $role ('st','ep','ta','in','cr') {
10647:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
10648:                                                    $numinrow,$rowcount);
10649:             $$rowtotal ++;
10650:             $rowcount ++;
10651:         }
10652:     }
10653:     return $datatable;
10654: }
10655: 
10656: sub print_defaults {
10657:     my ($position,$dom,$settings,$rowtotal) = @_;
10658:     my $rownum = 0;
10659:     my ($datatable,$css_class,$titles);
10660:     unless ($position eq 'bottom') {
10661:         $titles = &defaults_titles($dom);
10662:     }
10663:     if ($position eq 'top') {
10664:         my @items = ('auth_def','auth_arg_def','lang_def','timezone_def',
10665:                      'datelocale_def','portal_def');
10666:         my %defaults;
10667:         if (ref($settings) eq 'HASH') {
10668:             %defaults = %{$settings};
10669:         } else {
10670:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
10671:             foreach my $item (@items) {
10672:                 $defaults{$item} = $domdefaults{$item};
10673:             }
10674:         }
10675:         foreach my $item (@items) {
10676:             if ($rownum%2) {
10677:                 $css_class = '';
10678:             } else {
10679:                 $css_class = ' class="LC_odd_row" ';
10680:             }
10681:             $datatable .= '<tr'.$css_class.'>'.
10682:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
10683:                           '</span></td><td class="LC_right_item" colspan="3">';
10684:             if ($item eq 'auth_def') {
10685:                 my @authtypes = ('internal','krb4','krb5','localauth','lti');
10686:                 my %shortauth = (
10687:                                  internal => 'int',
10688:                                  krb4 => 'krb4',
10689:                                  krb5 => 'krb5',
10690:                                  localauth  => 'loc',
10691:                                  lti => 'lti',
10692:                                 );
10693:                 my %authnames = &authtype_names();
10694:                 foreach my $auth (@authtypes) {
10695:                     my $checked = ' ';
10696:                     if ($defaults{$item} eq $auth) {
10697:                         $checked = ' checked="checked" ';
10698:                     }
10699:                     $datatable .= '<label><input type="radio" name="'.$item.
10700:                                   '" value="'.$auth.'"'.$checked.'/>'.
10701:                                   $authnames{$shortauth{$auth}}.'</label>&nbsp;&nbsp;';
10702:                 }
10703:             } elsif ($item eq 'timezone_def') {
10704:                 my $includeempty = 1;
10705:                 $datatable .= &Apache::loncommon::select_timezone($item,$defaults{$item},undef,$includeempty);
10706:             } elsif ($item eq 'datelocale_def') {
10707:                 my $includeempty = 1;
10708:                 $datatable .= &Apache::loncommon::select_datelocale($item,$defaults{$item},undef,$includeempty);
10709:             } elsif ($item eq 'lang_def') {
10710:                 my $includeempty = 1;
10711:                 $datatable .= &Apache::loncommon::select_language($item,$defaults{$item},$includeempty);
10712:             } elsif ($item eq 'portal_def') {
10713:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
10714:                               $defaults{$item}.'" size="25" onkeyup="portalExtras(this);" />';
10715:                 my $portalsty = 'none';
10716:                 if ($defaults{$item}) {
10717:                     $portalsty = 'block';
10718:                 }
10719:                 foreach my $field ('email','web') {
10720:                     my $checkedoff = ' checked="checked"';
10721:                     my $checkedon;
10722:                     if ($defaults{$item.'_'.$field}) {
10723:                         $checkedon = $checkedoff;
10724:                         $checkedoff = '';
10725:                     } 
10726:                     $datatable .= '<div id="'.$item.'_'.$field.'_div" style="display:'.$portalsty.'">'.
10727:                               '<span class="LC_nobreak">'.$titles->{$field}.'&nbsp;'.
10728:                               '<label><input type="radio" name="'.$item.'_'.$field.'" value="1"'.$checkedon.'/>'.&mt('Yes').'</label>'.
10729:                               ('&nbsp;'x2).
10730:                               '<label><input type="radio" name="'.$item.'_'.$field.'" value="0"'.$checkedoff.'/>'.&mt('No').'</label>'.
10731:                               '</div>';
10732:                 }
10733:             } else {
10734:                 $datatable .= '<input type="text" name="'.$item.'" value="'.$defaults{$item}.'" />';
10735:             }
10736:             $datatable .= '</td></tr>';
10737:             $rownum ++;
10738:         }
10739:     } elsif ($position eq 'middle') {
10740:         my %defaults;
10741:         if (ref($settings) eq 'HASH') {
10742:             if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
10743:                 my $maxnum = @{$settings->{'inststatusorder'}};
10744:                 for (my $i=0; $i<$maxnum; $i++) {
10745:                     $css_class = $rownum%2?' class="LC_odd_row"':'';
10746:                     my $item = $settings->{'inststatusorder'}->[$i];
10747:                     my $title = $settings->{'inststatustypes'}->{$item};
10748:                     my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'$item'".');"';
10749:                     $datatable .= '<tr'.$css_class.'>'.
10750:                                   '<td><span class="LC_nobreak">'.
10751:                                   '<select name="inststatus_pos_'.$item.'"'.$chgstr.'>';
10752:                     for (my $k=0; $k<=$maxnum; $k++) {
10753:                         my $vpos = $k+1;
10754:                         my $selstr;
10755:                         if ($k == $i) {
10756:                             $selstr = ' selected="selected" ';
10757:                         }
10758:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
10759:                     }
10760:                     $datatable .= '</select>&nbsp;'.&mt('Internal ID:').'&nbsp;<b>'.$item.'</b>&nbsp;'.
10761:                                   '<input type="checkbox" name="inststatus_delete" value="'.$item.'" />'.
10762:                                   &mt('delete').'</span></td>'.
10763:                                   '<td class="LC_left_item" colspan="2"><span class="LC_nobreak">'.&mt('Name displayed').':'.
10764:                                   '<input type="text" size="20" name="inststatus_title_'.$item.'" value="'.$title.'" />'.
10765:                                   '</span></td></tr>';
10766:                 }
10767:                 $css_class = $rownum%2?' class="LC_odd_row"':'';
10768:                 my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'addinststatus_pos'".');"';
10769:                 $datatable .= '<tr '.$css_class.'>'.
10770:                               '<td><span class="LC_nobreak"><select name="addinststatus_pos"'.$chgstr.'>';
10771:                 for (my $k=0; $k<=$maxnum; $k++) {
10772:                     my $vpos = $k+1;
10773:                     my $selstr;
10774:                     if ($k == $maxnum) {
10775:                         $selstr = ' selected="selected" ';
10776:                     }
10777:                     $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
10778:                 }
10779:                 $datatable .= '</select>&nbsp;'.&mt('Internal ID:').
10780:                               '<input type="text" size="10" name="addinststatus" value="" />'.
10781:                               '&nbsp;'.&mt('(new)').
10782:                               '</span></td><td class="LC_left_item" colspan="2"><span class="LC_nobreak">'.
10783:                               &mt('Name displayed').':'.
10784:                               '<input type="text" size="20" name="addinststatus_title" value="" /></span></td>'.
10785:                               '</tr>'."\n";
10786:                 $rownum ++;
10787:             }
10788:         }
10789:     } else {
10790:         my ($unamemaprules,$ruleorder) =
10791:             &Apache::lonnet::inst_userrules($dom,'unamemap');
10792:         $css_class = $rownum%2?' class="LC_odd_row"':'';
10793:         if ((ref($unamemaprules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
10794:             my $numinrow = 2;
10795:             $datatable .= '<tr'.$css_class.'><td>'.&mt('Available conversions').'</td><td><table>'.
10796:                           &user_formats_row('unamemap',$settings,$unamemaprules,
10797:                                             $ruleorder,$numinrow).
10798:                           '</table></td></tr>';
10799:         }
10800:         if ($datatable eq '') {
10801:             $datatable .= '<tr'.$css_class.'><td colspan="2">'.
10802:                           &mt('No rules set for domain in customized localenroll.pm').
10803:                           '</td></tr>';
10804:         }
10805:     }
10806:     $$rowtotal += $rownum;
10807:     return $datatable;
10808: }
10809: 
10810: sub get_languages_hash {
10811:     my %langchoices;
10812:     foreach my $id (&Apache::loncommon::languageids()) {
10813:         my $code = &Apache::loncommon::supportedlanguagecode($id);
10814:         if ($code ne '') {
10815:             $langchoices{$code} =  &Apache::loncommon::plainlanguagedescription($id);
10816:         }
10817:     }
10818:     return %langchoices;
10819: }
10820: 
10821: sub defaults_titles {
10822:     my ($dom) = @_;
10823:     my %titles = &Apache::lonlocal::texthash (
10824:                    'auth_def'      => 'Default authentication type',
10825:                    'auth_arg_def'  => 'Default authentication argument',
10826:                    'lang_def'      => 'Default language',
10827:                    'timezone_def'  => 'Default timezone',
10828:                    'datelocale_def' => 'Default locale for dates',
10829:                    'portal_def'     => 'Portal/Default URL',
10830:                    'email'          => 'Email links use portal URL',
10831:                    'web'            => 'Public web links use portal URL',
10832:                    'intauth_cost'   => 'Encryption cost for bcrypt (positive integer)',
10833:                    'intauth_check'  => 'Check bcrypt cost if authenticated',
10834:                    'intauth_switch' => 'Existing crypt-based switched to bcrypt on authentication',
10835:                  );
10836:     if ($dom) {
10837:         my $uprimary_id = &Apache::lonnet::domain($dom,'primary');
10838:         my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
10839:         my $protocol = $Apache::lonnet::protocol{$uprimary_id};
10840:         $protocol = 'http' if ($protocol ne 'https');
10841:         if ($uint_dom) {
10842:             $titles{'portal_def'} .= ' '.&mt('(for example: [_1])',$protocol.'://loncapa.'.
10843:                                          $uint_dom);
10844:         }
10845:     }
10846:     return (\%titles);
10847: }
10848: 
10849: sub print_scantron {
10850:     my ($r,$position,$dom,$confname,$settings,$rowtotal) = @_;
10851:     if ($position eq 'top') {
10852:         return &print_scantronformat($r,$dom,$confname,$settings,\$rowtotal);
10853:     } else {
10854:         return &print_scantronconfig($dom,$settings,\$rowtotal);
10855:     }
10856: }
10857: 
10858: sub scantron_javascript {
10859:     return <<"ENDSCRIPT";
10860: 
10861: <script type="text/javascript">
10862: // <![CDATA[
10863: 
10864: function toggleScantron(form) {
10865:     var csvfieldset = new Array();
10866:     if (document.getElementById('scantroncsv_cols')) {
10867:         csvfieldset.push(document.getElementById('scantroncsv_cols'));
10868:     }
10869:     if (document.getElementById('scantroncsv_options')) {
10870:         csvfieldset.push(document.getElementById('scantroncsv_options'));
10871:     }
10872:     if (csvfieldset.length) {
10873:         if (document.getElementById('scantronconfcsv')) {
10874:             var scantroncsv = document.getElementById('scantronconfcsv');
10875:             if (scantroncsv.checked) {
10876:                 for (var i=0; i<csvfieldset.length; i++) {
10877:                     csvfieldset[i].style.display = 'block';
10878:                 }
10879:             } else {
10880:                 for (var i=0; i<csvfieldset.length; i++) {
10881:                     csvfieldset[i].style.display = 'none';
10882:                 }
10883:                 var csvselects = document.getElementsByClassName('scantronconfig_csv');
10884:                 if (csvselects.length) {
10885:                     for (var j=0; j<csvselects.length; j++) {
10886:                         csvselects[j].selectedIndex = 0;
10887:                     }
10888:                 }
10889:             }
10890:         }
10891:     }
10892:     return;
10893: }
10894: // ]]>
10895: </script>
10896: 
10897: ENDSCRIPT
10898: 
10899: }
10900: 
10901: sub print_scantronformat {
10902:     my ($r,$dom,$confname,$settings,$rowtotal) = @_;
10903:     my $itemcount = 1;
10904:     my ($datatable,$css_class,$scantronurl,$is_custom,%error,%scantronurls,
10905:         %confhash);
10906:     my $switchserver = &check_switchserver($dom,$confname);
10907:     my %lt = &Apache::lonlocal::texthash (
10908:                 default => 'Default bubblesheet format file error',
10909:                 custom  => 'Custom bubblesheet format file error',
10910:              );
10911:     my %scantronfiles = (
10912:         default => 'default.tab',
10913:         custom => 'custom.tab',
10914:     );
10915:     foreach my $key (keys(%scantronfiles)) {
10916:         $scantronurls{$key} = '/res/'.$dom.'/'.$confname.'/scantron/'
10917:                               .$scantronfiles{$key};
10918:     }
10919:     my @defaultinfo = &Apache::lonnet::stat_file($scantronurls{'default'});
10920:     if ((!@defaultinfo) || ($defaultinfo[0] eq 'no_such_dir')) {
10921:         if (!$switchserver) {
10922:             my $servadm = $r->dir_config('lonAdmEMail');
10923:             my ($configuserok,$author_ok) = &config_check($dom,$confname,$servadm);
10924:             if ($configuserok eq 'ok') {
10925:                 if ($author_ok eq 'ok') {
10926:                     my %legacyfile = (
10927:  default => $Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab',
10928:  custom  => $Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab',
10929:                     );
10930:                     my %md5chk;
10931:                     foreach my $type (keys(%legacyfile)) {
10932:                         ($md5chk{$type}) = split(/ /,`md5sum $legacyfile{$type}`);
10933:                         chomp($md5chk{$type});
10934:                     }
10935:                     if ($md5chk{'default'} ne $md5chk{'custom'}) {
10936:                         foreach my $type (keys(%legacyfile)) {
10937:                             ($scantronurls{$type},my $error) =
10938:                                 &legacy_scantronformat($r,$dom,$confname,
10939:                                                  $type,$legacyfile{$type},
10940:                                                  $scantronurls{$type},
10941:                                                  $scantronfiles{$type});
10942:                             if ($error ne '') {
10943:                                 $error{$type} = $error;
10944:                             }
10945:                         }
10946:                         if (keys(%error) == 0) {
10947:                             $is_custom = 1;
10948:                             $confhash{'scantron'}{'scantronformat'} =
10949:                                 $scantronurls{'custom'};
10950:                             my $putresult =
10951:                                 &Apache::lonnet::put_dom('configuration',
10952:                                                          \%confhash,$dom);
10953:                             if ($putresult ne 'ok') {
10954:                                 $error{'custom'} =
10955:                                     '<span class="LC_error">'.
10956:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
10957:                             }
10958:                         }
10959:                     } else {
10960:                         ($scantronurls{'default'},my $error) =
10961:                             &legacy_scantronformat($r,$dom,$confname,
10962:                                           'default',$legacyfile{'default'},
10963:                                           $scantronurls{'default'},
10964:                                           $scantronfiles{'default'});
10965:                         if ($error eq '') {
10966:                             $confhash{'scantron'}{'scantronformat'} = ''; 
10967:                             my $putresult =
10968:                                 &Apache::lonnet::put_dom('configuration',
10969:                                                          \%confhash,$dom);
10970:                             if ($putresult ne 'ok') {
10971:                                 $error{'default'} =
10972:                                     '<span class="LC_error">'.
10973:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
10974:                             }
10975:                         } else {
10976:                             $error{'default'} = $error;
10977:                         }
10978:                     }
10979:                 }
10980:             }
10981:         } else {
10982:             $error{'default'} = &mt("Unable to copy default bubblesheet formatfile to domain's RES space: [_1]",$switchserver);
10983:         }
10984:     }
10985:     if (ref($settings) eq 'HASH') {
10986:         if ($settings->{'scantronformat'} eq "/res/$dom/$confname/scantron/custom.tab") {
10987:             my @info = &Apache::lonnet::stat_file($settings->{'scantronformat'});
10988:             if ((!@info) || ($info[0] eq 'no_such_dir')) {
10989:                 $scantronurl = '';
10990:             } else {
10991:                 $scantronurl = $settings->{'scantronformat'};
10992:             }
10993:             $is_custom = 1;
10994:         } else {
10995:             $scantronurl = $scantronurls{'default'};
10996:         }
10997:     } else {
10998:         if ($is_custom) {
10999:             $scantronurl = $scantronurls{'custom'};
11000:         } else {
11001:             $scantronurl = $scantronurls{'default'};
11002:         }
11003:     }
11004:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
11005:     $datatable .= '<tr'.$css_class.'>';
11006:     if (!$is_custom) {
11007:         $datatable .= '<td>'.&mt('Default in use:').'<br />'.
11008:                       '<span class="LC_nobreak">';
11009:         if ($scantronurl) {
11010:             $datatable .= &Apache::loncommon::modal_link($scantronurl,&mt('Default bubblesheet format file'),600,500,
11011:                                                          undef,undef,undef,undef,'background-color:#ffffff');
11012:         } else {
11013:             $datatable = &mt('File unavailable for display');
11014:         }
11015:         $datatable .= '</span></td>';
11016:         if (keys(%error) == 0) { 
11017:             $datatable .= '<td style="vertical-align: bottom">';
11018:             if (!$switchserver) {
11019:                 $datatable .= &mt('Upload:').'<br />';
11020:             }
11021:         } else {
11022:             my $errorstr;
11023:             foreach my $key (sort(keys(%error))) {
11024:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
11025:             }
11026:             $datatable .= '<td>'.$errorstr;
11027:         }
11028:     } else {
11029:         if (keys(%error) > 0) {
11030:             my $errorstr;
11031:             foreach my $key (sort(keys(%error))) {
11032:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
11033:             } 
11034:             $datatable .= '<td>'.$errorstr.'</td><td>&nbsp;';
11035:         } elsif ($scantronurl) {
11036:             my $link =  &Apache::loncommon::modal_link($scantronurl,&mt('Custom bubblesheet format file'),600,500,
11037:                                                        undef,undef,undef,undef,'background-color:#ffffff');
11038:             $datatable .= '<td><span class="LC_nobreak">'.
11039:                           $link.
11040:                           '<label><input type="checkbox" name="scantronformat_del"'.
11041:                           ' value="1" />'.&mt('Delete?').'</label></span></td>'.
11042:                           '<td><span class="LC_nobreak">&nbsp;'.
11043:                           &mt('Replace:').'</span><br />';
11044:         }
11045:     }
11046:     if (keys(%error) == 0) {
11047:         if ($switchserver) {
11048:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
11049:         } else {
11050:             $datatable .='<span class="LC_nobreak">&nbsp;'.
11051:                          '<input type="file" name="scantronformat" /></span>';
11052:         }
11053:     }
11054:     $datatable .= '</td></tr>';
11055:     $$rowtotal ++;
11056:     return $datatable;
11057: }
11058: 
11059: sub legacy_scantronformat {
11060:     my ($r,$dom,$confname,$file,$legacyfile,$newurl,$newfile) = @_;
11061:     my ($url,$error);
11062:     my @statinfo = &Apache::lonnet::stat_file($newurl);
11063:     if ((!@statinfo) || ($statinfo[0] eq 'no_such_dir')) {
11064:         (my $result,$url) =
11065:             &publishlogo($r,'copy',$legacyfile,$dom,$confname,'scantron',
11066:                          '','',$newfile);
11067:         if ($result ne 'ok') {
11068:             $error = &mt("An error occurred publishing the [_1] bubblesheet format file in RES space. Error was: [_2].",$newfile,$result);
11069:         }
11070:     }
11071:     return ($url,$error);
11072: }
11073: 
11074: sub print_scantronconfig {
11075:     my ($dom,$settings,$rowtotal) = @_;
11076:     my $itemcount = 2;
11077:     my $is_checked = ' checked="checked"';
11078:     my %optionson = (
11079:                      hdr => ' checked="checked"',
11080:                      pad => ' checked="checked"',
11081:                      rem => ' checked="checked"',
11082:                     );
11083:     my %optionsoff = (
11084:                       hdr => '',
11085:                       pad => '',
11086:                       rem => '',
11087:                      );
11088:     my $currcsvsty = 'none';
11089:     my ($datatable,%csvfields,%checked,%onclick,%csvoptions);
11090:     my @fields = &scantroncsv_fields();
11091:     my %titles = &scantronconfig_titles();
11092:     if (ref($settings) eq 'HASH') {
11093:         if (ref($settings->{config}) eq 'HASH') {
11094:             if ($settings->{config}->{dat}) {
11095:                 $checked{'dat'} = $is_checked;
11096:             }
11097:             if (ref($settings->{config}->{csv}) eq 'HASH') {
11098:                 if (ref($settings->{config}->{csv}->{fields}) eq 'HASH') {
11099:                     %csvfields = %{$settings->{config}->{csv}->{fields}};
11100:                     if (keys(%csvfields) > 0) {
11101:                         $checked{'csv'} = $is_checked;
11102:                         $currcsvsty = 'block';
11103:                     }
11104:                 }
11105:                 if (ref($settings->{config}->{csv}->{options}) eq 'HASH') {
11106:                     %csvoptions = %{$settings->{config}->{csv}->{options}};
11107:                     foreach my $option (keys(%optionson)) {
11108:                         unless ($csvoptions{$option}) {
11109:                             $optionsoff{$option} = $optionson{$option};
11110:                             $optionson{$option} = '';
11111:                         }
11112:                     }
11113:                 }
11114:             }
11115:         } else {
11116:             $checked{'dat'} = $is_checked;
11117:         }
11118:     } else {
11119:         $checked{'dat'} = $is_checked;
11120:     }
11121:     $onclick{'csv'} = ' onclick="toggleScantron(this.form);"';
11122:     my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
11123:     $datatable = '<tr '.$css_class.'><td>'.&mt('Supported formats').'</td>'.
11124:                  '<td class="LC_left_item" valign="top"><span class="LC_nobreak">';
11125:     foreach my $item ('dat','csv') {
11126:         my $id;
11127:         if ($item eq 'csv') {
11128:             $id = 'id="scantronconfcsv" ';
11129:         }
11130:         $datatable .= '<label><input type="checkbox" name="scantronconfig" '.$id.'value="'.$item.'"'.$checked{$item}.$onclick{$item}.' />'.
11131:                       $titles{$item}.'</label>'.('&nbsp;'x3);
11132:         if ($item eq 'csv') {
11133:             $datatable .= '<fieldset style="display:'.$currcsvsty.'" id="scantroncsv_cols">'.
11134:                           '<legend>'.&mt('CSV Column Mapping').'</legend>'.
11135:                           '<table><tr><th>'.&mt('Field').'</th><th>'.&mt('Location').'</th></tr>'."\n";
11136:             foreach my $col (@fields) {
11137:                 my $selnone;
11138:                 if ($csvfields{$col} eq '') {
11139:                     $selnone = ' selected="selected"';
11140:                 }
11141:                 $datatable .= '<tr><td>'.$titles{$col}.'</td>'.
11142:                               '<td><select name="scantronconfig_csv_'.$col.'" class="scantronconfig_csv">'.
11143:                               '<option value=""'.$selnone.'></option>';
11144:                 for (my $i=0; $i<20; $i++) {
11145:                     my $shown = $i+1;
11146:                     my $sel;
11147:                     unless ($selnone) {
11148:                         if (exists($csvfields{$col})) {
11149:                             if ($csvfields{$col} == $i) {
11150:                                 $sel = ' selected="selected"';
11151:                             }
11152:                         }
11153:                     }
11154:                     $datatable .= '<option value="'.$i.'"'.$sel.'>'.$shown.'</option>';
11155:                 }
11156:                 $datatable .= '</select></td></tr>';
11157:            }
11158:            $datatable .= '</table></fieldset>'.
11159:                          '<fieldset style="display:'.$currcsvsty.'" id="scantroncsv_options">'.
11160:                          '<legend>'.&mt('CSV Options').'</legend>';
11161:            foreach my $option ('hdr','pad','rem') {
11162:                $datatable .= '<span class="LC_nobreak">'.$titles{$option}.':'.
11163:                          '<label><input type="radio" name="scantroncsv_'.$option.'" value="1"'.$optionson{$option}.' />'.
11164:                          &mt('Yes').'</label>'.('&nbsp;'x2)."\n".
11165:                          '<label><input type="radio" name="scantroncsv_'.$option.'" value="0"'.$optionsoff{$option}.' />'.&mt('No').'</label></span><br />';
11166:            }
11167:            $datatable .= '</fieldset>';
11168:            $itemcount ++;
11169:         }
11170:     }
11171:     $datatable .= '</td></tr>';
11172:     $$rowtotal ++;
11173:     return $datatable;
11174: }
11175: 
11176: sub scantronconfig_titles {
11177:     return &Apache::lonlocal::texthash(
11178:                                           dat => 'Standard format (.dat)',
11179:                                           csv => 'Comma separated values (.csv)',
11180:                                           hdr => 'Remove first line in file (contains column titles)',
11181:                                           pad => 'Prepend 0s to PaperID',
11182:                                           rem => 'Remove leading spaces (except Question Response columns)',
11183:                                           CODE => 'CODE',
11184:                                           ID   => 'Student ID',
11185:                                           PaperID => 'Paper ID',
11186:                                           FirstName => 'First Name',
11187:                                           LastName => 'Last Name',
11188:                                           FirstQuestion => 'First Question Response',
11189:                                           Section => 'Section',
11190:     );
11191: }
11192: 
11193: sub scantroncsv_fields {
11194:     return ('PaperID','LastName','FirstName','ID','Section','CODE','FirstQuestion');
11195: }
11196: 
11197: sub print_coursecategories {
11198:     my ($position,$dom,$hdritem,$settings,$rowtotal) = @_;
11199:     my $datatable;
11200:     if ($position eq 'top') {
11201:         my (%checked);
11202:         my @catitems = ('unauth','auth');
11203:         my @cattypes = ('std','domonly','codesrch','none');
11204:         $checked{'unauth'} = 'std';
11205:         $checked{'auth'} = 'std';
11206:         if (ref($settings) eq 'HASH') {
11207:             foreach my $type (@cattypes) {
11208:                 if ($type eq $settings->{'unauth'}) {
11209:                     $checked{'unauth'} = $type;
11210:                 }
11211:                 if ($type eq $settings->{'auth'}) {
11212:                     $checked{'auth'} = $type;
11213:                 }
11214:             }
11215:         }
11216:         my %lt = &Apache::lonlocal::texthash (
11217:                                                unauth   => 'Catalog type for unauthenticated users',
11218:                                                auth     => 'Catalog type for authenticated users',
11219:                                                none     => 'No catalog',
11220:                                                std      => 'Standard catalog',
11221:                                                domonly  => 'Domain-only catalog',
11222:                                                codesrch => "Code search form",
11223:                                              );
11224:        my $itemcount = 0;
11225:        foreach my $item (@catitems) {
11226:            my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
11227:            $datatable .= '<tr '.$css_class.'>'.
11228:                          '<td>'.$lt{$item}.'</td>'.
11229:                          '<td class="LC_right_item"><span class="LC_nobreak">';
11230:            foreach my $type (@cattypes) {
11231:                my $ischecked;
11232:                if ($checked{$item} eq $type) {
11233:                    $ischecked=' checked="checked"';
11234:                }
11235:                $datatable .= '<label>'.
11236:                              '<input type="radio" name="coursecat_'.$item.'" value="'.$type.'"'.$ischecked.
11237:                              ' />'.$lt{$type}.'</label>&nbsp;';
11238:            }
11239:            $datatable .= '</span></td></tr>';
11240:            $itemcount ++;
11241:         }
11242:         $$rowtotal += $itemcount;
11243:     } elsif ($position eq 'middle') {
11244:         my $toggle_cats_crs = ' ';
11245:         my $toggle_cats_dom = ' checked="checked" ';
11246:         my $can_cat_crs = ' ';
11247:         my $can_cat_dom = ' checked="checked" ';
11248:         my $toggle_catscomm_comm = ' ';
11249:         my $toggle_catscomm_dom = ' checked="checked" ';
11250:         my $can_catcomm_comm = ' ';
11251:         my $can_catcomm_dom = ' checked="checked" ';
11252:         my $toggle_catsplace_place = ' ';
11253:         my $toggle_catsplace_dom = ' checked="checked" ';
11254:         my $can_catplace_place = ' ';
11255:         my $can_catplace_dom = ' checked="checked" ';
11256: 
11257:         if (ref($settings) eq 'HASH') {
11258:             if ($settings->{'togglecats'} eq 'crs') {
11259:                 $toggle_cats_crs = $toggle_cats_dom;
11260:                 $toggle_cats_dom = ' ';
11261:             }
11262:             if ($settings->{'categorize'} eq 'crs') {
11263:                 $can_cat_crs = $can_cat_dom;
11264:                 $can_cat_dom = ' ';
11265:             }
11266:             if ($settings->{'togglecatscomm'} eq 'comm') {
11267:                 $toggle_catscomm_comm = $toggle_catscomm_dom;
11268:                 $toggle_catscomm_dom = ' ';
11269:             }
11270:             if ($settings->{'categorizecomm'} eq 'comm') {
11271:                 $can_catcomm_comm = $can_catcomm_dom;
11272:                 $can_catcomm_dom = ' ';
11273:             }
11274:             if ($settings->{'togglecatsplace'} eq 'place') {
11275:                 $toggle_catsplace_place = $toggle_catsplace_dom;
11276:                 $toggle_catsplace_dom = ' ';
11277:             }
11278:             if ($settings->{'categorizeplace'} eq 'place') {
11279:                 $can_catplace_place = $can_catplace_dom;
11280:                 $can_catplace_dom = ' ';
11281:             }
11282:         }
11283:         my %title = &Apache::lonlocal::texthash (
11284:                      togglecats      => 'Show/Hide a course in catalog',
11285:                      togglecatscomm  => 'Show/Hide a community in catalog',
11286:                      togglecatsplace => 'Show/Hide a placement test in catalog',
11287:                      categorize      => 'Assign a category to a course',
11288:                      categorizecomm  => 'Assign a category to a community',
11289:                      categorizeplace => 'Assign a category to a placement test',
11290:                     );
11291:         my %level = &Apache::lonlocal::texthash (
11292:                      dom   => 'Set in Domain',
11293:                      crs   => 'Set in Course',
11294:                      comm  => 'Set in Community',
11295:                      place => 'Set in Placement Test',
11296:                     );
11297:         $datatable = '<tr class="LC_odd_row">'.
11298:                   '<td>'.$title{'togglecats'}.'</td>'.
11299:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
11300:                   '<input type="radio" name="togglecats"'.
11301:                   $toggle_cats_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
11302:                   '<label><input type="radio" name="togglecats"'.
11303:                   $toggle_cats_crs.' value="crs" />'.$level{'crs'}.'</label></span></td>'.
11304:                   '</tr><tr>'.
11305:                   '<td>'.$title{'categorize'}.'</td>'.
11306:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
11307:                   '<label><input type="radio" name="categorize"'.
11308:                   $can_cat_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
11309:                   '<label><input type="radio" name="categorize"'.
11310:                   $can_cat_crs.'value="crs" />'.$level{'crs'}.'</label></span></td>'.
11311:                   '</tr><tr class="LC_odd_row">'.
11312:                   '<td>'.$title{'togglecatscomm'}.'</td>'.
11313:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
11314:                   '<input type="radio" name="togglecatscomm"'.
11315:                   $toggle_catscomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
11316:                   '<label><input type="radio" name="togglecatscomm"'.
11317:                   $toggle_catscomm_comm.' value="comm" />'.$level{'comm'}.'</label></span></td>'.
11318:                   '</tr><tr>'.
11319:                   '<td>'.$title{'categorizecomm'}.'</td>'.
11320:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
11321:                   '<label><input type="radio" name="categorizecomm"'.
11322:                   $can_catcomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
11323:                   '<label><input type="radio" name="categorizecomm"'.
11324:                   $can_catcomm_comm.'value="comm" />'.$level{'comm'}.'</label></span></td>'.
11325:                   '</tr><tr class="LC_odd_row">'.
11326:                   '<td>'.$title{'togglecatsplace'}.'</td>'.
11327:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
11328:                   '<input type="radio" name="togglecatsplace"'.
11329:                   $toggle_catsplace_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
11330:                   '<label><input type="radio" name="togglecatscomm"'.
11331:                   $toggle_catsplace_place.' value="comm" />'.$level{'place'}.'</label></span></td>'.
11332:                   '</tr><tr>'.
11333:                   '<td>'.$title{'categorizeplace'}.'</td>'.
11334:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
11335:                   '<label><input type="radio" name="categorizeplace"'.
11336:                   $can_catplace_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
11337:                   '<label><input type="radio" name="categorizeplace"'.
11338:                   $can_catplace_place.'value="place" />'.$level{'place'}.'</label></span></td>'.
11339:                   '</tr>';
11340:         $$rowtotal += 6;
11341:     } else {
11342:         my $css_class;
11343:         my $itemcount = 1;
11344:         my $cathash; 
11345:         if (ref($settings) eq 'HASH') {
11346:             $cathash = $settings->{'cats'};
11347:         }
11348:         if (ref($cathash) eq 'HASH') {
11349:             my (@cats,@trails,%allitems,%idx,@jsarray);
11350:             &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,
11351:                                                    \%allitems,\%idx,\@jsarray);
11352:             my $maxdepth = scalar(@cats);
11353:             my $colattrib = '';
11354:             if ($maxdepth > 2) {
11355:                 $colattrib = ' colspan="2" ';
11356:             }
11357:             my @path;
11358:             if (@cats > 0) {
11359:                 if (ref($cats[0]) eq 'ARRAY') {
11360:                     my $numtop = @{$cats[0]};
11361:                     my $maxnum = $numtop;
11362:                     my %default_names = (
11363:                           instcode    => &mt('Official courses'),
11364:                           communities => &mt('Communities'),
11365:                           placement   => &mt('Placement Tests'),
11366:                     );
11367: 
11368:                     if ((!grep(/^instcode$/,@{$cats[0]})) || 
11369:                         ($cathash->{'instcode::0'} eq '') ||
11370:                         (!grep(/^communities$/,@{$cats[0]})) || 
11371:                         ($cathash->{'communities::0'} eq '') ||
11372:                         (!grep(/^placement$/,@{$cats[0]})) ||
11373:                         ($cathash->{'placement::0'} eq '')) {
11374:                         $maxnum ++;
11375:                     }
11376:                     my $lastidx;
11377:                     for (my $i=0; $i<$numtop; $i++) {
11378:                         my $parent = $cats[0][$i];
11379:                         $css_class = $itemcount%2?' class="LC_odd_row"':'';
11380:                         my $item = &escape($parent).'::0';
11381:                         my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$item','$idx{$item}'".');"';
11382:                         $lastidx = $idx{$item};
11383:                         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
11384:                                       .'<select name="'.$item.'"'.$chgstr.'>';
11385:                         for (my $k=0; $k<=$maxnum; $k++) {
11386:                             my $vpos = $k+1;
11387:                             my $selstr;
11388:                             if ($k == $i) {
11389:                                 $selstr = ' selected="selected" ';
11390:                             }
11391:                             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
11392:                         }
11393:                         $datatable .= '</select></span></td><td>';
11394:                         if ($parent eq 'instcode' || $parent eq 'communities' || $parent eq 'placement') {
11395:                             $datatable .=  '<span class="LC_nobreak">'
11396:                                            .$default_names{$parent}.'</span>';
11397:                             if ($parent eq 'instcode') {
11398:                                 $datatable .= '<br /><span class="LC_nobreak">('
11399:                                               .&mt('with institutional codes')
11400:                                               .')</span></td><td'.$colattrib.'>';
11401:                             } else {
11402:                                 $datatable .= '<table><tr><td>';
11403:                             }
11404:                             $datatable .= '<span class="LC_nobreak">'
11405:                                           .'<label><input type="radio" name="'
11406:                                           .$parent.'" value="1" checked="checked" />'
11407:                                           .&mt('Display').'</label>';
11408:                             if ($parent eq 'instcode') {
11409:                                 $datatable .= '&nbsp;';
11410:                             } else {
11411:                                 $datatable .= '</span></td></tr><tr><td>'
11412:                                               .'<span class="LC_nobreak">';
11413:                             }
11414:                             $datatable .= '<label><input type="radio" name="'
11415:                                           .$parent.'" value="0" />'
11416:                                           .&mt('Do not display').'</label></span>';
11417:                             if (($parent eq 'communities') || ($parent eq 'placement')) {
11418:                                 $datatable .= '</td></tr></table>';
11419:                             }
11420:                             $datatable .= '</td>';
11421:                         } else {
11422:                             $datatable .= $parent
11423:                                           .'&nbsp;<span class="LC_nobreak"><label>'
11424:                                           .'<input type="checkbox" name="deletecategory" '
11425:                                           .'value="'.$item.'" />'.&mt('Delete').'</label></span></td>';
11426:                         }
11427:                         my $depth = 1;
11428:                         push(@path,$parent);
11429:                         $datatable .= &build_category_rows($itemcount,\@cats,$depth,$parent,\@path,\%idx);
11430:                         pop(@path);
11431:                         $datatable .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
11432:                         $itemcount ++;
11433:                     }
11434:                     $css_class = $itemcount%2?' class="LC_odd_row"':'';
11435:                     my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','$lastidx'".');"';
11436:                     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="addcategory_pos"'.$chgstr.'>';
11437:                     for (my $k=0; $k<=$maxnum; $k++) {
11438:                         my $vpos = $k+1;
11439:                         my $selstr;
11440:                         if ($k == $numtop) {
11441:                             $selstr = ' selected="selected" ';
11442:                         }
11443:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
11444:                     }
11445:                     $datatable .= '</select></span></td><td colspan="2">'.&mt('Add category:').'&nbsp;'
11446:                                   .'<input type="text" size="20" name="addcategory_name" value="" /></td>'
11447:                                   .'</tr>'."\n";
11448:                     $itemcount ++;
11449:                     foreach my $default ('instcode','communities','placement') {
11450:                         if ((!grep(/^\Q$default\E$/,@{$cats[0]})) || ($cathash->{$default.'::0'} eq '')) {
11451:                             $css_class = $itemcount%2?' class="LC_odd_row"':'';
11452:                             my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','$lastidx'".');"';
11453:                             $datatable .= '<tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr><tr '.$css_class.'><td>'.
11454:                                           '<span class="LC_nobreak"><select name="'.$default.'_pos"'.$chgstr.'>';
11455:                             for (my $k=0; $k<=$maxnum; $k++) {
11456:                                 my $vpos = $k+1;
11457:                                 my $selstr;
11458:                                 if ($k == $maxnum) {
11459:                                     $selstr = ' selected="selected" ';
11460:                                 }
11461:                                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
11462:                             }
11463:                             $datatable .= '</select></span></td>'.
11464:                                           '<td><span class="LC_nobreak">'.
11465:                                           $default_names{$default}.'</span>';
11466:                             if ($default eq 'instcode') {
11467:                                 $datatable .= '<br /><span class="LC_nobreak">(' 
11468:                                               .&mt('with institutional codes').')</span>';
11469:                             }
11470:                             $datatable .= '</td>'
11471:                                           .'<td><span class="LC_nobreak"><label><input type="radio" name="'.$default.'" value="1" />'
11472:                                           .&mt('Display').'</label>&nbsp;'
11473:                                           .'<label><input type="radio" name="'.$default.'" value="0" checked="checked"/>'
11474:                                           .&mt('Do not display').'</label></span></td></tr>';
11475:                         }
11476:                     }
11477:                 }
11478:             } else {
11479:                 $datatable .= &initialize_categories($itemcount);
11480:             }
11481:         } else {
11482:             $datatable .= '<tr><td class="LC_right_item">'.$hdritem->{'header'}->[1]->{'col2'}.'</td></tr>'
11483:                           .&initialize_categories($itemcount);
11484:         }
11485:         $$rowtotal += $itemcount;
11486:     }
11487:     return $datatable;
11488: }
11489: 
11490: sub print_serverstatuses {
11491:     my ($dom,$settings,$rowtotal) = @_;
11492:     my $datatable;
11493:     my @pages = &serverstatus_pages();
11494:     my (%namedaccess,%machineaccess);
11495:     foreach my $type (@pages) {
11496:         $namedaccess{$type} = '';
11497:         $machineaccess{$type}= '';
11498:     }
11499:     if (ref($settings) eq 'HASH') {
11500:         foreach my $type (@pages) {
11501:             if (exists($settings->{$type})) {
11502:                 if (ref($settings->{$type}) eq 'HASH') {
11503:                     foreach my $key (keys(%{$settings->{$type}})) {
11504:                         if ($key eq 'namedusers') {
11505:                             $namedaccess{$type} = $settings->{$type}->{$key};
11506:                         } elsif ($key eq 'machines') {
11507:                             $machineaccess{$type} = $settings->{$type}->{$key};
11508:                         }
11509:                     }
11510:                 }
11511:             }
11512:         }
11513:     }
11514:     my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
11515:     my $rownum = 0;
11516:     my $css_class;
11517:     foreach my $type (@pages) {
11518:         $rownum ++;
11519:         $css_class = $rownum%2?' class="LC_odd_row"':'';
11520:         $datatable .= '<tr'.$css_class.'>'.
11521:                       '<td><span class="LC_nobreak">'.
11522:                       $titles->{$type}.'</span></td>'.
11523:                       '<td class="LC_left_item">'.
11524:                       '<input type="text" name="'.$type.'_namedusers" '.
11525:                       'value="'.$namedaccess{$type}.'" size="30" /></td>'.
11526:                       '<td class="LC_right_item">'.
11527:                       '<span class="LC_nobreak">'.
11528:                       '<input type="text" name="'.$type.'_machines" '.
11529:                       'value="'.$machineaccess{$type}.'" size="10" />'.
11530:                       '</span></td></tr>'."\n";
11531:     }
11532:     $$rowtotal += $rownum;
11533:     return $datatable;
11534: }
11535: 
11536: sub serverstatus_pages {
11537:     return ('userstatus','lonstatus','loncron','server-status','codeversions',
11538:             'checksums','clusterstatus','certstatus','metadata_keywords',
11539:             'metadata_harvest','takeoffline','takeonline','showenv','toggledebug',
11540:             'ping','domconf','uniquecodes','diskusage','coursecatalog');
11541: }
11542: 
11543: sub defaults_javascript {
11544:     my ($settings) = @_;
11545:     return unless (ref($settings) eq 'HASH');
11546:     my $portal_js = <<"ENDPORTAL";
11547: 
11548: function portalExtras(caller) {
11549:     var x = caller.value;
11550:     var y = new Array('email','web');
11551:     for (var i=0; i<y.length; i++) { 
11552:         if (document.getElementById('portal_def_'+y[i]+'_div')) {
11553:             var z = document.getElementById('portal_def_'+y[i]+'_div');
11554:             if (x.length > 0) {
11555:                 z.style.display = 'block';
11556:             } else {
11557:                 z.style.display = 'none';
11558:             }
11559:         }
11560:     }
11561: }
11562: ENDPORTAL
11563:     if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
11564:         my $maxnum = scalar(@{$settings->{'inststatusorder'}});
11565:         if ($maxnum eq '') {
11566:             $maxnum = 0;
11567:         }
11568:         $maxnum ++;
11569:         my $jstext = '    var inststatuses = Array('."'".join("','",@{$settings->{'inststatusorder'}})."'".');';  
11570:         return <<"ENDSCRIPT";
11571: <script type="text/javascript">
11572: // <![CDATA[
11573: function reorderTypes(form,caller) {
11574:     var changedVal;
11575: $jstext 
11576:     var newpos = 'addinststatus_pos';
11577:     var current = new Array;
11578:     var maxh = $maxnum;
11579:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
11580:     var oldVal;
11581:     if (caller == newpos) {
11582:         changedVal = newitemVal;
11583:     } else {
11584:         var curritem = 'inststatus_pos_'+caller;
11585:         changedVal = form.elements[curritem].options[form.elements[curritem].selectedIndex].value;
11586:         current[newitemVal] = newpos;
11587:     }
11588:     for (var i=0; i<inststatuses.length; i++) {
11589:         if (inststatuses[i] != caller) {
11590:             var elementName = 'inststatus_pos_'+inststatuses[i];
11591:             if (form.elements[elementName]) {
11592:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
11593:                 current[currVal] = elementName;
11594:             }
11595:         }
11596:     }
11597:     for (var j=0; j<maxh; j++) {
11598:         if (current[j] == undefined) {
11599:             oldVal = j;
11600:         }
11601:     }
11602:     if (oldVal < changedVal) {
11603:         for (var k=oldVal+1; k<=changedVal ; k++) {
11604:            var elementName = current[k];
11605:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
11606:         }
11607:     } else {
11608:         for (var k=changedVal; k<oldVal; k++) {
11609:             var elementName = current[k];
11610:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
11611:         }
11612:     }
11613:     return;
11614: }
11615: 
11616: $portal_js
11617: 
11618: // ]]>
11619: </script>
11620: 
11621: ENDSCRIPT
11622:     } else {
11623: return <<"ENDSCRIPT";
11624: <script type="text/javascript">
11625: // <![CDATA[
11626: $portal_js
11627: // ]]>
11628: </script>
11629: 
11630: ENDSCRIPT
11631:     }
11632:     return;
11633: }
11634: 
11635: sub passwords_javascript {
11636:     my ($prefix) = @_;
11637:     my %intalert;
11638:     if ($prefix eq 'passwords') {
11639:         %intalert = &Apache::lonlocal::texthash (
11640:             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.',
11641:             authcost => 'Warning: bcrypt encryption cost for internal authentication must be an integer.',
11642:             passmin => 'Warning: minimum password length must be a positive integer greater than 6.',
11643:             passmax => 'Warning: maximum password length must be a positive integer (or blank).',
11644:             passexp => 'Warning: days before password expiration must be a positive integer (or blank).',
11645:             passnum => 'Warning: number of previous passwords to save must be a positive integer (or blank).',
11646:         );
11647:     } elsif ($prefix eq 'secrets') {
11648:         %intalert = &Apache::lonlocal::texthash (
11649:             passmin => 'Warning: minimum secret length must be a positive integer greater than 6.',
11650:             passmax => 'Warning: maximum secret length must be a positive integer (or blank).',
11651:         );
11652:     }
11653:     &js_escape(\%intalert);
11654:     my $defmin = $Apache::lonnet::passwdmin;
11655:     my $intauthjs; 
11656:     if ($prefix eq 'passwords') { $intauthjs = <<"ENDSCRIPT";
11657: 
11658: function warnIntAuth(field) {
11659:     if (field.name == 'intauth_check') {
11660:         if (field.value == '2') {
11661:             alert('$intalert{authcheck}');
11662:         }
11663:     }
11664:     if (field.name == 'intauth_cost') {
11665:         field.value.replace(/\s/g,'');
11666:         if (field.value != '') {
11667:             var regexdigit=/^\\d+\$/;
11668:             if (!regexdigit.test(field.value)) {
11669:                 alert('$intalert{authcost}');
11670:             }
11671:         }
11672:     }
11673:     return;
11674: }
11675: 
11676: ENDSCRIPT
11677: 
11678:      }
11679: 
11680:      $intauthjs .= <<"ENDSCRIPT";
11681: 
11682: function warnInt$prefix(field) {
11683:     field.value.replace(/^\s+/,'');
11684:     field.value.replace(/\s+\$/,'');
11685:     var regexdigit=/^\\d+\$/;
11686:     if (field.name == '${prefix}_min') {
11687:         if (field.value == '') {
11688:             alert('$intalert{passmin}');
11689:             field.value = '$defmin';
11690:         } else {
11691:             if (!regexdigit.test(field.value)) {
11692:                 alert('$intalert{passmin}');
11693:                 field.value = '$defmin';
11694:             }
11695:             var minval = parseInt(field.value,10);
11696:             if (minval < $defmin) {
11697:                 alert('$intalert{passmin}');
11698:                 field.value = '$defmin';
11699:             }
11700:         }
11701:     } else {
11702:         if (field.value == '0') {
11703:             field.value = '';
11704:         }
11705:         if (field.value != '') {
11706:             if (field.name == '${prefix}_expire') {
11707:                 var regexpposnum=/^\\d+(|\\.\\d*)\$/; 
11708:                 if (!regexpposnum.test(field.value)) {
11709:                     alert('$intalert{passexp}');
11710:                     field.value = '';
11711:                 } else {
11712:                     var expval = parseFloat(field.value);
11713:                     if (expval == 0) {
11714:                         alert('$intalert{passexp}');
11715:                         field.value = '';
11716:                     }
11717:                 }
11718:             } else {
11719:                 if (!regexdigit.test(field.value)) {
11720:                     if (field.name == '${prefix}_max') {
11721:                         alert('$intalert{passmax}');
11722:                     } else {
11723:                         if (field.name == '${prefix}_numsaved') {
11724:                             alert('$intalert{passnum}');
11725:                         }
11726:                     }
11727:                     field.value = '';
11728:                 }
11729:             }
11730:         }
11731:     }
11732:     return;
11733: }
11734: 
11735: ENDSCRIPT
11736:     return &Apache::lonhtmlcommon::scripttag($intauthjs);
11737: }
11738: 
11739: sub coursecategories_javascript {
11740:     my ($settings) = @_;
11741:     my ($output,$jstext,$cathash);
11742:     if (ref($settings) eq 'HASH') {
11743:         $cathash = $settings->{'cats'};
11744:     }
11745:     if (ref($cathash) eq 'HASH') {
11746:         my (@cats,@jsarray,%idx);
11747:         &Apache::loncommon::gather_categories($cathash,\@cats,\%idx,\@jsarray);
11748:         if (@jsarray > 0) {
11749:             $jstext = '    var categories = Array('.scalar(@jsarray).');'."\n";
11750:             for (my $i=0; $i<@jsarray; $i++) {
11751:                 if (ref($jsarray[$i]) eq 'ARRAY') {
11752:                     my $catstr = join('","',@{$jsarray[$i]});
11753:                     $jstext .= '    categories['.$i.'] = Array("'.$catstr.'");'."\n";
11754:                 }
11755:             }
11756:         }
11757:     } else {
11758:         $jstext  = '    var categories = Array(1);'."\n".
11759:                    '    categories[0] = Array("instcode_pos");'."\n"; 
11760:     }
11761:     my $instcode_reserved = &mt('The name: [_1] is a reserved category.','"instcode"');
11762:     my $communities_reserved = &mt('The name: [_1] is a reserved category.','"communities"');
11763:     my $placement_reserved = &mt('The name: [_1] is a reserved category.','"placement"');
11764:     my $choose_again = "\n".&mt('Please use a different name for the new top level category.'); 
11765:     &js_escape(\$instcode_reserved);
11766:     &js_escape(\$communities_reserved);
11767:     &js_escape(\$placement_reserved);
11768:     &js_escape(\$choose_again);
11769:     $output = <<"ENDSCRIPT";
11770: <script type="text/javascript">
11771: // <![CDATA[
11772: function reorderCats(form,parent,item,idx) {
11773:     var changedVal;
11774: $jstext
11775:     var newpos = 'addcategory_pos';
11776:     if (parent == '') {
11777:         var has_instcode = 0;
11778:         var maxtop = categories[idx].length;
11779:         for (var j=0; j<maxtop; j++) {
11780:             if (categories[idx][j] == 'instcode::0') {
11781:                 has_instcode == 1;
11782:             }
11783:         }
11784:         if (has_instcode == 0) {
11785:             categories[idx][maxtop] = 'instcode_pos';
11786:         }
11787:     } else {
11788:         newpos += '_'+parent;
11789:     }
11790:     var maxh = 1 + categories[idx].length;
11791:     var current = new Array;
11792:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
11793:     if (item == newpos) {
11794:         changedVal = newitemVal;
11795:     } else {
11796:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
11797:         current[newitemVal] = newpos;
11798:     }
11799:     for (var i=0; i<categories[idx].length; i++) {
11800:         var elementName = categories[idx][i];
11801:         if (elementName != item) {
11802:             if (form.elements[elementName]) {
11803:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
11804:                 current[currVal] = elementName;
11805:             }
11806:         }
11807:     }
11808:     var oldVal;
11809:     for (var j=0; j<maxh; j++) {
11810:         if (current[j] == undefined) {
11811:             oldVal = j;
11812:         }
11813:     }
11814:     if (oldVal < changedVal) {
11815:         for (var k=oldVal+1; k<=changedVal ; k++) {
11816:            var elementName = current[k];
11817:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
11818:         }
11819:     } else {
11820:         for (var k=changedVal; k<oldVal; k++) {
11821:             var elementName = current[k];
11822:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
11823:         }
11824:     }
11825:     return;
11826: }
11827: 
11828: function categoryCheck(form) {
11829:     if (form.elements['addcategory_name'].value == 'instcode') {
11830:         alert('$instcode_reserved\\n$choose_again');
11831:         return false;
11832:     }
11833:     if (form.elements['addcategory_name'].value == 'communities') {
11834:         alert('$communities_reserved\\n$choose_again');
11835:         return false;
11836:     }
11837:     if (form.elements['addcategory_name'].value == 'placement') {
11838:         alert('$placement_reserved\\n$choose_again');
11839:         return false;
11840:     }
11841:     return true;
11842: }
11843: 
11844: // ]]>
11845: </script>
11846: 
11847: ENDSCRIPT
11848:     return $output;
11849: }
11850: 
11851: sub initialize_categories {
11852:     my ($itemcount) = @_;
11853:     my ($datatable,$css_class,$chgstr);
11854:     my %default_names = &Apache::lonlocal::texthash (
11855:                       instcode    => 'Official courses (with institutional codes)',
11856:                       communities => 'Communities',
11857:                       placement   => 'Placement Tests',
11858:                         );
11859:     my %selnum = (
11860:                    instcode    => '0',
11861:                    communities => '1',
11862:                    placement   => '2',
11863:                  );
11864:     my %selected;
11865:     foreach my $default ('instcode','communities','placement') {
11866:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
11867:         $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','0'".');"';
11868:         map { $selected{$selnum{$_}} = '' } keys(%selnum);
11869:         $selected{$selnum{$default}} = ' selected="selected"';
11870:         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
11871:                      .'<select name="'.$default.'_pos"'.$chgstr.'>'
11872:                      .'<option value="0"'.$selected{'0'}.'>1</option>'
11873:                      .'<option value="1"'.$selected{'1'}.'>2</option>'
11874:                      .'<option value="2"'.$selected{'2'}.'>3</option>'
11875:                      .'<option value="3">4</option></select>&nbsp;'
11876:                      .$default_names{$default}
11877:                      .'</span></td><td><span class="LC_nobreak">'
11878:                      .'<label><input type="radio" name="'.$default.'" value="1" checked="checked" />'
11879:                      .&mt('Display').'</label>&nbsp;<label>'
11880:                      .'<input type="radio" name="'.$default.'" value="0" />'.&mt('Do not display')
11881:                  .'</label></span></td></tr>';
11882:         $itemcount ++;
11883:     }
11884:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
11885:     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','0'".');"';
11886:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
11887:                   .'<select name="addcategory_pos"'.$chgstr.'>'
11888:                   .'<option value="0">1</option>'
11889:                   .'<option value="1">2</option>'
11890:                   .'<option value="2">3</option>'
11891:                   .'<option value="3" selected="selected">4</option></select>&nbsp;'
11892:                   .&mt('Add category').'</span></td><td><span class="LC_nobreak">'.&mt('Name:')
11893:                   .'&nbsp;<input type="text" size="20" name="addcategory_name" value="" /></span>'
11894:                   .'</td></tr>';
11895:     return $datatable;
11896: }
11897: 
11898: sub build_category_rows {
11899:     my ($itemcount,$cats,$depth,$parent,$path,$idx) = @_;
11900:     my ($text,$name,$item,$chgstr);
11901:     if (ref($cats) eq 'ARRAY') {
11902:         my $maxdepth = scalar(@{$cats});
11903:         if (ref($cats->[$depth]) eq 'HASH') {
11904:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
11905:                 my $numchildren = @{$cats->[$depth]{$parent}};
11906:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
11907:                 $text .= '<td><table class="LC_data_table">';
11908:                 my ($idxnum,$parent_name,$parent_item);
11909:                 my $higher = $depth - 1;
11910:                 if ($higher == 0) {
11911:                     $parent_name = &escape($parent).'::'.$higher;
11912:                 } else {
11913:                     if (ref($path) eq 'ARRAY') {
11914:                         $parent_name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
11915:                     }
11916:                 }
11917:                 $parent_item = 'addcategory_pos_'.$parent_name;
11918:                 for (my $j=0; $j<=$numchildren; $j++) {
11919:                     if ($j < $numchildren) {
11920:                         $name = $cats->[$depth]{$parent}[$j];
11921:                         $item = &escape($name).':'.&escape($parent).':'.$depth;
11922:                         $idxnum = $idx->{$item};
11923:                     } else {
11924:                         $name = $parent_name;
11925:                         $item = $parent_item;
11926:                     }
11927:                     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'$parent_name','$item','$idxnum'".');"';
11928:                     $text .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="'.$item.'"'.$chgstr.'>';
11929:                     for (my $i=0; $i<=$numchildren; $i++) {
11930:                         my $vpos = $i+1;
11931:                         my $selstr;
11932:                         if ($j == $i) {
11933:                             $selstr = ' selected="selected" ';
11934:                         }
11935:                         $text .= '<option value="'.$i.'"'.$selstr.'>'.$vpos.'</option>';
11936:                     }
11937:                     $text .= '</select>&nbsp;';
11938:                     if ($j < $numchildren) {
11939:                         my $deeper = $depth+1;
11940:                         $text .= $name.'&nbsp;'
11941:                                  .'<label><input type="checkbox" name="deletecategory" value="'
11942:                                  .$item.'" />'.&mt('Delete').'</label></span></td><td>';
11943:                         if(ref($path) eq 'ARRAY') {
11944:                             push(@{$path},$name);
11945:                             $text .= &build_category_rows($itemcount,$cats,$deeper,$name,$path,$idx);
11946:                             pop(@{$path});
11947:                         }
11948:                     } else {
11949:                         $text .= &mt('Add subcategory:').'&nbsp;</span><input type="text" size="20" name="addcategory_name_';
11950:                         if ($j == $numchildren) {
11951:                             $text .= $name;
11952:                         } else {
11953:                             $text .= $item;
11954:                         }
11955:                         $text .= '" value="" />';
11956:                     }
11957:                     $text .= '</td></tr>';
11958:                 }
11959:                 $text .= '</table></td>';
11960:             } else {
11961:                 my $higher = $depth-1;
11962:                 if ($higher == 0) {
11963:                     $name = &escape($parent).'::'.$higher;
11964:                 } else {
11965:                     if (ref($path) eq 'ARRAY') {
11966:                         $name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
11967:                     }
11968:                 }
11969:                 my $colspan;
11970:                 if ($parent ne 'instcode') {
11971:                     $colspan = $maxdepth - $depth - 1;
11972:                     $text .= '<td colspan="'.$colspan.'">'.&mt('Add subcategory:').'<input type="text" size="20" name="subcat_'.$name.'" value="" /></td>';
11973:                 }
11974:             }
11975:         }
11976:     }
11977:     return $text;
11978: }
11979: 
11980: sub modifiable_userdata_row {
11981:     my ($context,$item,$settings,$numinrow,$rowcount,$usertypes,$fieldsref,$titlesref,
11982:         $rowid,$customcss,$rowstyle,$itemdesc) = @_;
11983:     my ($role,$rolename,$statustype);
11984:     $role = $item;
11985:     if ($context eq 'cancreate') {
11986:         if ($item =~ /^(emailusername)_(.+)$/) {
11987:             $role = $1;
11988:             $statustype = $2;
11989:             if (ref($usertypes) eq 'HASH') {
11990:                 if ($usertypes->{$statustype}) {
11991:                     $rolename = &mt('Data provided by [_1]',$usertypes->{$statustype});
11992:                 } else {
11993:                     $rolename = &mt('Data provided by user');
11994:                 }
11995:             }
11996:         }
11997:     } elsif ($context eq 'selfcreate') {
11998:         if (ref($usertypes) eq 'HASH') {
11999:             $rolename = $usertypes->{$role};
12000:         } else {
12001:             $rolename = $role;
12002:         }
12003:     } elsif ($context eq 'lti') {
12004:         $rolename = &mt('Institutional data used (if available)');
12005:     } elsif ($context eq 'privacy') {
12006:         $rolename = $itemdesc;
12007:     } else {
12008:         if ($role eq 'cr') {
12009:             $rolename = &mt('Custom role');
12010:         } else {
12011:             $rolename = &Apache::lonnet::plaintext($role);
12012:         }
12013:     }
12014:     my (@fields,%fieldtitles);
12015:     if (ref($fieldsref) eq 'ARRAY') {
12016:         @fields = @{$fieldsref};
12017:     } else {
12018:         @fields = ('lastname','firstname','middlename','generation',
12019:                    'permanentemail','id');
12020:     }
12021:     if ((ref($titlesref) eq 'HASH')) {
12022:         %fieldtitles = %{$titlesref};
12023:     } else {
12024:         %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
12025:     }
12026:     my $output;
12027:     my $css_class;
12028:     if ($rowcount%2) {
12029:         $css_class = 'LC_odd_row';
12030:     }
12031:     if ($customcss) {
12032:         $css_class .= " $customcss";
12033:     }
12034:     $css_class =~ s/^\s+//;
12035:     if ($css_class) {
12036:         $css_class = ' class="'.$css_class.'"';
12037:     }
12038:     if ($rowstyle) {
12039:         $css_class .= ' style="'.$rowstyle.'"';
12040:     }
12041:     if ($rowid) {
12042:         $rowid = ' id="'.$rowid.'"';
12043:     }
12044:     $output = '<tr '.$css_class.$rowid.'>'.
12045:               '<td><span class="LC_nobreak">'.$rolename.'</span></td>'.
12046:               '<td class="LC_left_item" colspan="2"><table>';
12047:     my $rem;
12048:     my %checks;
12049:     my %current;
12050:     if (ref($settings) eq 'HASH') {
12051:         my $hashref;
12052:         if ($context eq 'lti') {
12053:             if (ref($settings) eq 'HASH') {
12054:                 $hashref = $settings->{'instdata'};
12055:             }
12056:         } elsif ($context eq 'privacy') {
12057:             my ($key,$inner) = split(/_/,$role);
12058:             if (ref($settings) eq 'HASH') {
12059:                 if (ref($settings->{$key}) eq 'HASH') {
12060:                     $hashref = $settings->{$key}->{$inner};
12061:                 }
12062:             }
12063:         } elsif (ref($settings->{$context}) eq 'HASH') {
12064:             if (ref($settings->{$context}->{$role}) eq 'HASH') {
12065:                 $hashref = $settings->{'lti_instdata'};
12066:             }
12067:             if ($role eq 'emailusername') {
12068:                 if ($statustype) {
12069:                     if (ref($settings->{$context}->{$role}->{$statustype}) eq 'HASH') {
12070:                         $hashref = $settings->{$context}->{$role}->{$statustype};
12071:                     }
12072:                 }
12073:             }
12074:         }
12075:         if (ref($hashref) eq 'HASH') { 
12076:             foreach my $field (@fields) {
12077:                 if ($hashref->{$field}) {
12078:                     if ($role eq 'emailusername') {
12079:                         $checks{$field} = $hashref->{$field};
12080:                     } else {
12081:                         $checks{$field} = ' checked="checked" ';
12082:                     }
12083:                 }
12084:             }
12085:         }
12086:     }
12087:  
12088:     my $total = scalar(@fields);
12089:     for (my $i=0; $i<$total; $i++) {
12090:         $rem = $i%($numinrow);
12091:         if ($rem == 0) {
12092:             if ($i > 0) {
12093:                 $output .= '</tr>';
12094:             }
12095:             $output .= '<tr>';
12096:         }
12097:         my $check = ' ';
12098:         unless ($role eq 'emailusername') {
12099:             if (exists($checks{$fields[$i]})) {
12100:                 $check = $checks{$fields[$i]};
12101:             } elsif ($context eq 'privacy') {
12102:                 if ($role =~ /^priv_(domain|course)$/) {
12103:                     if (ref($settings) ne 'HASH') {
12104:                         $check = ' checked="checked" ';
12105:                     }
12106:                 } elsif ($role =~ /^priv_(author|community)$/) {
12107:                     if (ref($settings) ne 'HASH') {
12108:                         unless ($fields[$i] eq 'id') {
12109:                             $check = ' checked="checked" ';
12110:                         }
12111:                     }
12112:                 } elsif ($role =~ /^(unpriv|othdom)_/) {
12113:                     if (ref($settings) ne 'HASH') {
12114:                         if (($fields[$i] eq 'lastname') || ($fields[$i] eq 'firstname')) {
12115:                             $check = ' checked="checked" ';
12116:                         }
12117:                     }
12118:                 }
12119:             } elsif ($context ne 'lti') {
12120:                 if ($role eq 'st') {
12121:                     if (ref($settings) ne 'HASH') {
12122:                         $check = ' checked="checked" '; 
12123:                     }
12124:                 }
12125:             }
12126:         }
12127:         $output .= '<td class="LC_left_item">'.
12128:                    '<span class="LC_nobreak">';
12129:         my $prefix = 'canmodify';
12130:         if ($role eq 'emailusername') {
12131:             unless ($checks{$fields[$i]} =~ /^(required|optional)$/) {
12132:                 $checks{$fields[$i]} = 'omit';
12133:             }
12134:             foreach my $option ('required','optional','omit') {
12135:                 my $checked='';
12136:                 if ($checks{$fields[$i]} eq $option) {
12137:                     $checked='checked="checked" ';
12138:                 }
12139:                 $output .= '<label>'.
12140:                            '<input type="radio" name="'.$prefix.'_'.$item.'_'.$fields[$i].'" value="'.$option.'" '.$checked.'/>'.
12141:                            &mt($option).'</label>'.('&nbsp;' x2);
12142:             }
12143:             $output .= '<i>'.$fieldtitles{$fields[$i]}.'</i>';
12144:         } else {
12145:             if ($context eq 'lti') {
12146:                 $prefix = 'lti';
12147:             } elsif ($context eq 'privacy') {
12148:                 $prefix = 'privacy';
12149:             }
12150:             $output .= '<label>'.
12151:                        '<input type="checkbox" name="'.$prefix.'_'.$role.'" '.
12152:                        'value="'.$fields[$i].'"'.$check.'/>'.$fieldtitles{$fields[$i]}.
12153:                        '</label>';
12154:         }
12155:         $output .= '</span></td>';
12156:     }
12157:     $rem = $total%$numinrow;
12158:     my $colsleft;
12159:     if ($rem) {
12160:         $colsleft = $numinrow - $rem;
12161:     }
12162:     if ($colsleft > 1) {
12163:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
12164:                    '&nbsp;</td>';
12165:     } elsif ($colsleft == 1) {
12166:         $output .= '<td class="LC_left_item">&nbsp;</td>';
12167:     }
12168:     $output .= '</tr></table></td></tr>';
12169:     return $output;
12170: }
12171: 
12172: sub insttypes_row {
12173:     my ($settings,$types,$usertypes,$dom,$numinrow,$othertitle,$context,$rowtotal,$onclick,
12174:         $customcss,$rowstyle) = @_;
12175:     my %lt = &Apache::lonlocal::texthash (
12176:                       cansearch => 'Users allowed to search',
12177:                       statustocreate => 'Institutional affiliation(s) able to create own account (login/SSO)',
12178:                       lockablenames => 'User preference to lock name',
12179:                       selfassign    => 'Self-reportable affiliations',
12180:                       overrides     => "Override domain's helpdesk settings based on requester's affiliation",
12181:              );
12182:     my $showdom;
12183:     if ($context eq 'cansearch') {
12184:         $showdom = ' ('.$dom.')';
12185:     }
12186:     my $class = 'LC_left_item';
12187:     if ($context eq 'statustocreate') {
12188:         $class = 'LC_right_item';
12189:     }
12190:     my $css_class;
12191:     if ($$rowtotal%2) {
12192:         $css_class = 'LC_odd_row';
12193:     }
12194:     if ($customcss) {
12195:         $css_class .= ' '.$customcss;
12196:     }
12197:     $css_class =~ s/^\s+//;
12198:     if ($css_class) {
12199:         $css_class = ' class="'.$css_class.'"';
12200:     }
12201:     if ($rowstyle) {
12202:         $css_class .= ' style="'.$rowstyle.'"';
12203:     }
12204:     if ($onclick) {
12205:         $onclick = 'onclick="'.$onclick.'" ';
12206:     }
12207:     my $output = '<tr'.$css_class.'>'.
12208:                  '<td>'.$lt{$context}.$showdom.
12209:                  '</td><td class="'.$class.'" colspan="2"><table>';
12210:     my $rem;
12211:     if (ref($types) eq 'ARRAY') {
12212:         for (my $i=0; $i<@{$types}; $i++) {
12213:             if (defined($usertypes->{$types->[$i]})) {
12214:                 my $rem = $i%($numinrow);
12215:                 if ($rem == 0) {
12216:                     if ($i > 0) {
12217:                         $output .= '</tr>';
12218:                     }
12219:                     $output .= '<tr>';
12220:                 }
12221:                 my $check = ' ';
12222:                 if (ref($settings) eq 'HASH') {
12223:                     if (ref($settings->{$context}) eq 'ARRAY') {
12224:                         if (grep(/^\Q$types->[$i]\E$/,@{$settings->{$context}})) {
12225:                             $check = ' checked="checked" ';
12226:                         }
12227:                     } elsif (ref($settings->{$context}) eq 'HASH') {
12228:                         if (ref($settings->{$context}->{$types->[$i]}) eq 'HASH') {
12229:                             $check = ' checked="checked" ';
12230:                         }
12231:                     } elsif ($context eq 'statustocreate') {
12232:                         $check = ' checked="checked" ';
12233:                     }
12234:                 }
12235:                 $output .= '<td class="LC_left_item">'.
12236:                            '<span class="LC_nobreak"><label>'.
12237:                            '<input type="checkbox" name="'.$context.'" '.
12238:                            'value="'.$types->[$i].'"'.$check.$onclick.' />'.
12239:                            $usertypes->{$types->[$i]}.'</label></span></td>';
12240:             }
12241:         }
12242:         $rem = @{$types}%($numinrow);
12243:     }
12244:     my $colsleft = $numinrow - $rem;
12245:     if ($context eq 'overrides') {
12246:         if ($colsleft > 1) {
12247:             $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
12248:         } else {
12249:             $output .= '<td class="LC_left_item">';
12250:         }
12251:         $output .= '&nbsp;';  
12252:     } else {
12253:         if ($rem == 0) {
12254:             $output .= '<tr>';
12255:         }
12256:         if ($colsleft > 1) {
12257:             $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
12258:         } else {
12259:             $output .= '<td class="LC_left_item">';
12260:         }
12261:         my $defcheck = ' ';
12262:         if (ref($settings) eq 'HASH') {  
12263:             if (ref($settings->{$context}) eq 'ARRAY') {
12264:                 if (grep(/^default$/,@{$settings->{$context}})) {
12265:                     $defcheck = ' checked="checked" ';
12266:                 }
12267:             } elsif ($context eq 'statustocreate') {
12268:                 $defcheck = ' checked="checked" ';
12269:             }
12270:         }
12271:         $output .= '<span class="LC_nobreak"><label>'.
12272:                    '<input type="checkbox" name="'.$context.'" '.
12273:                    'value="default"'.$defcheck.$onclick.' />'.
12274:                    $othertitle.'</label></span>';
12275:     }
12276:     $output .= '</td></tr></table></td></tr>';
12277:     return $output;
12278: }
12279: 
12280: sub sorted_searchtitles {
12281:     my %searchtitles = &Apache::lonlocal::texthash(
12282:                          'uname' => 'username',
12283:                          'lastname' => 'last name',
12284:                          'lastfirst' => 'last name, first name',
12285:                      );
12286:     my @titleorder = ('uname','lastname','lastfirst');
12287:     return (\%searchtitles,\@titleorder);
12288: }
12289: 
12290: sub sorted_searchtypes {
12291:     my %srchtypes_desc = (
12292:                            exact    => 'is exact match',
12293:                            contains => 'contains ..',
12294:                            begins   => 'begins with ..',
12295:                          );
12296:     my @srchtypeorder = ('exact','begins','contains');
12297:     return (\%srchtypes_desc,\@srchtypeorder);
12298: }
12299: 
12300: sub usertype_update_row {
12301:     my ($settings,$usertypes,$fieldtitles,$fields,$types,$rownums) = @_;
12302:     my $datatable;
12303:     my $numinrow = 4;
12304:     foreach my $type (@{$types}) {
12305:         if (defined($usertypes->{$type})) {
12306:             $$rownums ++;
12307:             my $css_class = $$rownums%2?' class="LC_odd_row"':'';
12308:             $datatable .= '<tr'.$css_class.'><td>'.$usertypes->{$type}.
12309:                           '</td><td class="LC_left_item"><table>';
12310:             for (my $i=0; $i<@{$fields}; $i++) {
12311:                 my $rem = $i%($numinrow);
12312:                 if ($rem == 0) {
12313:                     if ($i > 0) {
12314:                         $datatable .= '</tr>';
12315:                     }
12316:                     $datatable .= '<tr>';
12317:                 }
12318:                 my $check = ' ';
12319:                 if (ref($settings) eq 'HASH') {
12320:                     if (ref($settings->{'fields'}) eq 'HASH') {
12321:                         if (ref($settings->{'fields'}{$type}) eq 'ARRAY') {
12322:                             if (grep(/^\Q$fields->[$i]\E$/,@{$settings->{'fields'}{$type}})) {
12323:                                 $check = ' checked="checked" ';
12324:                             }
12325:                         }
12326:                     }
12327:                 }
12328: 
12329:                 if ($i == @{$fields}-1) {
12330:                     my $colsleft = $numinrow - $rem;
12331:                     if ($colsleft > 1) {
12332:                         $datatable .= '<td colspan="'.$colsleft.'">';
12333:                     } else {
12334:                         $datatable .= '<td>';
12335:                     }
12336:                 } else {
12337:                     $datatable .= '<td>';
12338:                 }
12339:                 $datatable .= '<span class="LC_nobreak"><label>'.
12340:                               '<input type="checkbox" name="updateable_'.$type.
12341:                               '_'.$fields->[$i].'" value="1"'.$check.'/>'.
12342:                               $fieldtitles->{$fields->[$i]}.'</label></span></td>';
12343:             }
12344:             $datatable .= '</tr></table></td></tr>';
12345:         }
12346:     }
12347:     return $datatable;
12348: }
12349: 
12350: sub modify_login {
12351:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
12352:     my ($resulttext,$errors,$colchgtext,%changes,%colchanges,%newfile,%newurl,
12353:         %curr_loginvia,%loginhash,@currlangs,@newlangs,$addedfile,%title,@offon,
12354:         %currsaml,%saml,%samltext,%samlimg,%samlalt,%samlurl,%samltitle,%samlwindow,%samlnotsso);
12355:     %title = ( coursecatalog => 'Display course catalog',
12356:                adminmail => 'Display administrator E-mail address',
12357:                helpdesk  => 'Display "Contact Helpdesk" link',
12358:                newuser => 'Link for visitors to create a user account',
12359:                loginheader => 'Log-in box header',
12360:                saml => 'Dual SSO and non-SSO login');
12361:     @offon = ('off','on');
12362:     if (ref($domconfig{login}) eq 'HASH') {
12363:         if (ref($domconfig{login}{loginvia}) eq 'HASH') {
12364:             foreach my $lonhost (keys(%{$domconfig{login}{loginvia}})) {
12365:                 $curr_loginvia{$lonhost} = $domconfig{login}{loginvia}{$lonhost};
12366:             }
12367:         }
12368:         if (ref($domconfig{login}{'saml'}) eq 'HASH') {
12369:             foreach my $lonhost (keys(%{$domconfig{login}{'saml'}})) {
12370:                 if (ref($domconfig{login}{'saml'}{$lonhost}) eq 'HASH') {
12371:                     $currsaml{$lonhost} = $domconfig{login}{'saml'}{$lonhost};
12372:                     $saml{$lonhost} = 1;
12373:                     $samltext{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'text'};
12374:                     $samlurl{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'url'};
12375:                     $samlalt{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'alt'};
12376:                     $samlimg{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'img'};
12377:                     $samltitle{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'title'};
12378:                     $samlwindow{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'window'};
12379:                     $samlnotsso{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'notsso'};
12380:                 }
12381:             }
12382:         }
12383:     }
12384:     ($errors,%colchanges) = &modify_colors($r,$dom,$confname,['login'],
12385:                                            \%domconfig,\%loginhash);
12386:     my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
12387:     foreach my $item (@toggles) {
12388:         $loginhash{login}{$item} = $env{'form.'.$item};
12389:     }
12390:     $loginhash{login}{loginheader} = $env{'form.loginheader'};
12391:     if (ref($colchanges{'login'}) eq 'HASH') {  
12392:         $colchgtext = &display_colorchgs($dom,\%colchanges,['login'],
12393:                                          \%loginhash);
12394:     }
12395: 
12396:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
12397:     my %domservers = &Apache::lonnet::get_servers($dom);
12398:     my @loginvia_attribs = ('serverpath','custompath','exempt');
12399:     if (keys(%servers) > 1) {
12400:         foreach my $lonhost (keys(%servers)) {
12401:             next if ($env{'form.'.$lonhost.'_server'} eq $lonhost);
12402:             if (ref($curr_loginvia{$lonhost}) eq 'HASH') {
12403:                 if ($env{'form.'.$lonhost.'_server'} eq $curr_loginvia{$lonhost}{'server'}) {
12404:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $curr_loginvia{$lonhost}{'server'};
12405:                 } elsif ($curr_loginvia{$lonhost}{'server'} ne '') {
12406:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
12407:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
12408:                         $changes{'loginvia'}{$lonhost} = 1;
12409:                     } else {
12410:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = '';
12411:                         $changes{'loginvia'}{$lonhost} = 1;
12412:                     }
12413:                 } else {
12414:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
12415:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
12416:                         $changes{'loginvia'}{$lonhost} = 1;
12417:                     }
12418:                 }
12419:                 if ($loginhash{login}{loginvia}{$lonhost}{'server'} eq '') {
12420:                     foreach my $item (@loginvia_attribs) {
12421:                         $loginhash{login}{loginvia}{$lonhost}{$item} = '';
12422:                     }
12423:                 } else {
12424:                     foreach my $item (@loginvia_attribs) {
12425:                         my $new = $env{'form.'.$lonhost.'_'.$item};
12426:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
12427:                             $env{'form.'.$lonhost.'_custompath'} =~ s/\s+//g;
12428:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
12429:                                 $new = '/';
12430:                             }
12431:                         }
12432:                         if (($item eq 'custompath') && 
12433:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
12434:                             $new = '';
12435:                         }
12436:                         if ($new ne $curr_loginvia{$lonhost}{$item}) {
12437:                             $changes{'loginvia'}{$lonhost} = 1;
12438:                         }
12439:                         if ($item eq 'exempt') {
12440:                             $new = &check_exempt_addresses($new);
12441:                         }
12442:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
12443:                     }
12444:                 }
12445:             } else {
12446:                 if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
12447:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
12448:                     $changes{'loginvia'}{$lonhost} = 1;
12449:                     foreach my $item (@loginvia_attribs) {
12450:                         my $new = $env{'form.'.$lonhost.'_'.$item};
12451:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
12452:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
12453:                                 $new = '/';
12454:                             }
12455:                         }
12456:                         if (($item eq 'custompath') && 
12457:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
12458:                             $new = '';
12459:                         }
12460:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
12461:                     }
12462:                 }
12463:             }
12464:         }
12465:     }
12466: 
12467:     my $servadm = $r->dir_config('lonAdmEMail');
12468:     my %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
12469:     if (ref($domconfig{'login'}) eq 'HASH') {
12470:         if (ref($domconfig{'login'}{'helpurl'}) eq 'HASH') {
12471:             foreach my $lang (sort(keys(%{$domconfig{'login'}{'helpurl'}}))) {
12472:                 if ($lang eq 'nolang') {
12473:                     push(@currlangs,$lang);
12474:                 } elsif (defined($langchoices{$lang})) {
12475:                     push(@currlangs,$lang);
12476:                 } else {
12477:                     next;
12478:                 }
12479:             }
12480:         }
12481:     }
12482:     my @delurls = &Apache::loncommon::get_env_multiple('form.loginhelpurl_del');
12483:     if (@currlangs > 0) {
12484:         foreach my $lang (@currlangs) {
12485:             if (grep(/^\Q$lang\E$/,@delurls)) {
12486:                 $changes{'helpurl'}{$lang} = 1;
12487:             } elsif ($env{'form.loginhelpurl_'.$lang.'.filename'}) {
12488:                 $changes{'helpurl'}{$lang} = 1;
12489:                 $newfile{$lang} = $env{'form.loginhelpurl_'.$lang.'.filename'};
12490:                 push(@newlangs,$lang);
12491:             } else {
12492:                 $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
12493:             }
12494:         }
12495:     }
12496:     unless (grep(/^nolang$/,@currlangs)) {
12497:         if ($env{'form.loginhelpurl_nolang.filename'}) {
12498:             $changes{'helpurl'}{'nolang'} = 1;
12499:             $newfile{'nolang'} = $env{'form.loginhelpurl_nolang.filename'};
12500:             push(@newlangs,'nolang');
12501:         }
12502:     }
12503:     if ($env{'form.loginhelpurl_add_lang'}) {
12504:         if ((defined($langchoices{$env{'form.loginhelpurl_add_lang'}})) &&
12505:             ($env{'form.loginhelpurl_add_file.filename'})) {
12506:             $newfile{$env{'form.loginhelpurl_add_lang'}} = $env{'form.loginhelpurl_add_file.filename'};
12507:             $addedfile = $env{'form.loginhelpurl_add_lang'};
12508:         }
12509:     }
12510:     if ((@newlangs > 0) || ($addedfile)) {
12511:         my $error;
12512:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
12513:         if ($configuserok eq 'ok') {
12514:             if ($switchserver) {
12515:                 $error = &mt("Upload of custom help file is not permitted to this server: [_1]",$switchserver);
12516:             } elsif ($author_ok eq 'ok') {
12517:                 my @allnew = @newlangs;
12518:                 if ($addedfile ne '') {
12519:                     push(@allnew,$addedfile);
12520:                 }
12521:                 foreach my $lang (@allnew) {
12522:                     my $formelem = 'loginhelpurl_'.$lang;
12523:                     if ($lang eq $env{'form.loginhelpurl_add_lang'}) {
12524:                         $formelem = 'loginhelpurl_add_file';
12525:                     }
12526:                     (my $result,$newurl{$lang}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
12527:                                                                "help/$lang",'','',$newfile{$lang});
12528:                     if ($result eq 'ok') {
12529:                         $loginhash{'login'}{'helpurl'}{$lang} = $newurl{$lang};
12530:                         $changes{'helpurl'}{$lang} = 1;
12531:                     } else {
12532:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$newfile{$lang},$result);
12533:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
12534:                         if ((grep(/^\Q$lang\E$/,@currlangs)) &&
12535:                             (!grep(/^\Q$lang\E$/,@delurls))) {
12536:                             $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
12537:                         }
12538:                     }
12539:                 }
12540:             } else {
12541:                 $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);
12542:             }
12543:         } else {
12544:             $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);
12545:         }
12546:         if ($error) {
12547:             &Apache::lonnet::logthis($error);
12548:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12549:         }
12550:     }
12551: 
12552:     my (%currheadtagurls,%currexempt,@newhosts,%newheadtagurls,%possexempt);
12553:     if (ref($domconfig{'login'}) eq 'HASH') {
12554:         if (ref($domconfig{'login'}{'headtag'}) eq 'HASH') {
12555:             foreach my $lonhost (keys(%{$domconfig{'login'}{'headtag'}})) {
12556:                 if ($domservers{$lonhost}) {
12557:                     if (ref($domconfig{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
12558:                         $currheadtagurls{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'url'};
12559:                         $currexempt{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'exempt'};
12560:                     }
12561:                 }
12562:             }
12563:         }
12564:     }
12565:     my @delheadtagurls = &Apache::loncommon::get_env_multiple('form.loginheadtag_del');
12566:     foreach my $lonhost (sort(keys(%domservers))) {
12567:         if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
12568:             $changes{'headtag'}{$lonhost} = 1;
12569:         } else {
12570:             if ($env{'form.loginheadtagexempt_'.$lonhost}) {
12571:                 $possexempt{$lonhost} = &check_exempt_addresses($env{'form.loginheadtagexempt_'.$lonhost});
12572:             }
12573:             if ($env{'form.loginheadtag_'.$lonhost.'.filename'}) {
12574:                 push(@newhosts,$lonhost);
12575:             } elsif ($currheadtagurls{$lonhost}) {
12576:                 $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $currheadtagurls{$lonhost};
12577:                 if ($currexempt{$lonhost}) {
12578:                     if ((!exists($possexempt{$lonhost})) || ($possexempt{$lonhost} ne $currexempt{$lonhost})) {
12579:                         $changes{'headtag'}{$lonhost} = 1;
12580:                     }
12581:                 } elsif ($possexempt{$lonhost}) {
12582:                     $changes{'headtag'}{$lonhost} = 1;
12583:                 }
12584:                 if ($possexempt{$lonhost}) {
12585:                     $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
12586:                 }
12587:             }
12588:         }
12589:     }
12590:     if (@newhosts) {
12591:         my $error;
12592:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
12593:         if ($configuserok eq 'ok') {
12594:             if ($switchserver) {
12595:                 $error = &mt("Upload of custom markup is not permitted to this server: [_1]",$switchserver);
12596:             } elsif ($author_ok eq 'ok') {
12597:                 foreach my $lonhost (@newhosts) {
12598:                     my $formelem = 'loginheadtag_'.$lonhost;
12599:                     (my $result,$newheadtagurls{$lonhost}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
12600:                                                                           "login/headtag/$lonhost",'','',
12601:                                                                           $env{'form.loginheadtag_'.$lonhost.'.filename'});
12602:                     if ($result eq 'ok') {
12603:                         $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $newheadtagurls{$lonhost};
12604:                         $changes{'headtag'}{$lonhost} = 1;
12605:                         if ($possexempt{$lonhost}) {
12606:                             $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
12607:                         }
12608:                     } else {
12609:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",
12610:                                            $newheadtagurls{$lonhost},$result);
12611:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
12612:                         if ((grep(/^\Q$lonhost\E$/,keys(%currheadtagurls))) &&
12613:                             (!grep(/^\Q$lonhost\E$/,@delheadtagurls))) {
12614:                             $loginhash{'login'}{'headtag'}{$lonhost} = $currheadtagurls{$lonhost};
12615:                         }
12616:                     }
12617:                 }
12618:             } else {
12619:                 $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);
12620:             }
12621:         } else {
12622:             $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);
12623:         }
12624:         if ($error) {
12625:             &Apache::lonnet::logthis($error);
12626:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12627:         }
12628:     }
12629:     my @delsamlimg = &Apache::loncommon::get_env_multiple('form.saml_img_del');
12630:     my @newsamlimgs;
12631:     foreach my $lonhost (keys(%domservers)) {
12632:         if ($env{'form.saml_'.$lonhost}) {
12633:             if ($env{'form.saml_img_'.$lonhost.'.filename'}) {
12634:                 push(@newsamlimgs,$lonhost);
12635:             }
12636:             foreach my $item ('text','alt','url','title','window','notsso') {
12637:                 $env{'form.saml_'.$item.'_'.$lonhost} =~ s/^\s+|\s+$//g;
12638:             }
12639:             if ($saml{$lonhost}) {
12640:                 if ($env{'form.saml_window_'.$lonhost} ne '1') {
12641:                     $env{'form.saml_window_'.$lonhost} = '';
12642:                 }
12643:                 if (grep(/^\Q$lonhost\E$/,@delsamlimg)) {
12644: #FIXME Need to obsolete published image
12645:                     delete($currsaml{$lonhost}{'img'});
12646:                     $changes{'saml'}{$lonhost} = 1;
12647:                 }
12648:                 if ($env{'form.saml_alt_'.$lonhost} ne $samlalt{$lonhost}) {
12649:                     $changes{'saml'}{$lonhost} = 1;
12650:                 }
12651:                 if ($env{'form.saml_text_'.$lonhost} ne $samltext{$lonhost}) {
12652:                     $changes{'saml'}{$lonhost} = 1;
12653:                 }
12654:                 if ($env{'form.saml_url_'.$lonhost} ne $samlurl{$lonhost}) {
12655:                     $changes{'saml'}{$lonhost} = 1;
12656:                 }
12657:                 if ($env{'form.saml_title_'.$lonhost} ne $samltitle{$lonhost}) {
12658:                     $changes{'saml'}{$lonhost} = 1;
12659:                 }
12660:                 if ($env{'form.saml_window_'.$lonhost} ne $samlwindow{$lonhost}) {
12661:                     $changes{'saml'}{$lonhost} = 1;
12662:                 }
12663:                 if ($env{'form.saml_notsso_'.$lonhost} ne $samlnotsso{$lonhost}) {
12664:                     $changes{'saml'}{$lonhost} = 1;
12665:                 }
12666:             } else {
12667:                 $changes{'saml'}{$lonhost} = 1;
12668:             }
12669:             foreach my $item ('text','alt','url','title','window','notsso') {
12670:                 $currsaml{$lonhost}{$item} = $env{'form.saml_'.$item.'_'.$lonhost};
12671:             }
12672:         } else {
12673:             if ($saml{$lonhost}) {  
12674:                 $changes{'saml'}{$lonhost} = 1;
12675:                 delete($currsaml{$lonhost});
12676:             }
12677:         }
12678:     }
12679:     foreach my $posshost (keys(%currsaml)) {
12680:         unless (exists($domservers{$posshost})) { 
12681:             delete($currsaml{$posshost}); 
12682:         }
12683:     }
12684:     %{$loginhash{'login'}{'saml'}} = %currsaml;
12685:     if (@newsamlimgs) {
12686:         my $error;
12687:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
12688:         if ($configuserok eq 'ok') {
12689:             if ($switchserver) {
12690:                 $error = &mt("Upload of SSO Button Image is not permitted to this server: [_1].",$switchserver);
12691:             } elsif ($author_ok eq 'ok') {
12692:                 foreach my $lonhost (@newsamlimgs) {
12693:                     my $formelem = 'saml_img_'.$lonhost;
12694:                     my ($result,$imgurl) = &publishlogo($r,'upload',$formelem,$dom,$confname,
12695:                                                         "login/saml/$lonhost",'','',
12696:                                                         $env{'form.saml_img_'.$lonhost.'.filename'});
12697:                     if ($result eq 'ok') {
12698:                         $currsaml{$lonhost}{'img'} = $imgurl;
12699:                         $loginhash{'login'}{'saml'}{$lonhost}{'img'} = $imgurl;
12700:                         $changes{'saml'}{$lonhost} = 1;
12701:                     } else {
12702:                         my $puberror = &mt("Upload of SSO button image failed for [_1] because an error occurred publishing the file in RES space. Error was: [_2].",
12703:                                            $lonhost,$result);
12704:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
12705:                     }
12706:                 }
12707:             } else {
12708:                 $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);
12709:             }
12710:         } else {
12711:             $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);
12712:         }
12713:         if ($error) {
12714:             &Apache::lonnet::logthis($error);
12715:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12716:         }
12717:     }
12718:     &process_captcha('login',\%changes,$loginhash{'login'},$domconfig{'login'});
12719: 
12720:     my $defaulthelpfile = '/adm/loginproblems.html';
12721:     my $defaulttext = &mt('Default in use');
12722: 
12723:     my $putresult = &Apache::lonnet::put_dom('configuration',\%loginhash,
12724:                                              $dom);
12725:     if ($putresult eq 'ok') {
12726:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
12727:         my %defaultchecked = (
12728:                     'coursecatalog' => 'on',
12729:                     'helpdesk'      => 'on',
12730:                     'adminmail'     => 'off',
12731:                     'newuser'       => 'off',
12732:         );
12733:         if (ref($domconfig{'login'}) eq 'HASH') {
12734:             foreach my $item (@toggles) {
12735:                 if ($defaultchecked{$item} eq 'on') { 
12736:                     if (($domconfig{'login'}{$item} eq '0') &&
12737:                         ($env{'form.'.$item} eq '1')) {
12738:                         $changes{$item} = 1;
12739:                     } elsif (($domconfig{'login'}{$item} eq '' ||
12740:                               $domconfig{'login'}{$item} eq '1') &&
12741:                              ($env{'form.'.$item} eq '0')) {
12742:                         $changes{$item} = 1;
12743:                     }
12744:                 } elsif ($defaultchecked{$item} eq 'off') {
12745:                     if (($domconfig{'login'}{$item} eq '1') &&
12746:                         ($env{'form.'.$item} eq '0')) {
12747:                         $changes{$item} = 1;
12748:                     } elsif (($domconfig{'login'}{$item} eq '' ||
12749:                               $domconfig{'login'}{$item} eq '0') &&
12750:                              ($env{'form.'.$item} eq '1')) {
12751:                         $changes{$item} = 1;
12752:                     }
12753:                 }
12754:             }
12755:         }
12756:         if (keys(%changes) > 0 || $colchgtext) {
12757:             &Apache::loncommon::devalidate_domconfig_cache($dom);
12758:             if (exists($changes{'saml'})) {
12759:                 my $hostid_in_use;
12760:                 my @hosts = &Apache::lonnet::current_machine_ids();
12761:                 if (@hosts > 1) {
12762:                     foreach my $hostid (@hosts) {
12763:                         if (&Apache::lonnet::host_domain($hostid) eq $dom) {
12764:                             $hostid_in_use = $hostid;
12765:                             last;
12766:                         }
12767:                     }
12768:                 } else {
12769:                     $hostid_in_use = $r->dir_config('lonHostID');
12770:                 }
12771:                 if (($hostid_in_use) &&
12772:                     (&Apache::lonnet::host_domain($hostid_in_use) eq $dom)) {
12773:                     &Apache::lonnet::devalidate_cache_new('samllanding',$hostid_in_use);
12774:                 }
12775:                 if (ref($lastactref) eq 'HASH') {
12776:                     if (ref($changes{'saml'}) eq 'HASH') {
12777:                         my %updates;
12778:                         map { $updates{$_} = 1; } keys(%{$changes{'saml'}});
12779:                         $lastactref->{'samllanding'} = \%updates;
12780:                     }
12781:                 }
12782:             }
12783:             if (ref($lastactref) eq 'HASH') {
12784:                 $lastactref->{'domainconfig'} = 1;
12785:             }
12786:             $resulttext = &mt('Changes made:').'<ul>';
12787:             foreach my $item (sort(keys(%changes))) {
12788:                 if ($item eq 'loginvia') {
12789:                     if (ref($changes{$item}) eq 'HASH') {
12790:                         $resulttext .= '<li>'.&mt('Log-in page availability:').'<ul>';
12791:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
12792:                             if (defined($servers{$loginhash{login}{loginvia}{$lonhost}{'server'}})) {
12793:                                 if (ref($loginhash{login}{loginvia}{$lonhost}) eq 'HASH') {
12794:                                     my $protocol = $Apache::lonnet::protocol{$env{'form.'.$lonhost.'_server'}};
12795:                                     $protocol = 'http' if ($protocol ne 'https');
12796:                                     my $target = $protocol.'://'.$servers{$env{'form.'.$lonhost.'_server'}};
12797: 
12798:                                     if ($loginhash{login}{loginvia}{$lonhost}{'serverpath'} eq 'custom') {
12799:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'custompath'};
12800:                                     } else {
12801:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'serverpath'}; 
12802:                                     }
12803:                                     $resulttext .= '<li>'.&mt('Server: [_1] log-in page redirects to [_2].',$servers{$lonhost},'<a href="'.$target.'">'.$target.'</a>');
12804:                                     if ($loginhash{login}{loginvia}{$lonhost}{'exempt'} ne '') {
12805:                                         $resulttext .= '&nbsp;'.&mt('No redirection for clients from following IPs:').'&nbsp;'.$loginhash{login}{loginvia}{$lonhost}{'exempt'};
12806:                                     }
12807:                                     $resulttext .= '</li>';
12808:                                 } else {
12809:                                     $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$lonhost).'</li>';
12810:                                 }
12811:                             } else {
12812:                                 $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$servers{$lonhost}).'</li>';
12813:                             }
12814:                         }
12815:                         $resulttext .= '</ul></li>';
12816:                     }
12817:                 } elsif ($item eq 'helpurl') {
12818:                     if (ref($changes{$item}) eq 'HASH') {
12819:                         foreach my $lang (sort(keys(%{$changes{$item}}))) {
12820:                             if (grep(/^\Q$lang\E$/,@delurls)) {
12821:                                 my ($chg,$link);
12822:                                 $link = &Apache::loncommon::modal_link($defaulthelpfile,$defaulttext,600,500);
12823:                                 if ($lang eq 'nolang') {
12824:                                     $chg = &mt('custom log-in help file removed for no preferred language; [_1]',$link);
12825:                                 } else {
12826:                                     $chg = &mt('custom log-in help file removed for specific language: [_1]; [_2]',$langchoices{$lang},$link);
12827:                                 }
12828:                                 $resulttext .= '<li>'.$chg.'</li>';
12829:                             } else {
12830:                                 my $chg;
12831:                                 if ($lang eq 'nolang') {
12832:                                     $chg = &mt('custom log-in help file for no preferred language');
12833:                                 } else {
12834:                                     $chg = &mt('custom log-in help file for specific language: [_1]',$langchoices{$lang});
12835:                                 }
12836:                                 $resulttext .= '<li>'.&Apache::loncommon::modal_link(
12837:                                                       $loginhash{'login'}{'helpurl'}{$lang}.
12838:                                                       '?inhibitmenu=yes',$chg,600,500).
12839:                                                '</li>';
12840:                             }
12841:                         }
12842:                     }
12843:                 } elsif ($item eq 'headtag') {
12844:                     if (ref($changes{$item}) eq 'HASH') {
12845:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
12846:                             if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
12847:                                 $resulttext .= '<li>'.&mt('custom markup file removed for [_1]',$domservers{$lonhost}).'</li>';
12848:                             } elsif (ref($loginhash{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
12849:                                 $resulttext .= '<li><a href="'.
12850:                                                "javascript:void(open('$loginhash{'login'}{'headtag'}{$lonhost}{'url'}?inhibitmenu=yes','Custom_HeadTag',
12851:                                                'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
12852:                                                '">'.&mt('custom markup').'</a> '.&mt('(for [_1])',$servers{$lonhost}).' ';
12853:                                 if ($possexempt{$lonhost}) {
12854:                                     $resulttext .= &mt('not included for client IP(s): [_1]',$possexempt{$lonhost});
12855:                                 } else {
12856:                                     $resulttext .= &mt('included for any client IP');
12857:                                 }
12858:                                 $resulttext .= '</li>';
12859:                             }
12860:                         }
12861:                     }
12862:                 } elsif ($item eq 'saml') {
12863:                     if (ref($changes{$item}) eq 'HASH') {
12864:                         my %notlt = (
12865:                                        text   => 'Text for log-in by SSO',
12866:                                        img    => 'SSO button image',
12867:                                        alt    => 'Alt text for button image',
12868:                                        url    => 'SSO URL',
12869:                                        title  => 'Tooltip for SSO link',
12870:                                        window => 'Pop-up window if iframe',
12871:                                        notsso => 'Text for non-SSO log-in',
12872:                                     );
12873:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
12874:                             if (ref($currsaml{$lonhost}) eq 'HASH') {
12875:                                 $resulttext .= '<li>'.&mt("$title{$item} in use for [_1]","<b>$lonhost</b>").
12876:                                                '<ul>';
12877:                                 foreach my $key ('text','img','alt','url','title','window','notsso') {
12878:                                     if ($currsaml{$lonhost}{$key} eq '') {
12879:                                         $resulttext .= '<li>'.&mt("$notlt{$key} not in use").'</li>';
12880:                                     } else {
12881:                                         my $value = "'$currsaml{$lonhost}{$key}'";
12882:                                         if ($key eq 'img') {
12883:                                             $value = '<img src="'.$currsaml{$lonhost}{$key}.'" />';
12884:                                         } elsif ($key eq 'window') {
12885:                                             $value = 'On';
12886:                                         }
12887:                                         $resulttext .= '<li>'.&mt("$notlt{$key} set to: [_1]",
12888:                                                                   $value).'</li>';
12889:                                     }
12890:                                 }
12891:                                 $resulttext .= '</ul></li>';
12892:                             } else {
12893:                                 $resulttext .= '<li>'.&mt("$title{$item} not in use for [_1]",$lonhost).'</li>';
12894:                             }
12895:                         }
12896:                     }
12897:                 } elsif ($item eq 'captcha') {
12898:                     if (ref($loginhash{'login'}) eq 'HASH') {
12899:                         my $chgtxt;
12900:                         if ($loginhash{'login'}{$item} eq 'notused') {
12901:                             $chgtxt .= &mt('No CAPTCHA validation in use for helpdesk form.');
12902:                         } else {
12903:                             my %captchas = &captcha_phrases();
12904:                             if ($captchas{$loginhash{'login'}{$item}}) {
12905:                                 $chgtxt .= &mt("Validation for helpdesk form set to $captchas{$loginhash{'login'}{$item}}.");
12906:                             } else {
12907:                                 $chgtxt .= &mt('Validation for helpdesk form set to unknown type.');
12908:                             }
12909:                         }
12910:                         $resulttext .= '<li>'.$chgtxt.'</li>';
12911:                     }
12912:                 } elsif ($item eq 'recaptchakeys') {
12913:                     if (ref($loginhash{'login'}) eq 'HASH') {
12914:                         my ($privkey,$pubkey);
12915:                         if (ref($loginhash{'login'}{$item}) eq 'HASH') {
12916:                             $pubkey = $loginhash{'login'}{$item}{'public'};
12917:                             $privkey = $loginhash{'login'}{$item}{'private'};
12918:                         }
12919:                         my $chgtxt .= &mt('ReCAPTCHA keys changes').'<ul>';
12920:                         if (!$pubkey) {
12921:                             $chgtxt .= '<li>'.&mt('Public key deleted').'</li>';
12922:                         } else {
12923:                             $chgtxt .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
12924:                         }
12925:                         if (!$privkey) {
12926:                             $chgtxt .= '<li>'.&mt('Private key deleted').'</li>';
12927:                         } else {
12928:                             $chgtxt .= '<li>'.&mt('Private key set to [_1]',$privkey).'</li>';
12929:                         }
12930:                         $chgtxt .= '</ul>';
12931:                         $resulttext .= '<li>'.$chgtxt.'</li>';
12932:                     }
12933:                 } elsif ($item eq 'recaptchaversion') {
12934:                     if (ref($loginhash{'login'}) eq 'HASH') {
12935:                         if ($loginhash{'login'}{'captcha'} eq 'recaptcha') {
12936:                             $resulttext .= '<li>'.&mt('ReCAPTCHA for helpdesk form set to version [_1]',$loginhash{'login'}{'recaptchaversion'}).
12937:                                            '</li>';
12938:                         }
12939:                     }
12940:                 } else {
12941:                     $resulttext .= '<li>'.&mt("$title{$item} set to $offon[$env{'form.'.$item}]").'</li>';
12942:                 }
12943:             }
12944:             $resulttext .= $colchgtext.'</ul>';
12945:         } else {
12946:             $resulttext = &mt('No changes made to log-in page settings');
12947:         }
12948:     } else {
12949:         $resulttext = '<span class="LC_error">'.
12950: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
12951:     }
12952:     if ($errors) {
12953:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
12954:                        $errors.'</ul>';
12955:     }
12956:     return $resulttext;
12957: }
12958: 
12959: sub check_exempt_addresses {
12960:     my ($iplist) = @_;
12961:     $iplist =~ s/^\s+//;
12962:     $iplist =~ s/\s+$//;
12963:     my @poss_ips = split(/\s*[,:]\s*/,$iplist);
12964:     my (@okips,$new);
12965:     foreach my $ip (@poss_ips) {
12966:         if ($ip =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) {
12967:             if (($1 <= 255) && ($2 <= 255) && ($3 <= 255) && ($4 <= 255)) {
12968:                 push(@okips,$ip);
12969:             }
12970:         }
12971:     }
12972:     if (@okips > 0) {
12973:         $new = join(',',@okips);
12974:     } else {
12975:         $new = '';
12976:     }
12977:     return $new;
12978: }
12979: 
12980: sub color_font_choices {
12981:     my %choices =
12982:         &Apache::lonlocal::texthash (
12983:             img => "Header",
12984:             bgs => "Background colors",
12985:             links => "Link colors",
12986:             images => "Images",
12987:             font => "Font color",
12988:             fontmenu => "Font menu",
12989:             pgbg => "Page",
12990:             tabbg => "Header",
12991:             sidebg => "Border",
12992:             link => "Link",
12993:             alink => "Active link",
12994:             vlink => "Visited link",
12995:         );
12996:     return %choices;
12997: }
12998: 
12999: sub modify_ipaccess {
13000:     my ($dom,$lastactref,%domconfig) = @_;
13001:     my (@allpos,%changes,%confhash,$errors,$resulttext);
13002:     my (@items,%deletions,%itemids,@warnings);
13003:     my ($typeorder,$types) = &commblocktype_text();
13004:     if ($env{'form.ipaccess_add'}) {
13005:         my $name = $env{'form.ipaccess_name_add'};
13006:         my ($newid,$error) = &get_ipaccess_id($dom,$name);
13007:         if ($newid) {
13008:             $itemids{'add'} = $newid;
13009:             push(@items,'add');
13010:             $changes{$newid} = 1;
13011:         } else {
13012:             $error = &mt('Failed to acquire unique ID for new IP access control item');
13013:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
13014:         }
13015:     }
13016:     if (ref($domconfig{'ipaccess'}) eq 'HASH') {
13017:         my @todelete = &Apache::loncommon::get_env_multiple('form.ipaccess_del');
13018:         if (@todelete) {
13019:             map { $deletions{$_} = 1; } @todelete;
13020:         }
13021:         my $maxnum = $env{'form.ipaccess_maxnum'};
13022:         for (my $i=0; $i<$maxnum; $i++) {
13023:             my $itemid = $env{'form.ipaccess_id_'.$i};
13024:             $itemid =~ s/\D+//g;
13025:             if (ref($domconfig{'ipaccess'}{$itemid}) eq 'HASH') {
13026:                 if ($deletions{$itemid}) {
13027:                     $changes{$itemid} = $domconfig{'ipaccess'}{$itemid}{'name'};
13028:                 } else {
13029:                     push(@items,$i);
13030:                     $itemids{$i} = $itemid;
13031:                 }
13032:             }
13033:         }
13034:     }
13035:     foreach my $idx (@items) {
13036:         my $itemid = $itemids{$idx};
13037:         next unless ($itemid);
13038:         my %current;
13039:         unless ($idx eq 'add') {
13040:             if (ref($domconfig{'ipaccess'}{$itemid}) eq 'HASH') {
13041:                 %current = %{$domconfig{'ipaccess'}{$itemid}};
13042:             }
13043:         }
13044:         my $position = $env{'form.ipaccess_pos_'.$itemid};
13045:         $position =~ s/\D+//g;
13046:         if ($position ne '') {
13047:             $allpos[$position] = $itemid;
13048:         }
13049:         my $name = $env{'form.ipaccess_name_'.$idx};
13050:         $name =~ s/^\s+|\s+$//g;
13051:         $confhash{$itemid}{'name'} = $name;
13052:         my $possrange = $env{'form.ipaccess_range_'.$idx};
13053:         $possrange =~ s/^\s+|\s+$//g;
13054:         unless ($possrange eq '') {
13055:             $possrange =~ s/[\r\n]+/\s/g;
13056:             $possrange =~ s/\s*-\s*/-/g;
13057:             $possrange =~ s/\s+/,/g;
13058:             $possrange =~ s/,+/,/g;
13059:             if ($possrange ne '') {
13060:                 my (@ok,$count);
13061:                 $count = 0; 
13062:                 foreach my $poss (split(/\,/,$possrange)) {
13063:                     $count ++;
13064:                     $poss = &validate_ip_pattern($poss);
13065:                     if ($poss ne '') {
13066:                         push(@ok,$poss);
13067:                     }
13068:                 }
13069:                 my $diff = $count - scalar(@ok);
13070:                 if ($diff) {
13071:                     $errors .= '<li><span class="LC_error">'.
13072:                                &mt('[quant,_1,IP] invalid and excluded from saved value for IP range(s) for [_2]',
13073:                                    $diff,$name).
13074:                                '</span></li>';
13075:                 }
13076:                 if (@ok) {
13077:                     my @cidr_list;
13078:                     foreach my $item (@ok) {
13079:                         @cidr_list = &Net::CIDR::cidradd($item,@cidr_list);
13080:                     }
13081:                     $confhash{$itemid}{'ip'} = join(',',@cidr_list);
13082:                 }
13083:             }
13084:         }
13085:         foreach my $field ('name','ip') {
13086:             unless (($idx eq 'add') || ($changes{$itemid})) {
13087:                 if ($current{$field} ne $confhash{$itemid}{$field}) {
13088:                     $changes{$itemid} = 1;
13089:                     last;
13090:                 }
13091:             }
13092:         }
13093:         $confhash{$itemid}{'commblocks'} = {};
13094:          
13095:         my %commblocks;
13096:         map { $commblocks{$_} = 1; } &Apache::loncommon::get_env_multiple('form.ipaccess_block_'.$idx);  
13097:         foreach my $type (@{$typeorder}) {
13098:             if ($commblocks{$type}) {
13099:                 $confhash{$itemid}{'commblocks'}{$type} = 'on';
13100:             }
13101:             unless (($idx eq 'add') || ($changes{$itemid})) {
13102:                 if (ref($current{'commblocks'}) eq 'HASH') {
13103:                     if ($confhash{$itemid}{'commblocks'}{$type} ne $current{'commblocks'}{$type}) {
13104:                         $changes{$itemid} = 1;
13105:                     }
13106:                 } elsif ($confhash{$itemid}{'commblocks'}{$type}) {
13107:                     $changes{$itemid} = 1;
13108:                 }
13109:             }
13110:         }
13111:         $confhash{$itemid}{'courses'} = {};
13112:         my %crsdeletions;
13113:         my @delcrs = &Apache::loncommon::get_env_multiple('form.ipaccess_course_delete_'.$idx);
13114:         if (@delcrs) {
13115:             map { $crsdeletions{$_} = 1; } @delcrs;
13116:         }
13117:         if (ref($current{'courses'}) eq 'HASH') {
13118:             foreach my $cid (sort(keys(%{$current{'courses'}}))) {
13119:                 if ($crsdeletions{$cid}) {
13120:                     $changes{$itemid} = 1;
13121:                 } else {
13122:                     $confhash{$itemid}{'courses'}{$cid} = 1;
13123:                 }
13124:             }
13125:         }
13126:         $env{'form.ipaccess_cnum_'.$idx} =~ s/^\s+|\s+$//g;
13127:         $env{'form.ipaccess_cdom_'.$idx} =~ s/^\s+|\s+$//g;
13128:         if (($env{'form.ipaccess_cnum_'.$idx} =~ /^$match_courseid$/) && 
13129:             ($env{'form.ipaccess_cdom_'.$idx} =~ /^$match_domain$/)) {
13130:             if (&Apache::lonnet::homeserver($env{'form.ipaccess_cnum_'.$idx},
13131:                                             $env{'form.ipaccess_cdom_'.$idx}) eq 'no_host') {
13132:                 $errors .= '<li><span class="LC_error">'.
13133:                            &mt('Invalid courseID [_1] omitted from list of allowed courses',
13134:                                $env{'form.ipaccess_cdom_'.$idx}.'_'.$env{'form.ipaccess_cnum_'.$idx}).
13135:                            '</span></li>';
13136:             } else {
13137:                 $confhash{$itemid}{'courses'}{$env{'form.ipaccess_cdom_'.$idx}.'_'.$env{'form.ipaccess_cnum_'.$idx}} = 1;
13138:                 $changes{$itemid} = 1;
13139:             }
13140:         }
13141:     }
13142:     if (@allpos > 0) {
13143:         my $idx = 0;
13144:         foreach my $itemid (@allpos) {
13145:             if ($itemid ne '') {
13146:                 $confhash{$itemid}{'order'} = $idx;
13147:                 unless ($changes{$itemid}) {
13148:                     if (ref($domconfig{'ipaccess'}) eq 'HASH') {
13149:                         if (ref($domconfig{'ipaccess'}{$itemid}) eq 'HASH') {
13150:                             if ($domconfig{'ipaccess'}{$itemid}{'order'} ne $idx) {
13151:                                 $changes{$itemid} = 1;
13152:                             }
13153:                         }
13154:                     }
13155:                 }
13156:                 $idx ++;
13157:             }
13158:         }
13159:     }
13160:     if (keys(%changes)) {
13161:         my %defaultshash = (
13162:                               ipaccess => \%confhash,
13163:                            );
13164:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
13165:                                                  $dom);
13166:         if ($putresult eq 'ok') {
13167:             my $cachetime = 1800;
13168:             &Apache::lonnet::do_cache_new('ipaccess',$dom,\%confhash,$cachetime);
13169:             if (ref($lastactref) eq 'HASH') {
13170:                 $lastactref->{'ipaccess'} = 1;
13171:             }
13172:             $resulttext = &mt('Changes made:').'<ul>';
13173:             my %bynum;
13174:             foreach my $itemid (sort(keys(%changes))) {
13175:                 if (ref($confhash{$itemid}) eq 'HASH') {
13176:                     my $position = $confhash{$itemid}{'order'};
13177:                     if ($position =~ /^\d+$/) {
13178:                         $bynum{$position} = $itemid;
13179:                     }
13180:                 }
13181:             }
13182:             if (keys(%deletions)) {
13183:                 foreach my $itemid (sort { $a <=> $b } keys(%deletions)) {
13184:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
13185:                 }
13186:             }
13187:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
13188:                 my $itemid = $bynum{$pos};
13189:                 if (ref($confhash{$itemid}) eq 'HASH') {
13190:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'name'}.'</b><ul>';
13191:                     my $position = $pos + 1;
13192:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
13193:                     if ($confhash{$itemid}{'ip'} eq '') {
13194:                         $resulttext .= '<li>'.&mt('No IP Range(s) set').'</li>';
13195:                     } else {
13196:                         $resulttext .= '<li>'.&mt('IP Range(s): [_1]',$confhash{$itemid}{'ip'}).'</li>';
13197:                     }
13198:                     if (keys(%{$confhash{$itemid}{'commblocks'}})) {
13199:                         $resulttext .= '<li>'.&mt('Functionality Blocked: [_1]',
13200:                                                   join(', ', map { $types->{$_}; } sort(keys(%{$confhash{$itemid}{'commblocks'}})))).
13201:                                        '</li>';
13202:                     } else {
13203:                         $resulttext .= '<li>'.&mt('No functionality blocked').'</li>';
13204:                     }
13205:                     if (keys(%{$confhash{$itemid}{'courses'}})) {
13206:                         my @courses;
13207:                         foreach my $cid (sort(keys(%{$confhash{$itemid}{'courses'}}))) {
13208:                             my %courseinfo = &Apache::lonnet::coursedescription($cid,{'one_time' => 1}); 
13209:                             push(@courses,$courseinfo{'description'}.' ('.$cid.')');
13210:                         }
13211:                         $resulttext .= '<li>'.&mt('Courses/Communities allowed').':<ul><li>'.
13212:                                              join('</li><li>',@courses).'</li></ul>';
13213:                     } else {
13214:                         $resulttext .= '<li>'.&mt('No courses allowed').'</li>';
13215:                     }
13216:                     $resulttext .= '</ul></li>';
13217:                 }
13218:             }
13219:             $resulttext .= '</ul>';
13220:         } else {
13221:             $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
13222:         }
13223:     } else {
13224:         $resulttext = &mt('No changes made');
13225:     }
13226:     if ($errors) {
13227:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
13228:                        $errors.'</ul></p>';
13229:     }
13230:     return $resulttext;
13231: }
13232: 
13233: sub get_ipaccess_id {
13234:     my ($domain,$location) = @_;
13235:     # get lock on ipaccess db
13236:     my $lockhash = {
13237:                       lock => $env{'user.name'}.
13238:                               ':'.$env{'user.domain'},
13239:                    };
13240:     my $tries = 0;
13241:     my $gotlock = &Apache::lonnet::newput_dom('ipaccess',$lockhash,$domain);
13242:     my ($id,$error);
13243: 
13244:     while (($gotlock ne 'ok') && ($tries<10)) {
13245:         $tries ++;
13246:         sleep (0.1);
13247:         $gotlock = &Apache::lonnet::newput_dom('ipaccess',$lockhash,$domain);
13248:     }
13249:     if ($gotlock eq 'ok') {
13250:         my %currids = &Apache::lonnet::dump_dom('ipaccess',$domain);
13251:         if ($currids{'lock'}) {
13252:             delete($currids{'lock'});
13253:             if (keys(%currids)) {
13254:                 my @curr = sort { $a <=> $b } keys(%currids);
13255:                 if ($curr[-1] =~ /^\d+$/) {
13256:                     $id = 1 + $curr[-1];
13257:                 }
13258:             } else {
13259:                 $id = 1;
13260:             }
13261:             if ($id) {
13262:                 unless (&Apache::lonnet::newput_dom('ipaccess',{ $id => $location },$domain) eq 'ok') {
13263:                     $error = 'nostore';
13264:                 }
13265:             } else {
13266:                 $error = 'nonumber';
13267:             }
13268:         }
13269:         my $dellockoutcome = &Apache::lonnet::del_dom('ipaccess',['lock'],$domain);
13270:     } else {
13271:         $error = 'nolock';
13272:     }
13273:     return ($id,$error);
13274: }
13275: 
13276: sub modify_rolecolors {
13277:     my ($r,$dom,$confname,$roles,$lastactref,%domconfig) = @_;
13278:     my ($resulttext,%rolehash);
13279:     $rolehash{'rolecolors'} = {};
13280:     if (ref($domconfig{'rolecolors'}) ne 'HASH') {
13281:         if ($domconfig{'rolecolors'} eq '') {
13282:             $domconfig{'rolecolors'} = {};
13283:         }
13284:     }
13285:     my ($errors,%changes) = &modify_colors($r,$dom,$confname,$roles,
13286:                          $domconfig{'rolecolors'},$rolehash{'rolecolors'});
13287:     my $putresult = &Apache::lonnet::put_dom('configuration',\%rolehash,
13288:                                              $dom);
13289:     if ($putresult eq 'ok') {
13290:         if (keys(%changes) > 0) {
13291:             &Apache::loncommon::devalidate_domconfig_cache($dom);
13292:             if (ref($lastactref) eq 'HASH') {
13293:                 $lastactref->{'domainconfig'} = 1;
13294:             }
13295:             $resulttext = &display_colorchgs($dom,\%changes,$roles,
13296:                                              $rolehash{'rolecolors'});
13297:         } else {
13298:             $resulttext = &mt('No changes made to default color schemes');
13299:         }
13300:     } else {
13301:         $resulttext = '<span class="LC_error">'.
13302: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
13303:     }
13304:     if ($errors) {
13305:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
13306:                        $errors.'</ul>';
13307:     }
13308:     return $resulttext;
13309: }
13310: 
13311: sub modify_colors {
13312:     my ($r,$dom,$confname,$roles,$domconfig,$confhash) = @_;
13313:     my (%changes,%choices);
13314:     my @bgs;
13315:     my @links = ('link','alink','vlink');
13316:     my @logintext;
13317:     my @images;
13318:     my $servadm = $r->dir_config('lonAdmEMail');
13319:     my $errors;
13320:     my %defaults;
13321:     foreach my $role (@{$roles}) {
13322:         if ($role eq 'login') {
13323:             %choices = &login_choices();
13324:             @logintext = ('textcol','bgcol');
13325:         } else {
13326:             %choices = &color_font_choices();
13327:         }
13328:         if ($role eq 'login') {
13329:             @images = ('img','logo','domlogo','login');
13330:             @bgs = ('pgbg','mainbg','sidebg');
13331:         } else {
13332:             @images = ('img');
13333:             @bgs = ('pgbg','tabbg','sidebg');
13334:         }
13335:         my %defaults = &role_defaults($role,\@bgs,\@links,\@images,\@logintext);
13336:         unless ($env{'form.'.$role.'_font'} eq $defaults{'font'}) {
13337:             $confhash->{$role}{'font'} = $env{'form.'.$role.'_font'};
13338:         }
13339:         if ($role eq 'login') {
13340:             foreach my $item (@logintext) {
13341:                 $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
13342:                 if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
13343:                     $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
13344:                 }
13345:                 unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'logintext'}{$item})) {
13346:                     $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
13347:                 }
13348:             }
13349:         } else {
13350:             $env{'form.'.$role.'_fontmenu'} = lc($env{'form.'.$role.'_fontmenu'});
13351:             if ($env{'form.'.$role.'_fontmenu'} =~ /^\w+/) {
13352:                 $env{'form.'.$role.'_fontmenu'} = '#'.$env{'form.'.$role.'_fontmenu'};
13353:             }
13354:             unless($env{'form.'.$role.'_fontmenu'} eq lc($defaults{'fontmenu'})) {
13355:                 $confhash->{$role}{'fontmenu'} = $env{'form.'.$role.'_fontmenu'};
13356:             }
13357:         }
13358:         foreach my $item (@bgs) {
13359:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
13360:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
13361:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
13362:             }
13363:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'bgs'}{$item})) {
13364:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
13365:             }
13366:         }
13367:         foreach my $item (@links) {
13368:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
13369:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
13370:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
13371:             }
13372:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'links'}{$item})) {
13373:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
13374:             }
13375:         }
13376:         my ($configuserok,$author_ok,$switchserver) = 
13377:             &config_check($dom,$confname,$servadm);
13378:         my ($width,$height) = &thumb_dimensions();
13379:         if (ref($domconfig->{$role}) ne 'HASH') {
13380:             $domconfig->{$role} = {};
13381:         }
13382:         foreach my $img (@images) {
13383:             if ($role eq 'login') {
13384:                 if (($img eq 'img') || ($img eq 'logo')) {  
13385:                     if (defined($env{'form.login_showlogo_'.$img})) {
13386:                         $confhash->{$role}{'showlogo'}{$img} = 1;
13387:                     } else { 
13388:                         $confhash->{$role}{'showlogo'}{$img} = 0;
13389:                     }
13390:                 }
13391:                 if ($env{'form.login_alt_'.$img} ne '') {
13392:                     $confhash->{$role}{'alttext'}{$img} = $env{'form.login_alt_'.$img};
13393:                 }
13394:             }
13395: 	    if ( ! $env{'form.'.$role.'_'.$img.'.filename'} 
13396: 		 && !defined($domconfig->{$role}{$img})
13397: 		 && !$env{'form.'.$role.'_del_'.$img}
13398: 		 && $env{'form.'.$role.'_import_'.$img}) {
13399: 		# import the old configured image from the .tab setting
13400: 		# if they haven't provided a new one 
13401: 		$domconfig->{$role}{$img} = 
13402: 		    $env{'form.'.$role.'_import_'.$img};
13403: 	    }
13404:             if ($env{'form.'.$role.'_'.$img.'.filename'} ne '') {
13405:                 my $error;
13406:                 if ($configuserok eq 'ok') {
13407:                     if ($switchserver) {
13408:                         $error = &mt("Upload of [_1] image for $role page(s) is not permitted to this server: [_2]",$choices{$img},$switchserver);
13409:                     } else {
13410:                         if ($author_ok eq 'ok') {
13411:                             my ($result,$logourl) = 
13412:                                 &publishlogo($r,'upload',$role.'_'.$img,
13413:                                            $dom,$confname,$img,$width,$height);
13414:                             if ($result eq 'ok') {
13415:                                 $confhash->{$role}{$img} = $logourl;
13416:                                 $changes{$role}{'images'}{$img} = 1;
13417:                             } else {
13418:                                 $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);
13419:                             }
13420:                         } else {
13421:                             $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);
13422:                         }
13423:                     }
13424:                 } else {
13425:                     $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);
13426:                 }
13427:                 if ($error) {
13428:                     &Apache::lonnet::logthis($error);
13429:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
13430:                 }
13431:             } elsif ($domconfig->{$role}{$img} ne '') {
13432:                 if ($domconfig->{$role}{$img} !~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
13433:                     my $error;
13434:                     if ($configuserok eq 'ok') {
13435: # is confname an author?
13436:                         if ($switchserver eq '') {
13437:                             if ($author_ok eq 'ok') {
13438:                                 my ($result,$logourl) = 
13439:                                &publishlogo($r,'copy',$domconfig->{$role}{$img},
13440:                                             $dom,$confname,$img,$width,$height);
13441:                                 if ($result eq 'ok') {
13442:                                     $confhash->{$role}{$img} = $logourl;
13443: 				    $changes{$role}{'images'}{$img} = 1;
13444:                                 }
13445:                             }
13446:                         }
13447:                     }
13448:                 }
13449:             }
13450:         }
13451:         if (ref($domconfig) eq 'HASH') {
13452:             if (ref($domconfig->{$role}) eq 'HASH') {
13453:                 foreach my $img (@images) {
13454:                     if ($domconfig->{$role}{$img} ne '') {
13455:                         if ($env{'form.'.$role.'_del_'.$img}) {
13456:                             $confhash->{$role}{$img} = '';
13457:                             $changes{$role}{'images'}{$img} = 1;
13458:                         } else {
13459:                             if ($confhash->{$role}{$img} eq '') {
13460:                                 $confhash->{$role}{$img} = $domconfig->{$role}{$img};
13461:                             }
13462:                         }
13463:                     } else {
13464:                         if ($env{'form.'.$role.'_del_'.$img}) {
13465:                             $confhash->{$role}{$img} = '';
13466:                             $changes{$role}{'images'}{$img} = 1;
13467:                         } 
13468:                     }
13469:                     if ($role eq 'login') {
13470:                         if (($img eq 'logo') || ($img eq 'img')) {
13471:                             if (ref($domconfig->{'login'}{'showlogo'}) eq 'HASH') {
13472:                                 if ($confhash->{$role}{'showlogo'}{$img} ne 
13473:                                     $domconfig->{$role}{'showlogo'}{$img}) {
13474:                                     $changes{$role}{'showlogo'}{$img} = 1; 
13475:                                 }
13476:                             } else {
13477:                                 if ($confhash->{$role}{'showlogo'}{$img} == 0) {
13478:                                     $changes{$role}{'showlogo'}{$img} = 1;
13479:                                 }
13480:                             }
13481:                         }
13482:                         if ($img ne 'login') {
13483:                             if (ref($domconfig->{$role}{'alttext'}) eq 'HASH') {
13484:                                 if ($confhash->{$role}{'alttext'}{$img} ne
13485:                                     $domconfig->{$role}{'alttext'}{$img}) {
13486:                                     $changes{$role}{'alttext'}{$img} = 1;
13487:                                 }
13488:                             } else {
13489:                                 if ($confhash->{$role}{'alttext'}{$img} ne '') {
13490:                                     $changes{$role}{'alttext'}{$img} = 1;
13491:                                 }
13492:                             }
13493:                         }
13494:                     }
13495:                 }
13496:                 if ($domconfig->{$role}{'font'} ne '') {
13497:                     if ($confhash->{$role}{'font'} ne $domconfig->{$role}{'font'}) {
13498:                         $changes{$role}{'font'} = 1;
13499:                     }
13500:                 } else {
13501:                     if ($confhash->{$role}{'font'}) {
13502:                         $changes{$role}{'font'} = 1;
13503:                     }
13504:                 }
13505:                 if ($role ne 'login') {
13506:                     if ($domconfig->{$role}{'fontmenu'} ne '') {
13507:                         if ($confhash->{$role}{'fontmenu'} ne $domconfig->{$role}{'fontmenu'}) {
13508:                             $changes{$role}{'fontmenu'} = 1;
13509:                         }
13510:                     } else {
13511:                         if ($confhash->{$role}{'fontmenu'}) {
13512:                             $changes{$role}{'fontmenu'} = 1;
13513:                         }
13514:                     }
13515:                 }
13516:                 foreach my $item (@bgs) {
13517:                     if ($domconfig->{$role}{$item} ne '') {
13518:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
13519:                             $changes{$role}{'bgs'}{$item} = 1;
13520:                         } 
13521:                     } else {
13522:                         if ($confhash->{$role}{$item}) {
13523:                             $changes{$role}{'bgs'}{$item} = 1;
13524:                         }
13525:                     }
13526:                 }
13527:                 foreach my $item (@links) {
13528:                     if ($domconfig->{$role}{$item} ne '') {
13529:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
13530:                             $changes{$role}{'links'}{$item} = 1;
13531:                         }
13532:                     } else {
13533:                         if ($confhash->{$role}{$item}) {
13534:                             $changes{$role}{'links'}{$item} = 1;
13535:                         }
13536:                     }
13537:                 }
13538:                 foreach my $item (@logintext) {
13539:                     if ($domconfig->{$role}{$item} ne '') {
13540:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
13541:                             $changes{$role}{'logintext'}{$item} = 1;
13542:                         }
13543:                     } else {
13544:                         if ($confhash->{$role}{$item}) {
13545:                             $changes{$role}{'logintext'}{$item} = 1;
13546:                         }
13547:                     }
13548:                 }
13549:             } else {
13550:                 &default_change_checker($role,\@images,\@links,\@bgs,
13551:                                         \@logintext,$confhash,\%changes); 
13552:             }
13553:         } else {
13554:             &default_change_checker($role,\@images,\@links,\@bgs,
13555:                                     \@logintext,$confhash,\%changes); 
13556:         }
13557:     }
13558:     return ($errors,%changes);
13559: }
13560: 
13561: sub config_check {
13562:     my ($dom,$confname,$servadm) = @_;
13563:     my ($configuserok,$author_ok,$switchserver,%currroles);
13564:     my $uhome = &Apache::lonnet::homeserver($confname,$dom,1);
13565:     ($configuserok,%currroles) = &check_configuser($uhome,$dom,
13566:                                                    $confname,$servadm);
13567:     if ($configuserok eq 'ok') {
13568:         $switchserver = &check_switchserver($dom,$confname);
13569:         if ($switchserver eq '') {
13570:             $author_ok = &check_authorstatus($dom,$confname,%currroles);
13571:         }
13572:     }
13573:     return ($configuserok,$author_ok,$switchserver);
13574: }
13575: 
13576: sub default_change_checker {
13577:     my ($role,$images,$links,$bgs,$logintext,$confhash,$changes) = @_;
13578:     foreach my $item (@{$links}) {
13579:         if ($confhash->{$role}{$item}) {
13580:             $changes->{$role}{'links'}{$item} = 1;
13581:         }
13582:     }
13583:     foreach my $item (@{$bgs}) {
13584:         if ($confhash->{$role}{$item}) {
13585:             $changes->{$role}{'bgs'}{$item} = 1;
13586:         }
13587:     }
13588:     foreach my $item (@{$logintext}) {
13589:         if ($confhash->{$role}{$item}) {
13590:             $changes->{$role}{'logintext'}{$item} = 1;
13591:         }
13592:     }
13593:     foreach my $img (@{$images}) {
13594:         if ($env{'form.'.$role.'_del_'.$img}) {
13595:             $confhash->{$role}{$img} = '';
13596:             $changes->{$role}{'images'}{$img} = 1;
13597:         }
13598:         if ($role eq 'login') {
13599:             if ($confhash->{$role}{'showlogo'}{$img} == 0) {
13600:                 $changes->{$role}{'showlogo'}{$img} = 1;
13601:             }
13602:             if (ref($confhash->{$role}{'alttext'}) eq 'HASH') {
13603:                 if ($confhash->{$role}{'alttext'}{$img} ne '') {
13604:                     $changes->{$role}{'alttext'}{$img} = 1;
13605:                 }
13606:             }
13607:         }
13608:     }
13609:     if ($confhash->{$role}{'font'}) {
13610:         $changes->{$role}{'font'} = 1;
13611:     }
13612: }
13613: 
13614: sub display_colorchgs {
13615:     my ($dom,$changes,$roles,$confhash) = @_;
13616:     my (%choices,$resulttext);
13617:     if (!grep(/^login$/,@{$roles})) {
13618:         $resulttext = &mt('Changes made:').'<br />';
13619:     }
13620:     foreach my $role (@{$roles}) {
13621:         if ($role eq 'login') {
13622:             %choices = &login_choices();
13623:         } else {
13624:             %choices = &color_font_choices();
13625:         }
13626:         if (ref($changes->{$role}) eq 'HASH') {
13627:             if ($role ne 'login') {
13628:                 $resulttext .= '<h4>'.&mt($role).'</h4>';
13629:             }
13630:             foreach my $key (sort(keys(%{$changes->{$role}}))) {
13631:                 if ($role ne 'login') {
13632:                     $resulttext .= '<ul>';
13633:                 }
13634:                 if (ref($changes->{$role}{$key}) eq 'HASH') {
13635:                     if ($role ne 'login') {
13636:                         $resulttext .= '<li>'.&mt($choices{$key}).':<ul>';
13637:                     }
13638:                     foreach my $item (sort(keys(%{$changes->{$role}{$key}}))) {
13639:                         if (($role eq 'login') && ($key eq 'showlogo')) {
13640:                             if ($confhash->{$role}{$key}{$item}) {
13641:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to be displayed").'</li>';
13642:                             } else {
13643:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to not be displayed").'</li>';
13644:                             }
13645:                         } elsif (($role eq 'login') && ($key eq 'alttext')) {
13646:                             if ($confhash->{$role}{$key}{$item} ne '') {
13647:                                 $resulttext .= '<li>'.&mt("$choices{$key} for $choices{$item} set to [_1].",
13648:                                                $confhash->{$role}{$key}{$item}).'</li>';
13649:                             } else {
13650:                                 $resulttext .= '<li>'.&mt("$choices{$key} for $choices{$item} deleted.").'</li>';
13651:                             }
13652:                         } elsif ($confhash->{$role}{$item} eq '') {
13653:                             $resulttext .= '<li>'.&mt("$choices{$item} set to default").'</li>';
13654:                         } else {
13655:                             my $newitem = $confhash->{$role}{$item};
13656:                             if ($key eq 'images') {
13657:                                 $newitem = '<img src="'.$confhash->{$role}{$item}.'" alt="'.$choices{$item}.'" style="vertical-align: bottom" />';
13658:                             }
13659:                             $resulttext .= '<li>'.&mt("$choices{$item} set to [_1]",$newitem).'</li>';
13660:                         }
13661:                     }
13662:                     if ($role ne 'login') {
13663:                         $resulttext .= '</ul></li>';
13664:                     }
13665:                 } else {
13666:                     if ($confhash->{$role}{$key} eq '') {
13667:                         $resulttext .= '<li>'.&mt("$choices{$key} set to default").'</li>';
13668:                     } else {
13669:                         $resulttext .= '<li>'.&mt("$choices{$key} set to [_1]",$confhash->{$role}{$key}).'</li>';
13670:                     }
13671:                 }
13672:                 if ($role ne 'login') {
13673:                     $resulttext .= '</ul>';
13674:                 }
13675:             }
13676:         }
13677:     }
13678:     return $resulttext;
13679: }
13680: 
13681: sub thumb_dimensions {
13682:     return ('200','50');
13683: }
13684: 
13685: sub check_dimensions {
13686:     my ($inputfile) = @_;
13687:     my ($fullwidth,$fullheight);
13688:     if ($inputfile =~ m|^[/\w.\-]+$|) {
13689:         if (open(PIPE,"identify $inputfile 2>&1 |")) {
13690:             my $imageinfo = <PIPE>;
13691:             if (!close(PIPE)) {
13692:                 &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
13693:             }
13694:             chomp($imageinfo);
13695:             my ($fullsize) = 
13696:                 ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
13697:             if ($fullsize) {
13698:                 ($fullwidth,$fullheight) = split(/x/,$fullsize);
13699:             }
13700:         }
13701:     }
13702:     return ($fullwidth,$fullheight);
13703: }
13704: 
13705: sub check_configuser {
13706:     my ($uhome,$dom,$confname,$servadm) = @_;
13707:     my ($configuserok,%currroles);
13708:     if ($uhome eq 'no_host') {
13709:         srand( time() ^ ($$ + ($$ << 15))  ); # Seed rand.
13710:         my $configpass = &LONCAPA::Enrollment::create_password($dom);
13711:         $configuserok = 
13712:             &Apache::lonnet::modifyuser($dom,$confname,'','internal',
13713:                              $configpass,'','','','','',undef,$servadm);
13714:     } else {
13715:         $configuserok = 'ok';
13716:         %currroles = 
13717:             &Apache::lonnet::get_my_roles($confname,$dom,'userroles');
13718:     }
13719:     return ($configuserok,%currroles);
13720: }
13721: 
13722: sub check_authorstatus {
13723:     my ($dom,$confname,%currroles) = @_;
13724:     my $author_ok;
13725:     if (!$currroles{':'.$dom.':au'}) {
13726:         my $start = time;
13727:         my $end = 0;
13728:         $author_ok = 
13729:             &Apache::lonnet::assignrole($dom,$confname,'/'.$dom.'/',
13730:                                         'au',$end,$start,'','','domconfig');
13731:     } else {
13732:         $author_ok = 'ok';
13733:     }
13734:     return $author_ok;
13735: }
13736: 
13737: sub publishlogo {
13738:     my ($r,$action,$formname,$dom,$confname,$subdir,$thumbwidth,$thumbheight,$savefileas) = @_;
13739:     my ($output,$fname,$logourl,$madethumb);
13740:     if ($action eq 'upload') {
13741:         $fname=$env{'form.'.$formname.'.filename'};
13742:         chop($env{'form.'.$formname});
13743:     } else {
13744:         ($fname) = ($formname =~ /([^\/]+)$/);
13745:     }
13746:     if ($savefileas ne '') {
13747:         $fname = $savefileas;
13748:     }
13749:     $fname=&Apache::lonnet::clean_filename($fname);
13750: # See if there is anything left
13751:     unless ($fname) { return ('error: no uploaded file'); }
13752:     $fname="$subdir/$fname";
13753:     my $docroot=$r->dir_config('lonDocRoot');
13754:     my $filepath="$docroot/priv";
13755:     my $relpath = "$dom/$confname";
13756:     my ($fnamepath,$file,$fetchthumb);
13757:     $file=$fname;
13758:     if ($fname=~m|/|) {
13759:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
13760:     }
13761:     my @parts=split(/\//,"$filepath/$relpath/$fnamepath");
13762:     my $count;
13763:     for ($count=5;$count<=$#parts;$count++) {
13764:         $filepath.="/$parts[$count]";
13765:         if ((-e $filepath)!=1) {
13766:             mkdir($filepath,02770);
13767:         }
13768:     }
13769:     # Check for bad extension and disallow upload
13770:     if ($file=~/\.(\w+)$/ &&
13771:         (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
13772:         $output = 
13773:             &mt('Invalid file extension ([_1]) - reserved for internal use.',$1); 
13774:     } elsif ($file=~/\.(\w+)$/ &&
13775:         !defined(&Apache::loncommon::fileembstyle($1))) {
13776:         $output = &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
13777:     } elsif ($file=~/\.(\d+)\.(\w+)$/) {
13778:         $output = &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
13779:     } elsif (-d "$filepath/$file") {
13780:         $output = &mt('Filename is a directory name - rename the file and re-upload');
13781:     } else {
13782:         my $source = $filepath.'/'.$file;
13783:         my $logfile;
13784:         if (!open($logfile,">>",$source.'.log')) {
13785:             return (&mt('No write permission to Authoring Space'));
13786:         }
13787:         print $logfile
13788: "\n================= Publish ".localtime()." ================\n".
13789: $env{'user.name'}.':'.$env{'user.domain'}."\n";
13790: # Save the file
13791:         if (!open(FH,">",$source)) {
13792:             &Apache::lonnet::logthis('Failed to create '.$source);
13793:             return (&mt('Failed to create file'));
13794:         }
13795:         if ($action eq 'upload') {
13796:             if (!print FH ($env{'form.'.$formname})) {
13797:                 &Apache::lonnet::logthis('Failed to write to '.$source);
13798:                 return (&mt('Failed to write file'));
13799:             }
13800:         } else {
13801:             my $original = &Apache::lonnet::filelocation('',$formname);
13802:             if(!copy($original,$source)) {
13803:                 &Apache::lonnet::logthis('Failed to copy '.$original.' to '.$source);
13804:                 return (&mt('Failed to write file'));
13805:             }
13806:         }
13807:         close(FH);
13808:         chmod(0660, $source); # Permissions to rw-rw---.
13809: 
13810:         my $targetdir=$docroot.'/res/'.$dom.'/'.$confname .'/'.$fnamepath;
13811:         my $copyfile=$targetdir.'/'.$file;
13812: 
13813:         my @parts=split(/\//,$targetdir);
13814:         my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
13815:         for (my $count=5;$count<=$#parts;$count++) {
13816:             $path.="/$parts[$count]";
13817:             if (!-e $path) {
13818:                 print $logfile "\nCreating directory ".$path;
13819:                 mkdir($path,02770);
13820:             }
13821:         }
13822:         my $versionresult;
13823:         if (-e $copyfile) {
13824:             $versionresult = &logo_versioning($targetdir,$file,$logfile);
13825:         } else {
13826:             $versionresult = 'ok';
13827:         }
13828:         if ($versionresult eq 'ok') {
13829:             if (copy($source,$copyfile)) {
13830:                 print $logfile "\nCopied original source to ".$copyfile."\n";
13831:                 $output = 'ok';
13832:                 $logourl = '/res/'.$dom.'/'.$confname.'/'.$fname;
13833:                 push(@{$modified_urls},[$copyfile,$source]);
13834:                 my $metaoutput = 
13835:                     &write_metadata($dom,$confname,$formname,$targetdir,$file,$logfile);
13836:                 unless ($registered_cleanup) {
13837:                     my $handlers = $r->get_handlers('PerlCleanupHandler');
13838:                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
13839:                     $registered_cleanup=1;
13840:                 }
13841:             } else {
13842:                 print $logfile "\nUnable to write ".$copyfile.':'.$!."\n";
13843:                 $output = &mt('Failed to copy file to RES space').", $!";
13844:             }
13845:             if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
13846:                 my $inputfile = $filepath.'/'.$file;
13847:                 my $outfile = $filepath.'/'.'tn-'.$file;
13848:                 my ($fullwidth,$fullheight) = &check_dimensions($inputfile);
13849:                 if ($fullwidth ne '' && $fullheight ne '') { 
13850:                     if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
13851:                         my $thumbsize = $thumbwidth.'x'.$thumbheight;
13852:                         my @args = ('convert','-sample',$thumbsize,$inputfile,$outfile);
13853:                         system({$args[0]} @args);
13854:                         chmod(0660, $filepath.'/tn-'.$file);
13855:                         if (-e $outfile) {
13856:                             my $copyfile=$targetdir.'/tn-'.$file;
13857:                             if (copy($outfile,$copyfile)) {
13858:                                 print $logfile "\nCopied source to ".$copyfile."\n";
13859:                                 my $thumb_metaoutput = 
13860:                                     &write_metadata($dom,$confname,$formname,
13861:                                                     $targetdir,'tn-'.$file,$logfile);
13862:                                 push(@{$modified_urls},[$copyfile,$outfile]);
13863:                                 unless ($registered_cleanup) {
13864:                                     my $handlers = $r->get_handlers('PerlCleanupHandler');
13865:                                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
13866:                                     $registered_cleanup=1;
13867:                                 }
13868:                                 $madethumb = 1;
13869:                             } else {
13870:                                 print $logfile "\nUnable to write ".$copyfile.
13871:                                                ':'.$!."\n";
13872:                             }
13873:                         }
13874:                     }
13875:                 }
13876:             }
13877:         } else {
13878:             $output = $versionresult;
13879:         }
13880:     }
13881:     return ($output,$logourl,$madethumb);
13882: }
13883: 
13884: sub logo_versioning {
13885:     my ($targetdir,$file,$logfile) = @_;
13886:     my $target = $targetdir.'/'.$file;
13887:     my ($maxversion,$fn,$extn,$output);
13888:     $maxversion = 0;
13889:     if ($file =~ /^(.+)\.(\w+)$/) {
13890:         $fn=$1;
13891:         $extn=$2;
13892:     }
13893:     opendir(DIR,$targetdir);
13894:     while (my $filename=readdir(DIR)) {
13895:         if ($filename=~/\Q$fn\E\.(\d+)\.\Q$extn\E$/) {
13896:             $maxversion=($1>$maxversion)?$1:$maxversion;
13897:         }
13898:     }
13899:     $maxversion++;
13900:     print $logfile "\nCreating old version ".$maxversion."\n";
13901:     my $copyfile=$targetdir.'/'.$fn.'.'.$maxversion.'.'.$extn;
13902:     if (copy($target,$copyfile)) {
13903:         print $logfile "Copied old target to ".$copyfile."\n";
13904:         $copyfile=$copyfile.'.meta';
13905:         if (copy($target.'.meta',$copyfile)) {
13906:             print $logfile "Copied old target metadata to ".$copyfile."\n";
13907:             $output = 'ok';
13908:         } else {
13909:             print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
13910:             $output = &mt('Failed to copy old meta').", $!, ";
13911:         }
13912:     } else {
13913:         print $logfile "Unable to write ".$copyfile.':'.$!."\n";
13914:         $output = &mt('Failed to copy old target').", $!, ";
13915:     }
13916:     return $output;
13917: }
13918: 
13919: sub write_metadata {
13920:     my ($dom,$confname,$formname,$targetdir,$file,$logfile) = @_;
13921:     my (%metadatafields,%metadatakeys,$output);
13922:     $metadatafields{'title'}=$formname;
13923:     $metadatafields{'creationdate'}=time;
13924:     $metadatafields{'lastrevisiondate'}=time;
13925:     $metadatafields{'copyright'}='public';
13926:     $metadatafields{'modifyinguser'}=$env{'user.name'}.':'.
13927:                                          $env{'user.domain'};
13928:     $metadatafields{'authorspace'}=$confname.':'.$dom;
13929:     $metadatafields{'domain'}=$dom;
13930:     {
13931:         print $logfile "\nWrite metadata file for ".$targetdir.'/'.$file;
13932:         my $mfh;
13933:         if (open($mfh,">",$targetdir.'/'.$file.'.meta')) {
13934:             foreach (sort(keys(%metadatafields))) {
13935:                 unless ($_=~/\./) {
13936:                     my $unikey=$_;
13937:                     $unikey=~/^([A-Za-z]+)/;
13938:                     my $tag=$1;
13939:                     $tag=~tr/A-Z/a-z/;
13940:                     print $mfh "\n\<$tag";
13941:                     foreach (split(/\,/,$metadatakeys{$unikey})) {
13942:                         my $value=$metadatafields{$unikey.'.'.$_};
13943:                         $value=~s/\"/\'\'/g;
13944:                         print $mfh ' '.$_.'="'.$value.'"';
13945:                     }
13946:                     print $mfh '>'.
13947:                         &HTML::Entities::encode($metadatafields{$unikey},'<>&"')
13948:                             .'</'.$tag.'>';
13949:                 }
13950:             }
13951:             $output = 'ok';
13952:             print $logfile "\nWrote metadata";
13953:             close($mfh);
13954:         } else {
13955:             print $logfile "\nFailed to open metadata file";
13956:             $output = &mt('Could not write metadata');
13957:         }
13958:     }
13959:     return $output;
13960: }
13961: 
13962: sub notifysubscribed {
13963:     foreach my $targetsource (@{$modified_urls}){
13964:         next unless (ref($targetsource) eq 'ARRAY');
13965:         my ($target,$source)=@{$targetsource};
13966:         if ($source ne '') {
13967:             if (open(my $logfh,">>",$source.'.log')) {
13968:                 print $logfh "\nCleanup phase: Notifications\n";
13969:                 my @subscribed=&subscribed_hosts($target);
13970:                 foreach my $subhost (@subscribed) {
13971:                     print $logfh "\nNotifying host ".$subhost.':';
13972:                     my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
13973:                     print $logfh $reply;
13974:                 }
13975:                 my @subscribedmeta=&subscribed_hosts("$target.meta");
13976:                 foreach my $subhost (@subscribedmeta) {
13977:                     print $logfh "\nNotifying host for metadata only ".$subhost.':';
13978:                     my $reply=&Apache::lonnet::critical('update:'.$target.'.meta',
13979:                                                         $subhost);
13980:                     print $logfh $reply;
13981:                 }
13982:                 print $logfh "\n============ Done ============\n";
13983:                 close($logfh);
13984:             }
13985:         }
13986:     }
13987:     return OK;
13988: }
13989: 
13990: sub subscribed_hosts {
13991:     my ($target) = @_;
13992:     my @subscribed;
13993:     if (open(my $fh,"<","$target.subscription")) {
13994:         while (my $subline=<$fh>) {
13995:             if ($subline =~ /^($match_lonid):/) {
13996:                 my $host = $1;
13997:                 if ($host ne $Apache::lonnet::perlvar{'lonHostID'}) {
13998:                     unless (grep(/^\Q$host\E$/,@subscribed)) {
13999:                         push(@subscribed,$host);
14000:                     }
14001:                 }
14002:             }
14003:         }
14004:     }
14005:     return @subscribed;
14006: }
14007: 
14008: sub check_switchserver {
14009:     my ($dom,$confname) = @_;
14010:     my ($allowed,$switchserver);
14011:     my $home = &Apache::lonnet::homeserver($confname,$dom);
14012:     if ($home eq 'no_host') {
14013:         $home = &Apache::lonnet::domain($dom,'primary');
14014:     }
14015:     my @ids=&Apache::lonnet::current_machine_ids();
14016:     foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
14017:     if (!$allowed) {
14018: 	$switchserver='<a href="/adm/switchserver?otherserver='.$home.'&amp;role=dc./'.$dom.'/&amp;destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
14019:     }
14020:     return $switchserver;
14021: }
14022: 
14023: sub modify_quotas {
14024:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
14025:     my ($context,@usertools,@options,%validations,%titles,%confhash,%toolshash,
14026:         %limithash,$toolregexp,%conditions,$resulttext,%changes,$confname,$configuserok,
14027:         $author_ok,$switchserver,$errors,$validationitemsref,$validationnamesref,
14028:         $validationfieldsref);
14029:     if ($action eq 'quotas') {
14030:         $context = 'tools'; 
14031:     } else {
14032:         $context = $action;
14033:     }
14034:     if ($context eq 'requestcourses') {
14035:         @usertools = ('official','unofficial','community','textbook','placement','lti');
14036:         @options =('norequest','approval','validate','autolimit');
14037:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
14038:         %titles = &courserequest_titles();
14039:         $toolregexp = join('|',@usertools);
14040:         %conditions = &courserequest_conditions();
14041:         $confname = $dom.'-domainconfig';
14042:         my $servadm = $r->dir_config('lonAdmEMail');
14043:         ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
14044:         ($validationitemsref,$validationnamesref,$validationfieldsref) = 
14045:             &Apache::loncoursequeueadmin::requestcourses_validation_types();
14046:     } elsif ($context eq 'requestauthor') {
14047:         @usertools = ('author');
14048:         %titles = &authorrequest_titles();
14049:     } else {
14050:         @usertools = ('aboutme','blog','webdav','portfolio','timezone');
14051:         %titles = &tool_titles();
14052:     }
14053:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
14054:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
14055:     foreach my $key (keys(%env)) {
14056:         if ($context eq 'requestcourses') {
14057:             if ($key =~ /^form\.crsreq_($toolregexp)_(.+)$/) {
14058:                 my $item = $1;
14059:                 my $type = $2;
14060:                 if ($type =~ /^limit_(.+)/) {
14061:                     $limithash{$item}{$1} = $env{$key};
14062:                 } else {
14063:                     $confhash{$item}{$type} = $env{$key};
14064:                 }
14065:             }
14066:         } elsif ($context eq 'requestauthor') {
14067:             if ($key =~ /^\Qform.authorreq_\E(.+)$/) {
14068:                 $confhash{$1} = $env{$key};
14069:             }
14070:         } else {
14071:             if ($key =~ /^form\.quota_(.+)$/) {
14072:                 $confhash{'defaultquota'}{$1} = $env{$key};
14073:             } elsif ($key =~ /^form\.authorquota_(.+)$/) {
14074:                 $confhash{'authorquota'}{$1} = $env{$key};
14075:             } elsif ($key =~ /^form\.\Q$context\E_(.+)$/) {
14076:                 @{$toolshash{$1}} = &Apache::loncommon::get_env_multiple($key);
14077:             }
14078:         }
14079:     }
14080:     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
14081:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.'.$context.'notifyapproval');
14082:         @approvalnotify = sort(@approvalnotify);
14083:         $confhash{'notify'}{'approval'} = join(',',@approvalnotify);
14084:         my @crstypes = ('official','unofficial','community','textbook','placement','lti');
14085:         my @hasuniquecode = &Apache::loncommon::get_env_multiple('form.uniquecode');
14086:         foreach my $type (@hasuniquecode) {
14087:             if (grep(/^\Q$type\E$/,@crstypes)) {
14088:                 $confhash{'uniquecode'}{$type} = 1;
14089:             }
14090:         }
14091:         my (%newbook,%allpos);
14092:         if ($context eq 'requestcourses') {
14093:             foreach my $type ('textbooks','templates') {
14094:                 @{$allpos{$type}} = (); 
14095:                 my $invalid;
14096:                 if ($type eq 'textbooks') {
14097:                     $invalid = &mt('Invalid LON-CAPA course for textbook');
14098:                 } else {
14099:                     $invalid = &mt('Invalid LON-CAPA course for template');
14100:                 }
14101:                 if ($env{'form.'.$type.'_addbook'}) {
14102:                     if (($env{'form.'.$type.'_addbook_cnum'} =~ /^$match_courseid$/) &&
14103:                         ($env{'form.'.$type.'_addbook_cdom'} =~ /^$match_domain$/)) {
14104:                         if (&Apache::lonnet::homeserver($env{'form.'.$type.'_addbook_cnum'},
14105:                                                         $env{'form.'.$type.'_addbook_cdom'}) eq 'no_host') {
14106:                             $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
14107:                         } else {
14108:                             $newbook{$type} = $env{'form.'.$type.'_addbook_cdom'}.'_'.$env{'form.'.$type.'_addbook_cnum'};
14109:                             my $position = $env{'form.'.$type.'_addbook_pos'};
14110:                             $position =~ s/\D+//g;
14111:                             if ($position ne '') {
14112:                                 $allpos{$type}[$position] = $newbook{$type};
14113:                             }
14114:                         }
14115:                     } else {
14116:                         $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
14117:                     }
14118:                 }
14119:             } 
14120:         }
14121:         if (ref($domconfig{$action}) eq 'HASH') {
14122:             if (ref($domconfig{$action}{'notify'}) eq 'HASH') {
14123:                 if ($domconfig{$action}{'notify'}{'approval'} ne $confhash{'notify'}{'approval'}) {
14124:                     $changes{'notify'}{'approval'} = 1;
14125:                 }
14126:             } else {
14127:                 if ($confhash{'notify'}{'approval'}) {
14128:                     $changes{'notify'}{'approval'} = 1;
14129:                 }
14130:             }
14131:             if (ref($domconfig{$action}{'uniquecode'}) eq 'HASH') {
14132:                 if (ref($confhash{'uniquecode'}) eq 'HASH') {
14133:                     foreach my $crstype (keys(%{$domconfig{$action}{'uniquecode'}})) {
14134:                         unless ($confhash{'uniquecode'}{$crstype}) {
14135:                             $changes{'uniquecode'} = 1;
14136:                         }
14137:                     }
14138:                     unless ($changes{'uniquecode'}) {
14139:                         foreach my $crstype (keys(%{$confhash{'uniquecode'}})) {
14140:                             unless ($domconfig{$action}{'uniquecode'}{$crstype}) {
14141:                                 $changes{'uniquecode'} = 1;
14142:                             }
14143:                         }
14144:                     }
14145:                } else {
14146:                    $changes{'uniquecode'} = 1;
14147:                }
14148:             } elsif (ref($confhash{'uniquecode'}) eq 'HASH') {
14149:                 $changes{'uniquecode'} = 1;
14150:             }
14151:             if ($context eq 'requestcourses') {
14152:                 foreach my $type ('textbooks','templates') {
14153:                     if (ref($domconfig{$action}{$type}) eq 'HASH') {
14154:                         my %deletions;
14155:                         my @todelete = &Apache::loncommon::get_env_multiple('form.'.$type.'_del');
14156:                         if (@todelete) {
14157:                             map { $deletions{$_} = 1; } @todelete;
14158:                         }
14159:                         my %imgdeletions;
14160:                         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.'.$type.'_image_del');
14161:                         if (@todeleteimages) {
14162:                             map { $imgdeletions{$_} = 1; } @todeleteimages;
14163:                         }
14164:                         my $maxnum = $env{'form.'.$type.'_maxnum'};
14165:                         for (my $i=0; $i<=$maxnum; $i++) {
14166:                             my $itemid = $env{'form.'.$type.'_id_'.$i};
14167:                             my ($key) = ($itemid =~ /^\Q$type\E_(\w+)$/); 
14168:                             if (ref($domconfig{$action}{$type}{$key}) eq 'HASH') {
14169:                                 if ($deletions{$key}) {
14170:                                     if ($domconfig{$action}{$type}{$key}{'image'}) {
14171:                                         #FIXME need to obsolete item in RES space
14172:                                     }
14173:                                     next;
14174:                                 } else {
14175:                                     my $newpos = $env{'form.'.$itemid};
14176:                                     $newpos =~ s/\D+//g;
14177:                                     foreach my $item ('subject','title','publisher','author') {
14178:                                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
14179:                                                  ($type eq 'templates'));
14180:                                         $confhash{$type}{$key}{$item} = $env{'form.'.$type.'_'.$item.'_'.$i};
14181:                                         if ($domconfig{$action}{$type}{$key}{$item} ne $confhash{$type}{$key}{$item}) {
14182:                                             $changes{$type}{$key} = 1;
14183:                                         }
14184:                                     }
14185:                                     $allpos{$type}[$newpos] = $key;
14186:                                 }
14187:                                 if ($imgdeletions{$key}) {
14188:                                     $changes{$type}{$key} = 1;
14189:                                     #FIXME need to obsolete item in RES space
14190:                                 } elsif ($env{'form.'.$type.'_image_'.$i.'.filename'}) {
14191:                                     my ($cdom,$cnum) = split(/_/,$key);
14192:                                     if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
14193:                                         $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
14194:                                     } else {
14195:                                         my ($imgurl,$error) = &process_textbook_image($r,$dom,$confname,$type.'_image_'.$i,
14196:                                                                                       $cdom,$cnum,$type,$configuserok,
14197:                                                                                       $switchserver,$author_ok);
14198:                                         if ($imgurl) {
14199:                                             $confhash{$type}{$key}{'image'} = $imgurl;
14200:                                             $changes{$type}{$key} = 1; 
14201:                                         }
14202:                                         if ($error) {
14203:                                             &Apache::lonnet::logthis($error);
14204:                                             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
14205:                                         }
14206:                                     }
14207:                                 } elsif ($domconfig{$action}{$type}{$key}{'image'}) {
14208:                                     $confhash{$type}{$key}{'image'} = 
14209:                                         $domconfig{$action}{$type}{$key}{'image'};
14210:                                 }
14211:                             }
14212:                         }
14213:                     }
14214:                 }
14215:             }
14216:         } else {
14217:             if ($confhash{'notify'}{'approval'}) {
14218:                 $changes{'notify'}{'approval'} = 1;
14219:             }
14220:             if (ref($confhash{'uniquecode'} eq 'HASH')) {
14221:                 $changes{'uniquecode'} = 1;
14222:             }
14223:         }
14224:         if ($context eq 'requestcourses') {
14225:             foreach my $type ('textbooks','templates') {
14226:                 if ($newbook{$type}) {
14227:                     $changes{$type}{$newbook{$type}} = 1;
14228:                     foreach my $item ('subject','title','publisher','author') {
14229:                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
14230:                                  ($type eq 'template'));
14231:                         $env{'form.'.$type.'_addbook_'.$item} =~ s/(`)/'/g;
14232:                         if ($env{'form.'.$type.'_addbook_'.$item}) {
14233:                             $confhash{$type}{$newbook{$type}}{$item} = $env{'form.'.$type.'_addbook_'.$item};
14234:                         }
14235:                     }
14236:                     if ($type eq 'textbooks') {
14237:                         if ($env{'form.'.$type.'_addbook_image.filename'} ne '') {
14238:                             my ($cdom,$cnum) = split(/_/,$newbook{$type});
14239:                             if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
14240:                                 $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
14241:                             } else {
14242:                                 my ($imageurl,$error) =
14243:                                     &process_textbook_image($r,$dom,$confname,$type.'_addbook_image',$cdom,$cnum,$type,
14244:                                                             $configuserok,$switchserver,$author_ok);
14245:                                 if ($imageurl) {
14246:                                     $confhash{$type}{$newbook{$type}}{'image'} = $imageurl;
14247:                                 }
14248:                                 if ($error) {
14249:                                     &Apache::lonnet::logthis($error);
14250:                                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
14251:                                 }
14252:                             }
14253:                         }
14254:                     }
14255:                 }
14256:                 if (@{$allpos{$type}} > 0) {
14257:                     my $idx = 0;
14258:                     foreach my $item (@{$allpos{$type}}) {
14259:                         if ($item ne '') {
14260:                             $confhash{$type}{$item}{'order'} = $idx;
14261:                             if (ref($domconfig{$action}) eq 'HASH') {
14262:                                 if (ref($domconfig{$action}{$type}) eq 'HASH') {
14263:                                     if (ref($domconfig{$action}{$type}{$item}) eq 'HASH') {
14264:                                         if ($domconfig{$action}{$type}{$item}{'order'} ne $idx) {
14265:                                             $changes{$type}{$item} = 1;
14266:                                         }
14267:                                     }
14268:                                 }
14269:                             }
14270:                             $idx ++;
14271:                         }
14272:                     }
14273:                 }
14274:             }
14275:             if (ref($validationitemsref) eq 'ARRAY') {
14276:                 foreach my $item (@{$validationitemsref}) {
14277:                     if ($item eq 'fields') {
14278:                         my @changed;
14279:                         @{$confhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.requestcourses_validation_'.$item);
14280:                         if (@{$confhash{'validation'}{$item}} > 0) {
14281:                             @{$confhash{'validation'}{$item}} = sort(@{$confhash{'validation'}{$item}});
14282:                         }
14283:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
14284:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
14285:                                 if (ref($domconfig{'requestcourses'}{'validation'}{$item}) eq 'ARRAY') {
14286:                                     @changed = &Apache::loncommon::compare_arrays($confhash{'validation'}{$item},
14287:                                                                                   $domconfig{'requestcourses'}{'validation'}{$item});
14288:                                 } else {
14289:                                     @changed = @{$confhash{'validation'}{$item}};
14290:                                 }
14291:                             } else {
14292:                                 @changed = @{$confhash{'validation'}{$item}};
14293:                             }
14294:                         } else {
14295:                             @changed = @{$confhash{'validation'}{$item}};
14296:                         }
14297:                         if (@changed) {
14298:                             if ($confhash{'validation'}{$item}) {
14299:                                 $changes{'validation'}{$item} = join(', ',@{$confhash{'validation'}{$item}});
14300:                             } else {
14301:                                 $changes{'validation'}{$item} = &mt('None');
14302:                             }
14303:                         }
14304:                     } else {
14305:                         $confhash{'validation'}{$item} = $env{'form.requestcourses_validation_'.$item};
14306:                         if ($item eq 'markup') {
14307:                             if ($env{'form.requestcourses_validation_'.$item}) {
14308:                                 $env{'form.requestcourses_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
14309:                             }
14310:                         }
14311:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
14312:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
14313:                                 if ($domconfig{'requestcourses'}{'validation'}{$item} ne $confhash{'validation'}{$item}) {
14314:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
14315:                                 }
14316:                             } else {
14317:                                 if ($confhash{'validation'}{$item} ne '') {
14318:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
14319:                                 }
14320:                             }
14321:                         } else {
14322:                             if ($confhash{'validation'}{$item} ne '') {
14323:                                 $changes{'validation'}{$item} = $confhash{'validation'}{$item};
14324:                             }
14325:                         }
14326:                     }
14327:                 }
14328:             }
14329:             if ($env{'form.validationdc'}) {
14330:                 my $newval = $env{'form.validationdc'};
14331:                 my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
14332:                 if (exists($domcoords{$newval})) {
14333:                     $confhash{'validation'}{'dc'} = $newval;
14334:                 }
14335:             }
14336:             if (ref($confhash{'validation'}) eq 'HASH') {
14337:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
14338:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
14339:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
14340:                             unless ($confhash{'validation'}{'dc'} eq $domconfig{'requestcourses'}{'validation'}{'dc'}) {
14341:                                 if ($confhash{'validation'}{'dc'} eq '') {
14342:                                     $changes{'validation'}{'dc'} = &mt('None');
14343:                                 } else {
14344:                                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
14345:                                 }
14346:                             }
14347:                         } elsif ($confhash{'validation'}{'dc'} ne '') {
14348:                             $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
14349:                         }
14350:                     } elsif ($confhash{'validation'}{'dc'} ne '') {
14351:                         $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
14352:                     }
14353:                 } elsif ($confhash{'validation'}{'dc'} ne '') {
14354:                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
14355:                 }
14356:             } else {
14357:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
14358:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
14359:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
14360:                             $changes{'validation'}{'dc'} = &mt('None');
14361:                         }
14362:                     }
14363:                 }
14364:             }
14365:         }
14366:     } else {
14367:         $confhash{'defaultquota'}{'default'} = $env{'form.defaultquota'};
14368:         $confhash{'authorquota'}{'default'} = $env{'form.authorquota'};
14369:     }
14370:     foreach my $item (@usertools) {
14371:         foreach my $type (@{$types},'default','_LC_adv') {
14372:             my $unset; 
14373:             if ($context eq 'requestcourses') {
14374:                 $unset = '0';
14375:                 if ($type eq '_LC_adv') {
14376:                     $unset = '';
14377:                 }
14378:                 if ($confhash{$item}{$type} eq 'autolimit') {
14379:                     $confhash{$item}{$type} .= '=';
14380:                     unless ($limithash{$item}{$type} =~ /\D/) {
14381:                         $confhash{$item}{$type} .= $limithash{$item}{$type};
14382:                     }
14383:                 }
14384:             } elsif ($context eq 'requestauthor') {
14385:                 $unset = '0';
14386:                 if ($type eq '_LC_adv') {
14387:                     $unset = '';
14388:                 }
14389:             } else {
14390:                 if (grep(/^\Q$type\E$/,@{$toolshash{$item}})) {
14391:                     $confhash{$item}{$type} = 1;
14392:                 } else {
14393:                     $confhash{$item}{$type} = 0;
14394:                 }
14395:             }
14396:             if (ref($domconfig{$action}) eq 'HASH') {
14397:                 if ($action eq 'requestauthor') {
14398:                     if ($domconfig{$action}{$type} ne $confhash{$type}) {
14399:                         $changes{$type} = 1;
14400:                     }
14401:                 } elsif (ref($domconfig{$action}{$item}) eq 'HASH') {
14402:                     if ($domconfig{$action}{$item}{$type} ne $confhash{$item}{$type}) {
14403:                         $changes{$item}{$type} = 1;
14404:                     }
14405:                 } else {
14406:                     if ($context eq 'requestcourses') {
14407:                         if ($confhash{$item}{$type} ne $unset) {
14408:                             $changes{$item}{$type} = 1;
14409:                         }
14410:                     } else {
14411:                         if (!$confhash{$item}{$type}) {
14412:                             $changes{$item}{$type} = 1;
14413:                         }
14414:                     }
14415:                 }
14416:             } else {
14417:                 if ($context eq 'requestcourses') {
14418:                     if ($confhash{$item}{$type} ne $unset) {
14419:                         $changes{$item}{$type} = 1;
14420:                     }
14421:                 } elsif ($context eq 'requestauthor') {
14422:                     if ($confhash{$type} ne $unset) {
14423:                         $changes{$type} = 1;
14424:                     }
14425:                 } else {
14426:                     if (!$confhash{$item}{$type}) {
14427:                         $changes{$item}{$type} = 1;
14428:                     }
14429:                 }
14430:             }
14431:         }
14432:     }
14433:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
14434:         if (ref($domconfig{'quotas'}) eq 'HASH') {
14435:             if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
14436:                 foreach my $key (keys(%{$domconfig{'quotas'}{'defaultquota'}})) {
14437:                     if (exists($confhash{'defaultquota'}{$key})) {
14438:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{'defaultquota'}{$key}) {
14439:                             $changes{'defaultquota'}{$key} = 1;
14440:                         }
14441:                     } else {
14442:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{'defaultquota'}{$key};
14443:                     }
14444:                 }
14445:             } else {
14446:                 foreach my $key (keys(%{$domconfig{'quotas'}})) {
14447:                     if (exists($confhash{'defaultquota'}{$key})) {
14448:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{$key}) {
14449:                             $changes{'defaultquota'}{$key} = 1;
14450:                         }
14451:                     } else {
14452:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{$key};
14453:                     }
14454:                 }
14455:             }
14456:             if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
14457:                 foreach my $key (keys(%{$domconfig{'quotas'}{'authorquota'}})) {
14458:                     if (exists($confhash{'authorquota'}{$key})) {
14459:                         if ($confhash{'authorquota'}{$key} ne $domconfig{'quotas'}{'authorquota'}{$key}) {
14460:                             $changes{'authorquota'}{$key} = 1;
14461:                         }
14462:                     } else {
14463:                         $confhash{'authorquota'}{$key} = $domconfig{'quotas'}{'authorquota'}{$key};
14464:                     }
14465:                 }
14466:             }
14467:         }
14468:         if (ref($confhash{'defaultquota'}) eq 'HASH') {
14469:             foreach my $key (keys(%{$confhash{'defaultquota'}})) {
14470:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
14471:                     if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
14472:                         if (!exists($domconfig{'quotas'}{'defaultquota'}{$key})) {
14473:                             $changes{'defaultquota'}{$key} = 1;
14474:                         }
14475:                     } else {
14476:                         if (!exists($domconfig{'quotas'}{$key})) {
14477:                             $changes{'defaultquota'}{$key} = 1;
14478:                         }
14479:                     }
14480:                 } else {
14481:                     $changes{'defaultquota'}{$key} = 1;
14482:                 }
14483:             }
14484:         }
14485:         if (ref($confhash{'authorquota'}) eq 'HASH') {
14486:             foreach my $key (keys(%{$confhash{'authorquota'}})) {
14487:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
14488:                     if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
14489:                         if (!exists($domconfig{'quotas'}{'authorquota'}{$key})) {
14490:                             $changes{'authorquota'}{$key} = 1;
14491:                         }
14492:                     } else {
14493:                         $changes{'authorquota'}{$key} = 1;
14494:                     }
14495:                 } else {
14496:                     $changes{'authorquota'}{$key} = 1;
14497:                 }
14498:             }
14499:         }
14500:     }
14501: 
14502:     if ($context eq 'requestauthor') {
14503:         $domdefaults{'requestauthor'} = \%confhash;
14504:     } else {
14505:         foreach my $key (keys(%confhash)) {
14506:             unless (($context eq 'requestcourses') && (($key eq 'textbooks') || ($key eq 'templates'))) {
14507:                 $domdefaults{$key} = $confhash{$key};
14508:             }
14509:         }
14510:     }
14511: 
14512:     my %quotahash = (
14513:                       $action => { %confhash }
14514:                     );
14515:     my $putresult = &Apache::lonnet::put_dom('configuration',\%quotahash,
14516:                                              $dom);
14517:     if ($putresult eq 'ok') {
14518:         if (keys(%changes) > 0) {
14519:             my $cachetime = 24*60*60;
14520:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
14521:             if (ref($lastactref) eq 'HASH') {
14522:                 $lastactref->{'domdefaults'} = 1;
14523:             }
14524:             $resulttext = &mt('Changes made:').'<ul>';
14525:             unless (($context eq 'requestcourses') ||
14526:                     ($context eq 'requestauthor')) {
14527:                 if (ref($changes{'defaultquota'}) eq 'HASH') {
14528:                     $resulttext .= '<li>'.&mt('Portfolio default quotas').'<ul>';
14529:                     foreach my $type (@{$types},'default') {
14530:                         if (defined($changes{'defaultquota'}{$type})) {
14531:                             my $typetitle = $usertypes->{$type};
14532:                             if ($type eq 'default') {
14533:                                 $typetitle = $othertitle;
14534:                             }
14535:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'defaultquota'}{$type}).'</li>';
14536:                         }
14537:                     }
14538:                     $resulttext .= '</ul></li>';
14539:                 }
14540:                 if (ref($changes{'authorquota'}) eq 'HASH') {
14541:                     $resulttext .= '<li>'.&mt('Authoring Space default quotas').'<ul>';
14542:                     foreach my $type (@{$types},'default') {
14543:                         if (defined($changes{'authorquota'}{$type})) {
14544:                             my $typetitle = $usertypes->{$type};
14545:                             if ($type eq 'default') {
14546:                                 $typetitle = $othertitle;
14547:                             }
14548:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'authorquota'}{$type}).'</li>';
14549:                         }
14550:                     }
14551:                     $resulttext .= '</ul></li>';
14552:                 }
14553:             }
14554:             my %newenv;
14555:             foreach my $item (@usertools) {
14556:                 my (%haschgs,%inconf);
14557:                 if ($context eq 'requestauthor') {
14558:                     %haschgs = %changes;
14559:                     %inconf = %confhash;
14560:                 } else {
14561:                     if (ref($changes{$item}) eq 'HASH') {
14562:                         %haschgs = %{$changes{$item}};
14563:                     }
14564:                     if (ref($confhash{$item}) eq 'HASH') {
14565:                         %inconf = %{$confhash{$item}};
14566:                     }
14567:                 }
14568:                 if (keys(%haschgs) > 0) {
14569:                     my $newacc = 
14570:                         &Apache::lonnet::usertools_access($env{'user.name'},
14571:                                                           $env{'user.domain'},
14572:                                                           $item,'reload',$context);
14573:                     if (($context eq 'requestcourses') ||
14574:                         ($context eq 'requestauthor')) {
14575:                         if ($env{'environment.canrequest.'.$item} ne $newacc) {
14576:                             $newenv{'environment.canrequest.'.$item} = $newacc;
14577:                         }
14578:                     } else {
14579:                         if ($env{'environment.availabletools.'.$item} ne $newacc) { 
14580:                             $newenv{'environment.availabletools.'.$item} = $newacc;
14581:                         }
14582:                     }
14583:                     unless ($context eq 'requestauthor') {
14584:                         $resulttext .= '<li>'.$titles{$item}.'<ul>';
14585:                     }
14586:                     foreach my $type (@{$types},'default','_LC_adv') {
14587:                         if ($haschgs{$type}) {
14588:                             my $typetitle = $usertypes->{$type};
14589:                             if ($type eq 'default') {
14590:                                 $typetitle = $othertitle;
14591:                             } elsif ($type eq '_LC_adv') {
14592:                                 $typetitle = 'LON-CAPA Advanced Users'; 
14593:                             }
14594:                             if ($inconf{$type}) {
14595:                                 if ($context eq 'requestcourses') {
14596:                                     my $cond;
14597:                                     if ($inconf{$type} =~ /^autolimit=(\d*)$/) {
14598:                                         if ($1 eq '') {
14599:                                             $cond = &mt('(Automatic processing of any request).');
14600:                                         } else {
14601:                                             $cond = &mt('(Automatic processing of requests up to limit of [quant,_1,request] per user).',$1);
14602:                                         }
14603:                                     } else { 
14604:                                         $cond = $conditions{$inconf{$type}};
14605:                                     }
14606:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1].',$typetitle).' '.$cond.'</li>';
14607:                                 } elsif ($context eq 'requestauthor') {
14608:                                     $resulttext .= '<li>'.&mt('Set to "[_1]" for "[_2]".',
14609:                                                              $titles{$inconf{$type}},$typetitle);
14610: 
14611:                                 } else {
14612:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1]',$typetitle).'</li>';
14613:                                 }
14614:                             } else {
14615:                                 if ($type eq '_LC_adv') {
14616:                                     if ($inconf{$type} eq '0') {
14617:                                         $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
14618:                                     } else { 
14619:                                         $resulttext .= '<li>'.&mt('No override set for [_1]',$typetitle).'</li>';
14620:                                     }
14621:                                 } else {
14622:                                     $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
14623:                                 }
14624:                             }
14625:                         }
14626:                     }
14627:                     unless ($context eq 'requestauthor') {
14628:                         $resulttext .= '</ul></li>';
14629:                     }
14630:                 }
14631:             }
14632:             if (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
14633:                 if (ref($changes{'notify'}) eq 'HASH') {
14634:                     if ($changes{'notify'}{'approval'}) {
14635:                         if (ref($confhash{'notify'}) eq 'HASH') {
14636:                             if ($confhash{'notify'}{'approval'}) {
14637:                                 $resulttext .= '<li>'.&mt('Notification of requests requiring approval will be sent to: ').$confhash{'notify'}{'approval'}.'</li>';
14638:                             } else {
14639:                                 $resulttext .= '<li>'.&mt('No Domain Coordinators will receive notification of requests requiring approval.').'</li>';
14640:                             }
14641:                         }
14642:                     }
14643:                 }
14644:             }
14645:             if ($action eq 'requestcourses') {
14646:                 my @offon = ('off','on');
14647:                 if ($changes{'uniquecode'}) {
14648:                     if (ref($confhash{'uniquecode'}) eq 'HASH') {
14649:                         my $codestr = join(' ',map{ &mt($_); } sort(keys(%{$confhash{'uniquecode'}})));
14650:                         $resulttext .= '<li>'.
14651:                                        &mt('Generation of six character code as course identifier for distribution to students set to on for: [_1].','<b>'.$codestr.'</b>').
14652:                                        '</li>';
14653:                     } else {
14654:                         $resulttext .= '<li>'.&mt('Generation of six character code as course identifier for distribution to students set to off.').
14655:                                        '</li>';
14656:                     }
14657:                 }
14658:                 foreach my $type ('textbooks','templates') {
14659:                     if (ref($changes{$type}) eq 'HASH') {
14660:                         $resulttext .= '<li>'.&mt("Available $type updated").'<ul>';
14661:                         foreach my $key (sort(keys(%{$changes{$type}}))) {
14662:                             my %coursehash = &Apache::lonnet::coursedescription($key);
14663:                             my $coursetitle = $coursehash{'description'};
14664:                             my $position = $confhash{$type}{$key}{'order'} + 1;
14665:                             $resulttext .= '<li>';
14666:                             foreach my $item ('subject','title','publisher','author') {
14667:                                 next if ((($item eq 'author') || ($item eq 'publisher')) &&
14668:                                          ($type eq 'templates'));
14669:                                 my $name = $item.':';
14670:                                 $name =~ s/^(\w)/\U$1/;
14671:                                 $resulttext .= &mt($name).' '.$confhash{$type}{$key}{$item}.'<br />';
14672:                             }
14673:                             $resulttext .= ' '.&mt('Order: [_1]',$position).'<br />';
14674:                             if ($type eq 'textbooks') {
14675:                                 if ($confhash{$type}{$key}{'image'}) {
14676:                                     $resulttext .= ' '.&mt('Image: [_1]',
14677:                                                    '<img src="'.$confhash{$type}{$key}{'image'}.'"'.
14678:                                                    ' alt="Textbook cover" />').'<br />';
14679:                                 }
14680:                             }
14681:                             $resulttext .= ' '.&mt('LON-CAPA Course: [_1]',$coursetitle).'</li>';
14682:                         }
14683:                         $resulttext .= '</ul></li>';
14684:                     }
14685:                 }
14686:                 if (ref($changes{'validation'}) eq 'HASH') {
14687:                     if ((ref($validationitemsref) eq 'ARRAY') && (ref($validationnamesref) eq 'HASH')) {
14688:                         $resulttext .= '<li>'.&mt('Validation of courses/communities updated').'<ul>';
14689:                         foreach my $item (@{$validationitemsref}) {
14690:                             if (exists($changes{'validation'}{$item})) {
14691:                                 if ($item eq 'markup') {
14692:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
14693:                                                               '<br /><pre>'.$changes{'validation'}{$item}.'</pre>').'</li>';
14694:                                 } else {
14695:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
14696:                                                               '<b>'.$changes{'validation'}{$item}.'</b>').'</li>';
14697:                                 }
14698:                             }
14699:                         }
14700:                         if (exists($changes{'validation'}{'dc'})) {
14701:                             $resulttext .= '<li>'.&mt('Validated course requests identified as processed by: [_1]',
14702:                                                      '<b>'.$changes{'validation'}{'dc'}.'</b>').'</li>';
14703:                         }
14704:                     }
14705:                 }
14706:             }
14707:             $resulttext .= '</ul>';
14708:             if (keys(%newenv)) {
14709:                 &Apache::lonnet::appenv(\%newenv);
14710:             }
14711:         } else {
14712:             if ($context eq 'requestcourses') {
14713:                 $resulttext = &mt('No changes made to rights to request creation of courses.');
14714:             } elsif ($context eq 'requestauthor') {
14715:                 $resulttext = &mt('No changes made to rights to request author space.');
14716:             } else {
14717:                 $resulttext = &mt('No changes made to availability of personal information pages, blogs, portfolios or default quotas');
14718:             }
14719:         }
14720:     } else {
14721:         $resulttext = '<span class="LC_error">'.
14722: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
14723:     }
14724:     if ($errors) {
14725:         $resulttext .= '<p>'.&mt('The following errors occurred when modifying Textbook settings.').
14726:                        '<ul>'.$errors.'</ul></p>';
14727:     }
14728:     return $resulttext;
14729: }
14730: 
14731: sub process_textbook_image {
14732:     my ($r,$dom,$confname,$caller,$cdom,$cnum,$type,$configuserok,$switchserver,$author_ok) = @_;
14733:     my $filename = $env{'form.'.$caller.'.filename'};
14734:     my ($error,$url);
14735:     my ($width,$height) = (50,50);
14736:     if ($configuserok eq 'ok') {
14737:         if ($switchserver) {
14738:             $error = &mt('Upload of textbook image is not permitted to this server: [_1]',
14739:                          $switchserver);
14740:         } elsif ($author_ok eq 'ok') {
14741:             my ($result,$imageurl) =
14742:                 &publishlogo($r,'upload',$caller,$dom,$confname,
14743:                              "$type/$cdom/$cnum/cover",$width,$height);
14744:             if ($result eq 'ok') {
14745:                 $url = $imageurl;
14746:             } else {
14747:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
14748:             }
14749:         } else {
14750:             $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);
14751:         }
14752:     } else {
14753:         $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);
14754:     }
14755:     return ($url,$error);
14756: }
14757: 
14758: sub modify_ltitools {
14759:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
14760:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
14761:     my ($newid,@allpos,%changes,%confhash,%encconfig,$errors,$resulttext);
14762:     my $confname = $dom.'-domainconfig';
14763:     my $servadm = $r->dir_config('lonAdmEMail');
14764:     my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
14765:     my (%posslti,%possfield);
14766:     my @courseroles = ('cc','in','ta','ep','st');
14767:     my @ltiroles = qw(Instructor ContentDeveloper TeachingAssistant Learner);
14768:     map { $posslti{$_} = 1; } @ltiroles;
14769:     my @allfields = ('fullname','firstname','lastname','email','user','roles');
14770:     map { $possfield{$_} = 1; } @allfields;
14771:     my %lt = &ltitools_names(); 
14772:     if ($env{'form.ltitools_add'}) {
14773:         my $title = $env{'form.ltitools_add_title'};
14774:         $title =~ s/(`)/'/g;
14775:         ($newid,my $error) = &get_ltitools_id($dom,$title);
14776:         if ($newid) {
14777:             my $position = $env{'form.ltitools_add_pos'};
14778:             $position =~ s/\D+//g;
14779:             if ($position ne '') {
14780:                 $allpos[$position] = $newid;
14781:             }
14782:             $changes{$newid} = 1;
14783:             foreach my $item ('title','url','key','secret','lifetime') {
14784:                 $env{'form.ltitools_add_'.$item} =~ s/(`)/'/g;
14785:                 if ($item eq 'lifetime') {
14786:                     $env{'form.ltitools_add_'.$item} =~ s/[^\d.]//g;
14787:                 }
14788:                 if ($env{'form.ltitools_add_'.$item}) {
14789:                     if (($item eq 'key') || ($item eq 'secret')) {
14790:                         $encconfig{$newid}{$item} = $env{'form.ltitools_add_'.$item};
14791:                     } else {
14792:                         $confhash{$newid}{$item} = $env{'form.ltitools_add_'.$item};
14793:                     }
14794:                 }
14795:             }
14796:             if ($env{'form.ltitools_add_version'} eq 'LTI-1p0') {
14797:                 $confhash{$newid}{'version'} = $env{'form.ltitools_add_version'};
14798:             }
14799:             if ($env{'form.ltitools_add_msgtype'} eq 'basic-lti-launch-request') {
14800:                 $confhash{$newid}{'msgtype'} = $env{'form.ltitools_add_msgtype'};
14801:             }
14802:             if ($env{'form.ltitools_add_sigmethod'} eq 'HMAC-SHA256') {
14803:                 $confhash{$newid}{'sigmethod'} = $env{'form.ltitools_add_sigmethod'};
14804:             } else {
14805:                 $confhash{$newid}{'sigmethod'} = 'HMAC-SHA1';
14806:             }
14807:             foreach my $item ('width','height','linktext','explanation') {
14808:                 $env{'form.ltitools_add_'.$item} =~ s/^\s+//;
14809:                 $env{'form.ltitools_add_'.$item} =~ s/\s+$//;
14810:                 if (($item eq 'width') || ($item eq 'height')) {
14811:                     if ($env{'form.ltitools_add_'.$item} =~ /^\d+$/) {
14812:                         $confhash{$newid}{'display'}{$item} = $env{'form.ltitools_add_'.$item};
14813:                     }
14814:                 } else {
14815:                     if ($env{'form.ltitools_add_'.$item} ne '') {
14816:                         $confhash{$newid}{'display'}{$item} = $env{'form.ltitools_add_'.$item}; 
14817:                     }
14818:                 }
14819:             }
14820:             if ($env{'form.ltitools_add_target'} eq 'window') {
14821:                 $confhash{$newid}{'display'}{'target'} = $env{'form.ltitools_add_target'};
14822:             } elsif ($env{'form.ltitools_add_target'} eq 'tab') {
14823:                 $confhash{$newid}{'display'}{'target'} = $env{'form.ltitools_add_target'};
14824:             } else {
14825:                 $confhash{$newid}{'display'}{'target'} = 'iframe';
14826:             }
14827:             foreach my $item ('passback','roster') {
14828:                 if ($env{'form.ltitools_'.$item.'_add'}) {
14829:                     $confhash{$newid}{$item} = 1;
14830:                     if ($env{'form.ltitools_'.$item.'valid_add'} ne '') {
14831:                         my $lifetime = $env{'form.ltitools_'.$item.'valid_add'};
14832:                         $lifetime =~ s/^\s+|\s+$//g;
14833:                         if ($lifetime =~ /^\d+\.?\d*$/) {
14834:                             $confhash{$newid}{$item.'valid'} = $lifetime;
14835:                         }
14836:                     }
14837:                 }
14838:             }
14839:             if ($env{'form.ltitools_add_image.filename'} ne '') {
14840:                 my ($imageurl,$error) =
14841:                     &process_ltitools_image($r,$dom,$confname,'ltitools_add_image',$newid,
14842:                                             $configuserok,$switchserver,$author_ok);
14843:                 if ($imageurl) {
14844:                     $confhash{$newid}{'image'} = $imageurl;
14845:                 }
14846:                 if ($error) {
14847:                     &Apache::lonnet::logthis($error);
14848:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
14849:                 }
14850:             }
14851:             my @fields = &Apache::loncommon::get_env_multiple('form.ltitools_add_fields');
14852:             foreach my $field (@fields) {
14853:                 if ($possfield{$field}) {
14854:                     if ($field eq 'roles') {
14855:                         foreach my $role (@courseroles) {
14856:                             my $choice = $env{'form.ltitools_add_roles_'.$role};
14857:                             if (($choice ne '') && ($posslti{$choice})) {
14858:                                 $confhash{$newid}{'roles'}{$role} = $choice;
14859:                                 if ($role eq 'cc') {
14860:                                     $confhash{$newid}{'roles'}{'co'} = $choice; 
14861:                                 }
14862:                             }
14863:                         }
14864:                     } else {
14865:                         $confhash{$newid}{'fields'}{$field} = 1;
14866:                     }
14867:                 }
14868:             }
14869:             if (ref($confhash{$newid}{'fields'}) eq 'HASH') {
14870:                 if ($confhash{$newid}{'fields'}{'user'}) {
14871:                     if ($env{'form.ltitools_userincdom_add'}) {
14872:                         $confhash{$newid}{'incdom'} = 1;
14873:                     }
14874:                 }
14875:             }
14876:             my @courseconfig = &Apache::loncommon::get_env_multiple('form.ltitools_courseconfig');
14877:             foreach my $item (@courseconfig) {
14878:                 $confhash{$newid}{'crsconf'}{$item} = 1;
14879:             }
14880:             if ($env{'form.ltitools_add_custom'}) {
14881:                 my $name = $env{'form.ltitools_add_custom_name'};
14882:                 my $value = $env{'form.ltitools_add_custom_value'};
14883:                 $value =~ s/(`)/'/g;
14884:                 $name =~ s/(`)/'/g;
14885:                 $confhash{$newid}{'custom'}{$name} = $value;
14886:             }
14887:         } else {
14888:             my $error = &mt('Failed to acquire unique ID for new external tool');   
14889:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
14890:         }
14891:     }
14892:     if (ref($domconfig{$action}) eq 'HASH') {
14893:         my %deletions;
14894:         my @todelete = &Apache::loncommon::get_env_multiple('form.ltitools_del');
14895:         if (@todelete) {
14896:             map { $deletions{$_} = 1; } @todelete;
14897:         }
14898:         my %customadds;
14899:         my @newcustom = &Apache::loncommon::get_env_multiple('form.ltitools_customadd');
14900:         if (@newcustom) {
14901:             map { $customadds{$_} = 1; } @newcustom;
14902:         } 
14903:         my %imgdeletions;
14904:         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.ltitools_image_del');
14905:         if (@todeleteimages) {
14906:             map { $imgdeletions{$_} = 1; } @todeleteimages;
14907:         }
14908:         my $maxnum = $env{'form.ltitools_maxnum'};
14909:         for (my $i=0; $i<=$maxnum; $i++) {
14910:             my $itemid = $env{'form.ltitools_id_'.$i};
14911:             $itemid =~ s/\D+//g;
14912:             if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
14913:                 if ($deletions{$itemid}) {
14914:                     if ($domconfig{$action}{$itemid}{'image'}) {
14915:                         #FIXME need to obsolete item in RES space
14916:                     }
14917:                     $changes{$itemid} = $domconfig{$action}{$itemid}{'title'};
14918:                     next;
14919:                 } else {
14920:                     my $newpos = $env{'form.ltitools_'.$itemid};
14921:                     $newpos =~ s/\D+//g;
14922:                     foreach my $item ('title','url','lifetime') {
14923:                         $confhash{$itemid}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
14924:                         if ($domconfig{$action}{$itemid}{$item} ne $confhash{$itemid}{$item}) {
14925:                             $changes{$itemid} = 1;
14926:                         }
14927:                     }
14928:                     foreach my $item ('key','secret') {
14929:                         $encconfig{$itemid}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
14930:                         if ($domconfig{$action}{$itemid}{$item} ne $encconfig{$itemid}{$item}) {
14931:                             $changes{$itemid} = 1;
14932:                         }
14933:                     }
14934:                     if ($env{'form.ltitools_version_'.$i} eq 'LTI-1p0') {
14935:                         $confhash{$itemid}{'version'} = $env{'form.ltitools_version_'.$i};
14936:                     }
14937:                     if ($env{'form.ltitools_msgtype_'.$i} eq 'basic-lti-launch-request') {
14938:                         $confhash{$itemid}{'msgtype'} = $env{'form.ltitools_msgtype_'.$i};
14939:                     }
14940:                     if ($env{'form.ltitools_sigmethod_'.$i} eq 'HMAC-SHA256') {
14941:                         $confhash{$itemid}{'sigmethod'} = $env{'form.ltitools_sigmethod_'.$i};
14942:                     } else {
14943:                         $confhash{$itemid}{'sigmethod'} = 'HMAC-SHA1'; 
14944:                     }
14945:                     if ($domconfig{$action}{$itemid}{'sigmethod'} eq '') {
14946:                         if ($confhash{$itemid}{'sigmethod'} ne 'HMAC-SHA1') {
14947:                             $changes{$itemid} = 1;
14948:                         }
14949:                     } elsif ($domconfig{$action}{$itemid}{'sigmethod'} ne $confhash{$itemid}{'sigmethod'}) {
14950:                         $changes{$itemid} = 1;
14951:                     }
14952:                     foreach my $size ('width','height') {
14953:                         $env{'form.ltitools_'.$size.'_'.$i} =~ s/^\s+//;
14954:                         $env{'form.ltitools_'.$size.'_'.$i} =~ s/\s+$//;
14955:                         if ($env{'form.ltitools_'.$size.'_'.$i} =~ /^\d+$/) {
14956:                             $confhash{$itemid}{'display'}{$size} = $env{'form.ltitools_'.$size.'_'.$i};
14957:                             if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
14958:                                 if ($domconfig{$action}{$itemid}{'display'}{$size} ne $confhash{$itemid}{'display'}{$size}) {
14959:                                     $changes{$itemid} = 1;
14960:                                 }
14961:                             } else {
14962:                                 $changes{$itemid} = 1;
14963:                             }
14964:                         } elsif (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
14965:                             if ($domconfig{$action}{$itemid}{'display'}{$size} ne '') {
14966:                                 $changes{$itemid} = 1;
14967:                             }
14968:                         }
14969:                     }
14970:                     foreach my $item ('linktext','explanation') {
14971:                         $env{'form.ltitools_'.$item.'_'.$i} =~ s/^\s+//;
14972:                         $env{'form.ltitools_'.$item.'_'.$i} =~ s/\s+$//;
14973:                         if ($env{'form.ltitools_'.$item.'_'.$i} ne '') {
14974:                             $confhash{$itemid}{'display'}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
14975:                             if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
14976:                                 if ($domconfig{$action}{$itemid}{'display'}{$item} ne $confhash{$itemid}{'display'}{$item}) {
14977:                                     $changes{$itemid} = 1;
14978:                                 }
14979:                             } else {
14980:                                 $changes{$itemid} = 1;
14981:                             }
14982:                         } elsif (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
14983:                             if ($domconfig{$action}{$itemid}{'display'}{$item} ne '') {
14984:                                 $changes{$itemid} = 1;
14985:                             }
14986:                         }
14987:                     }
14988:                     if ($env{'form.ltitools_target_'.$i} eq 'window') {
14989:                         $confhash{$itemid}{'display'}{'target'} = $env{'form.ltitools_target_'.$i};
14990:                     } elsif ($env{'form.ltitools_target_'.$i} eq 'tab') {
14991:                         $confhash{$itemid}{'display'}{'target'} = $env{'form.ltitools_target_'.$i};
14992:                     } else {
14993:                         $confhash{$itemid}{'display'}{'target'} = 'iframe';
14994:                     }
14995:                     if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
14996:                         if ($domconfig{$action}{$itemid}{'display'}{'target'} ne $confhash{$itemid}{'display'}{'target'}) {
14997:                             $changes{$itemid} = 1;
14998:                         }
14999:                     } else {
15000:                         $changes{$itemid} = 1;
15001:                     }
15002:                     foreach my $extra ('passback','roster') {
15003:                         if ($env{'form.ltitools_'.$extra.'_'.$i}) {
15004:                             $confhash{$itemid}{$extra} = 1;
15005:                             if ($env{'form.ltitools_'.$extra.'valid_'.$i} ne '') {
15006:                                 my $lifetime = $env{'form.ltitools_'.$extra.'valid_'.$i};
15007:                                 $lifetime =~ s/^\s+|\s+$//g;
15008:                                 if ($lifetime =~ /^\d+\.?\d*$/) {
15009:                                     $confhash{$itemid}{$extra.'valid'} = $lifetime;
15010:                                 }
15011:                             }
15012:                         }
15013:                         if ($domconfig{$action}{$itemid}{$extra} ne $confhash{$itemid}{$extra}) {
15014:                             $changes{$itemid} = 1;
15015:                         }
15016:                         if ($domconfig{$action}{$itemid}{$extra.'valid'} ne $confhash{$itemid}{$extra.'valid'}) {
15017:                             $changes{$itemid} = 1;
15018:                         }
15019:                     }
15020:                     my @courseconfig = &Apache::loncommon::get_env_multiple('form.ltitools_courseconfig_'.$i);
15021:                     foreach my $item ('label','title','target','linktext','explanation','append') {
15022:                         if (grep(/^\Q$item\E$/,@courseconfig)) {
15023:                             $confhash{$itemid}{'crsconf'}{$item} = 1;
15024:                             if (ref($domconfig{$action}{$itemid}{'crsconf'}) eq 'HASH') {
15025:                                 if ($domconfig{$action}{$itemid}{'crsconf'}{$item} ne $confhash{$itemid}{'crsconf'}{$item}) {
15026:                                     $changes{$itemid} = 1;
15027:                                 }
15028:                             } else {
15029:                                 $changes{$itemid} = 1;
15030:                             }
15031:                         }
15032:                     }
15033:                     my @fields = &Apache::loncommon::get_env_multiple('form.ltitools_fields_'.$i);
15034:                     foreach my $field (@fields) {
15035:                         if ($possfield{$field}) {
15036:                             if ($field eq 'roles') {
15037:                                 foreach my $role (@courseroles) {
15038:                                     my $choice = $env{'form.ltitools_roles_'.$role.'_'.$i};
15039:                                     if (($choice ne '') && ($posslti{$choice})) {
15040:                                         $confhash{$itemid}{'roles'}{$role} = $choice;
15041:                                         if ($role eq 'cc') {
15042:                                             $confhash{$itemid}{'roles'}{'co'} = $choice;
15043:                                         }
15044:                                     }
15045:                                     if (ref($domconfig{$action}{$itemid}{'roles'}) eq 'HASH') {
15046:                                         if ($domconfig{$action}{$itemid}{'roles'}{$role} ne $confhash{$itemid}{'roles'}{$role}) {
15047:                                             $changes{$itemid} = 1;
15048:                                         }
15049:                                     } elsif ($confhash{$itemid}{'roles'}{$role}) {
15050:                                         $changes{$itemid} = 1;
15051:                                     }
15052:                                 }
15053:                             } else {
15054:                                 $confhash{$itemid}{'fields'}{$field} = 1;
15055:                                 if (ref($domconfig{$action}{$itemid}{'fields'}) eq 'HASH') {
15056:                                     if ($domconfig{$action}{$itemid}{'fields'}{$field} ne $confhash{$itemid}{'fields'}{$field}) {
15057:                                         $changes{$itemid} = 1;
15058:                                     }
15059:                                 } else {
15060:                                     $changes{$itemid} = 1;
15061:                                 }
15062:                             }
15063:                         }
15064:                     }
15065:                     if (ref($confhash{$itemid}{'fields'}) eq 'HASH') {
15066:                         if ($confhash{$itemid}{'fields'}{'user'}) {
15067:                             if ($env{'form.ltitools_userincdom_'.$i}) {
15068:                                 $confhash{$itemid}{'incdom'} = 1;
15069:                             }
15070:                             if ($domconfig{$action}{$itemid}{'incdom'} ne $confhash{$itemid}{'incdom'}) {
15071:                                 $changes{$itemid} = 1;
15072:                             }
15073:                         }
15074:                     }
15075:                     $allpos[$newpos] = $itemid;
15076:                 }
15077:                 if ($imgdeletions{$itemid}) {
15078:                     $changes{$itemid} = 1;
15079:                     #FIXME need to obsolete item in RES space
15080:                 } elsif ($env{'form.ltitools_image_'.$i.'.filename'}) {
15081:                     my ($imgurl,$error) = &process_ltitools_image($r,$dom,$confname,'ltitools_image_'.$i,
15082:                                                                  $itemid,$configuserok,$switchserver,
15083:                                                                  $author_ok);
15084:                     if ($imgurl) {
15085:                         $confhash{$itemid}{'image'} = $imgurl;
15086:                         $changes{$itemid} = 1;
15087:                     }
15088:                     if ($error) {
15089:                         &Apache::lonnet::logthis($error);
15090:                         $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
15091:                     }
15092:                 } elsif ($domconfig{$action}{$itemid}{'image'}) {
15093:                     $confhash{$itemid}{'image'} =
15094:                        $domconfig{$action}{$itemid}{'image'};
15095:                 }
15096:                 if ($customadds{$i}) {
15097:                     my $name = $env{'form.ltitools_custom_name_'.$i};
15098:                     $name =~ s/(`)/'/g;
15099:                     $name =~ s/^\s+//;
15100:                     $name =~ s/\s+$//;
15101:                     my $value = $env{'form.ltitools_custom_value_'.$i};
15102:                     $value =~ s/(`)/'/g;
15103:                     $value =~ s/^\s+//;
15104:                     $value =~ s/\s+$//;
15105:                     if ($name ne '') {
15106:                         $confhash{$itemid}{'custom'}{$name} = $value;
15107:                         $changes{$itemid} = 1;
15108:                     }
15109:                 }
15110:                 my %customdels;
15111:                 my @customdeletions = &Apache::loncommon::get_env_multiple('form.ltitools_customdel_'.$i); 
15112:                 if (@customdeletions) {
15113:                     $changes{$itemid} = 1;
15114:                 }
15115:                 map { $customdels{$_} = 1; } @customdeletions;
15116:                 if (ref($domconfig{$action}{$itemid}{'custom'}) eq 'HASH') {
15117:                     foreach my $key (keys(%{$domconfig{$action}{$itemid}{'custom'}})) {
15118:                         unless ($customdels{$key}) {
15119:                             if ($env{'form.ltitools_customval_'.$key.'_'.$i} ne '') {
15120:                                 $confhash{$itemid}{'custom'}{$key} = $env{'form.ltitools_customval_'.$key.'_'.$i}; 
15121:                             }
15122:                             if ($domconfig{$action}{$itemid}{'custom'}{$key} ne $env{'form.ltitools_customval_'.$key.'_'.$i}) {
15123:                                 $changes{$itemid} = 1;
15124:                             }
15125:                         }
15126:                     }
15127:                 }
15128:                 unless ($changes{$itemid}) {
15129:                     foreach my $key (keys(%{$domconfig{$action}{$itemid}})) {
15130:                         if (ref($domconfig{$action}{$itemid}{$key}) eq 'HASH') {
15131:                             if (ref($confhash{$itemid}{$key}) eq 'HASH') {
15132:                                 foreach my $innerkey (keys(%{$domconfig{$action}{$itemid}{$key}})) {
15133:                                     unless (exists($confhash{$itemid}{$key}{$innerkey})) {
15134:                                         $changes{$itemid} = 1;
15135:                                         last;
15136:                                     }
15137:                                 }
15138:                             } elsif (keys(%{$domconfig{$action}{$itemid}{$key}}) > 0) {
15139:                                 $changes{$itemid} = 1;
15140:                             }
15141:                         }
15142:                         last if ($changes{$itemid});
15143:                     }
15144:                 }
15145:             }
15146:         }
15147:     }
15148:     if (@allpos > 0) {
15149:         my $idx = 0;
15150:         foreach my $itemid (@allpos) {
15151:             if ($itemid ne '') {
15152:                 $confhash{$itemid}{'order'} = $idx;
15153:                 if (ref($domconfig{$action}) eq 'HASH') {
15154:                     if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
15155:                         if ($domconfig{$action}{$itemid}{'order'} ne $idx) {
15156:                             $changes{$itemid} = 1;
15157:                         }
15158:                     }
15159:                 }
15160:                 $idx ++;
15161:             }
15162:         }
15163:     }
15164:     my %ltitoolshash = (
15165:                           $action => { %confhash }
15166:                        );
15167:     my $putresult = &Apache::lonnet::put_dom('configuration',\%ltitoolshash,
15168:                                              $dom);
15169:     if ($putresult eq 'ok') {
15170:         my %ltienchash = (
15171:                              $action => { %encconfig }
15172:                          );
15173:         &Apache::lonnet::put_dom('encconfig',\%ltienchash,$dom,undef,1);
15174:         if (keys(%changes) > 0) {
15175:             my $cachetime = 24*60*60;
15176:             my %ltiall = %confhash;
15177:             foreach my $id (keys(%ltiall)) {
15178:                 if (ref($encconfig{$id}) eq 'HASH') {
15179:                     foreach my $item ('key','secret') {
15180:                         $ltiall{$id}{$item} = $encconfig{$id}{$item};
15181:                     }
15182:                 }
15183:             }
15184:             &Apache::lonnet::do_cache_new('ltitools',$dom,\%ltiall,$cachetime);
15185:             if (ref($lastactref) eq 'HASH') {
15186:                 $lastactref->{'ltitools'} = 1;
15187:             }
15188:             $resulttext = &mt('Changes made:').'<ul>';
15189:             my %bynum;
15190:             foreach my $itemid (sort(keys(%changes))) {
15191:                 my $position = $confhash{$itemid}{'order'};
15192:                 $bynum{$position} = $itemid;
15193:             }
15194:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
15195:                 my $itemid = $bynum{$pos}; 
15196:                 if (ref($confhash{$itemid}) ne 'HASH') {
15197:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
15198:                 } else {
15199:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'title'}.'</b>';
15200:                     if ($confhash{$itemid}{'image'}) {
15201:                         $resulttext .= '&nbsp;'.
15202:                                        '<img src="'.$confhash{$itemid}{'image'}.'"'.
15203:                                        ' alt="'.&mt('Tool Provider icon').'" />';
15204:                     }
15205:                     $resulttext .= '</li><ul>';
15206:                     my $position = $pos + 1;
15207:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
15208:                     foreach my $item ('version','msgtype','sigmethod','url','lifetime') {
15209:                         if ($confhash{$itemid}{$item} ne '') {
15210:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{$item}.'</li>';
15211:                         }
15212:                     }
15213:                     if ($encconfig{$itemid}{'key'} ne '') {
15214:                         $resulttext .= '<li>'.$lt{'key'}.':&nbsp;'.$encconfig{$itemid}{'key'}.'</li>';
15215:                     }
15216:                     if ($encconfig{$itemid}{'secret'} ne '') {
15217:                         $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;';
15218:                         my $num = length($encconfig{$itemid}{'secret'});
15219:                         $resulttext .= ('*'x$num).'</li>';
15220:                     }
15221:                     $resulttext .= '<li>'.&mt('Configurable in course:');
15222:                     my @possconfig = ('label','title','target','linktext','explanation','append');
15223:                     my $numconfig = 0; 
15224:                     if (ref($confhash{$itemid}{'crsconf'}) eq 'HASH') { 
15225:                         foreach my $item (@possconfig) {
15226:                             if ($confhash{$itemid}{'crsconf'}{$item}) {
15227:                                 $numconfig ++;
15228:                                 $resulttext .= ' "'.$lt{'crs'.$item}.'"';
15229:                             }
15230:                         }
15231:                     }
15232:                     if (!$numconfig) {
15233:                         $resulttext .= '&nbsp;'.&mt('None');
15234:                     }
15235:                     $resulttext .= '</li>';
15236:                     foreach my $item ('passback','roster') {
15237:                         $resulttext .= '<li>'.$lt{$item}.'&nbsp;';
15238:                         if ($confhash{$itemid}{$item}) {
15239:                             $resulttext .= &mt('Yes');
15240:                             if ($confhash{$itemid}{$item.'valid'}) {
15241:                                 if ($item eq 'passback') {
15242:                                     $resulttext .= ' '.&mt('valid for at least [quant,_1,day] after launch',
15243:                                                            $confhash{$itemid}{$item.'valid'});
15244:                                 } else {
15245:                                     $resulttext .= ' '.&mt('valid for at least [quant,_1,second] after launch',
15246:                                                            $confhash{$itemid}{$item.'valid'});
15247:                                 }
15248:                             }
15249:                         } else {
15250:                             $resulttext .= &mt('No');
15251:                         }
15252:                         $resulttext .= '</li>';
15253:                     }
15254:                     if (ref($confhash{$itemid}{'display'}) eq 'HASH') {
15255:                         my $displaylist;
15256:                         if ($confhash{$itemid}{'display'}{'target'}) {
15257:                             $displaylist = &mt('Display target').':&nbsp;'.
15258:                                            $confhash{$itemid}{'display'}{'target'}.',';
15259:                         }
15260:                         foreach my $size ('width','height') { 
15261:                             if ($confhash{$itemid}{'display'}{$size}) {
15262:                                 $displaylist .= ('&nbsp;'x2).$lt{$size}.':&nbsp;'.
15263:                                                 $confhash{$itemid}{'display'}{$size}.',';
15264:                             }
15265:                         }
15266:                         if ($displaylist) {
15267:                             $displaylist =~ s/,$//;
15268:                             $resulttext .= '<li>'.$displaylist.'</li>';
15269:                         }
15270:                         foreach my $item ('linktext','explanation') {
15271:                             if ($confhash{$itemid}{'display'}{$item}) {
15272:                                 $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{'display'}{$item}.'</li>';
15273:                             }
15274:                         }
15275:                     }
15276:                     if (ref($confhash{$itemid}{'fields'}) eq 'HASH') {
15277:                         my $fieldlist;
15278:                         foreach my $field (@allfields) {
15279:                             if ($confhash{$itemid}{'fields'}{$field}) {
15280:                                 $fieldlist .= ('&nbsp;'x2).$lt{$field}.',';
15281:                             }
15282:                         }
15283:                         if ($fieldlist) {
15284:                             $fieldlist =~ s/,$//;
15285:                             if ($confhash{$itemid}{'fields'}{'user'}) {
15286:                                 if ($confhash{$itemid}{'incdom'}) {
15287:                                     $fieldlist .= ' ('.&mt('username:domain').')';
15288:                                 } else {
15289:                                     $fieldlist .= ' ('.&mt('username').')';
15290:                                 }
15291:                             }
15292:                             $resulttext .= '<li>'.&mt('Data sent').':'.$fieldlist.'</li>';
15293:                         }
15294:                     }
15295:                     if (ref($confhash{$itemid}{'roles'}) eq 'HASH') {
15296:                         my $rolemaps;
15297:                         foreach my $role (@courseroles) {
15298:                             if ($confhash{$itemid}{'roles'}{$role}) {
15299:                                 $rolemaps .= ('&nbsp;'x2).&Apache::lonnet::plaintext($role,'Course').'='.
15300:                                              $confhash{$itemid}{'roles'}{$role}.',';
15301:                             }
15302:                         }
15303:                         if ($rolemaps) {
15304:                             $rolemaps =~ s/,$//; 
15305:                             $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
15306:                         }
15307:                     }
15308:                     if (ref($confhash{$itemid}{'custom'}) eq 'HASH') {
15309:                         my $customlist;
15310:                         if (keys(%{$confhash{$itemid}{'custom'}})) {
15311:                             foreach my $key (sort(keys(%{$confhash{$itemid}{'custom'}}))) {
15312:                                 $customlist .= $key.':'.$confhash{$itemid}{'custom'}{$key}.('&nbsp;'x2);
15313:                             } 
15314:                         }
15315:                         if ($customlist) {
15316:                             $resulttext .= '<li>'.&mt('Custom items').': '.$customlist.'</li>';
15317:                         }
15318:                     } 
15319:                     $resulttext .= '</ul></li>';
15320:                 }
15321:             }
15322:             $resulttext .= '</ul>';
15323:         } else {
15324:             $resulttext = &mt('No changes made.');
15325:         }
15326:     } else {
15327:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
15328:     }
15329:     if ($errors) {
15330:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
15331:                        $errors.'</ul>';
15332:     }
15333:     return $resulttext;
15334: }
15335: 
15336: sub process_ltitools_image {
15337:     my ($r,$dom,$confname,$caller,$itemid,$configuserok,$switchserver,$author_ok) = @_;
15338:     my $filename = $env{'form.'.$caller.'.filename'};
15339:     my ($error,$url);
15340:     my ($width,$height) = (21,21);
15341:     if ($configuserok eq 'ok') {
15342:         if ($switchserver) {
15343:             $error = &mt('Upload of Tool Provider (LTI) icon is not permitted to this server: [_1]',
15344:                          $switchserver);
15345:         } elsif ($author_ok eq 'ok') {
15346:             my ($result,$imageurl,$madethumb) =
15347:                 &publishlogo($r,'upload',$caller,$dom,$confname,
15348:                              "ltitools/$itemid/icon",$width,$height);
15349:             if ($result eq 'ok') {
15350:                 if ($madethumb) {
15351:                     my ($path,$imagefile) = ($imageurl =~ m{^(.+)/([^/]+)$});
15352:                     my $imagethumb = "$path/tn-".$imagefile;
15353:                     $url = $imagethumb;
15354:                 } else {
15355:                     $url = $imageurl;
15356:                 }
15357:             } else {
15358:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
15359:             }
15360:         } else {
15361:             $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);
15362:         }
15363:     } else {
15364:         $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);
15365:     }
15366:     return ($url,$error);
15367: }
15368: 
15369: sub get_ltitools_id {
15370:     my ($cdom,$title) = @_;
15371:     # get lock on ltitools db
15372:     my $lockhash = {
15373:                       lock => $env{'user.name'}.
15374:                               ':'.$env{'user.domain'},
15375:                    };
15376:     my $tries = 0;
15377:     my $gotlock = &Apache::lonnet::newput_dom('ltitools',$lockhash,$cdom);
15378:     my ($id,$error);
15379:  
15380:     while (($gotlock ne 'ok') && ($tries<10)) {
15381:         $tries ++;
15382:         sleep (0.1);
15383:         $gotlock = &Apache::lonnet::newput_dom('ltitools',$lockhash,$cdom);
15384:     }
15385:     if ($gotlock eq 'ok') {
15386:         my %currids = &Apache::lonnet::dump_dom('ltitools',$cdom);
15387:         if ($currids{'lock'}) {
15388:             delete($currids{'lock'});
15389:             if (keys(%currids)) {
15390:                 my @curr = sort { $a <=> $b } keys(%currids);
15391:                 if ($curr[-1] =~ /^\d+$/) {
15392:                     $id = 1 + $curr[-1];
15393:                 }
15394:             } else {
15395:                 $id = 1;
15396:             }
15397:             if ($id) {
15398:                 unless (&Apache::lonnet::newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
15399:                     $error = 'nostore';
15400:                 }
15401:             } else {
15402:                 $error = 'nonumber';
15403:             }
15404:         }
15405:         my $dellockoutcome = &Apache::lonnet::del_dom('ltitools',['lock'],$cdom);
15406:     } else {
15407:         $error = 'nolock';
15408:     }
15409:     return ($id,$error);
15410: }
15411: 
15412: sub modify_proctoring {
15413:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
15414:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
15415:     my (@allpos,%changes,%confhash,%encconfhash,$errors,$resulttext,%imgdeletions);
15416:     my $confname = $dom.'-domainconfig';
15417:     my $servadm = $r->dir_config('lonAdmEMail');
15418:     my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
15419:     my %providernames = &proctoring_providernames();
15420:     my $maxnum = scalar(keys(%providernames));
15421: 
15422:     my (%requserfields,%optuserfields,%defaults,%extended,%crsconf,@courseroles,@ltiroles);
15423:     my ($requref,$opturef,$defref,$extref,$crsref,$rolesref,$ltiref) = &proctoring_data();
15424:     if (ref($requref) eq 'HASH') {
15425:         %requserfields = %{$requref};
15426:     }
15427:     if (ref($opturef) eq 'HASH') {
15428:         %optuserfields = %{$opturef};
15429:     }
15430:     if (ref($defref) eq 'HASH') {
15431:         %defaults = %{$defref};
15432:     }
15433:     if (ref($extref) eq 'HASH') {
15434:         %extended = %{$extref};
15435:     }
15436:     if (ref($crsref) eq 'HASH') {
15437:         %crsconf = %{$crsref};
15438:     }
15439:     if (ref($rolesref) eq 'ARRAY') {
15440:         @courseroles = @{$rolesref};
15441:     }
15442:     if (ref($ltiref) eq 'ARRAY') {
15443:         @ltiroles = @{$ltiref};
15444:     }
15445: 
15446:     if (ref($domconfig{$action}) eq 'HASH') {
15447:         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.proctoring_image_del');
15448:         if (@todeleteimages) {
15449:             map { $imgdeletions{$_} = 1; } @todeleteimages;
15450:         }
15451:     }
15452:     my %customadds;
15453:     my @newcustom = &Apache::loncommon::get_env_multiple('form.proctoring_customadd');
15454:     if (@newcustom) {
15455:         map { $customadds{$_} = 1; } @newcustom;
15456:     }
15457:     foreach my $provider (sort(keys(%providernames))) {
15458:         $confhash{$provider} = {};
15459:         my $pos = $env{'form.proctoring_pos_'.$provider};
15460:         $pos =~ s/\D+//g;
15461:         $allpos[$pos] = $provider;
15462:         my (%current,%currentenc);
15463:         my $showroles = 0;
15464:         if (ref($domconfig{$action}) eq 'HASH') {
15465:             if (ref($domconfig{$action}{$provider}) eq 'HASH') {
15466:                 %current = %{$domconfig{$action}{$provider}};
15467:                 foreach my $item ('key','secret') { 
15468:                     $currentenc{$item} = $current{$item};
15469:                     delete($current{$item});
15470:                 }
15471:             }
15472:         }
15473:         if ($env{'form.proctoring_available_'.$provider}) {
15474:             $confhash{$provider}{'available'} = 1;
15475:             unless ($current{'available'}) {
15476:                 $changes{$provider} = 1;
15477:             }
15478:         } else {
15479:             %{$confhash{$provider}} = %current;
15480:             %{$encconfhash{$provider}} = %currentenc;
15481:             $confhash{$provider}{'available'} = 0;
15482:             if ($current{'available'}) {
15483:                 $changes{$provider} = 1;
15484:             }
15485:         }
15486:         if ($confhash{$provider}{'available'}) {
15487:             foreach my $field ('lifetime','version','sigmethod','url','key','secret') {
15488:                 my $possval = $env{'form.proctoring_'.$provider.'_'.$field};
15489:                 if ($field eq 'lifetime') {
15490:                     if ($possval =~ /^\d+$/) {
15491:                         $confhash{$provider}{$field} = $possval;
15492:                     }
15493:                 } elsif ($field eq 'version') {
15494:                     if ($possval =~ /^\d+\.\d+$/) {
15495:                         $confhash{$provider}{$field} = $possval;
15496:                     }
15497:                 } elsif ($field eq 'sigmethod') {
15498:                     if ($possval =~ /^\QHMAC-SHA\E(1|256)$/) {
15499:                         $confhash{$provider}{$field} = $possval;
15500:                     }
15501:                 } elsif ($field eq 'url') {
15502:                     $confhash{$provider}{$field} = $possval;
15503:                 } elsif (($field eq 'key') || ($field eq 'secret')) {
15504:                     $encconfhash{$provider}{$field} = $possval;
15505:                     unless ($currentenc{$field} eq $possval) {
15506:                         $changes{$provider} = 1;
15507:                     }
15508:                 }
15509:                 unless (($field eq 'key') || ($field eq 'secret')) {
15510:                     unless ($current{$field} eq $confhash{$provider}{$field}) {
15511:                         $changes{$provider} = 1;
15512:                     }
15513:                 }
15514:             }
15515:             if ($imgdeletions{$provider}) {
15516:                 $changes{$provider} = 1;
15517:             } elsif ($env{'form.proctoring_image_'.$provider.'.filename'} ne '') {
15518:                 my ($imageurl,$error) =
15519:                     &process_proctoring_image($r,$dom,$confname,'proctoring_image_'.$provider,$provider,
15520:                                               $configuserok,$switchserver,$author_ok);
15521:                 if ($imageurl) {
15522:                     $confhash{$provider}{'image'} = $imageurl;
15523:                     $changes{$provider} = 1; 
15524:                 }
15525:                 if ($error) {
15526:                     &Apache::lonnet::logthis($error);
15527:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
15528:                 }
15529:             } elsif (exists($current{'image'})) {
15530:                 $confhash{$provider}{'image'} = $current{'image'};
15531:             }
15532:             if (ref($requserfields{$provider}) eq 'ARRAY') {
15533:                 if (@{$requserfields{$provider}} > 0) {
15534:                     if (grep(/^user$/,@{$requserfields{$provider}})) {
15535:                         if ($env{'form.proctoring_userincdom_'.$provider}) {
15536:                             $confhash{$provider}{'incdom'} = 1;
15537:                         }
15538:                         unless ($current{'incdom'} eq $confhash{$provider}{'incdom'}) {
15539:                             $changes{$provider} = 1;
15540:                         }
15541:                     }
15542:                     if (grep(/^roles$/,@{$requserfields{$provider}})) {
15543:                         $showroles = 1;
15544:                     }
15545:                 }
15546:             }
15547:             $confhash{$provider}{'fields'} = [];
15548:             if (ref($optuserfields{$provider}) eq 'ARRAY') {
15549:                 if (@{$optuserfields{$provider}} > 0) {
15550:                     my @optfields = &Apache::loncommon::get_env_multiple('form.proctoring_optional_'.$provider);
15551:                     foreach my $field (@{$optuserfields{$provider}}) {
15552:                         if (grep(/^\Q$field\E$/,@optfields)) {
15553:                             push(@{$confhash{$provider}{'fields'}},$field);
15554:                         }
15555:                     }
15556:                 }
15557:                 if (ref($current{'fields'}) eq 'ARRAY') {
15558:                     unless ($changes{$provider}) {
15559:                         my @new = sort(@{$confhash{$provider}{'fields'}});
15560:                         my @old = sort(@{$current{'fields'}}); 
15561:                         my @diffs = &Apache::loncommon::compare_arrays(\@new,\@old);
15562:                         if (@diffs) {
15563:                             $changes{$provider} = 1;
15564:                         }
15565:                     }
15566:                 } elsif (@{$confhash{$provider}{'fields'}}) {
15567:                     $changes{$provider} = 1;
15568:                 }
15569:             }
15570:             if (ref($defaults{$provider}) eq 'ARRAY') {  
15571:                 if (@{$defaults{$provider}} > 0) {
15572:                     my %options;
15573:                     if (ref($extended{$provider}) eq 'HASH') {
15574:                         %options = %{$extended{$provider}};
15575:                     }
15576:                     my @checked = &Apache::loncommon::get_env_multiple('form.proctoring_defaults_'.$provider);
15577:                     foreach my $field (@{$defaults{$provider}}) {
15578:                         if ((exists($options{$field})) && (ref($options{$field}) eq 'ARRAY')) {
15579:                             my $poss = $env{'form.proctoring_defaults_'.$field.'_'.$provider};
15580:                             if (grep(/^\Q$poss\E$/,@{$options{$field}})) {
15581:                                 push(@{$confhash{$provider}{'defaults'}},$poss); 
15582:                             }
15583:                         } elsif ((exists($options{$field})) && (ref($options{$field}) eq 'HASH')) {
15584:                             foreach my $inner (keys(%{$options{$field}})) {
15585:                                 if (ref($options{$field}{$inner}) eq 'ARRAY') {
15586:                                     my $poss = $env{'form.proctoring_'.$inner.'_'.$provider};
15587:                                     if (grep(/^\Q$poss\E$/,@{$options{$field}{$inner}})) {
15588:                                         $confhash{$provider}{'defaults'}{$inner} = $poss;
15589:                                     }
15590:                                 } else {
15591:                                     $confhash{$provider}{'defaults'}{$inner} = $env{'form.proctoring_'.$inner.'_'.$provider};
15592:                                 }
15593:                             }
15594:                         } else {
15595:                             if (grep(/^\Q$field\E$/,@checked)) {
15596:                                 push(@{$confhash{$provider}{'defaults'}},$field);
15597:                             }
15598:                         }
15599:                     }
15600:                     if (ref($confhash{$provider}{'defaults'}) eq 'ARRAY') {
15601:                         if (ref($current{'defaults'}) eq 'ARRAY') {
15602:                             unless ($changes{$provider}) {
15603:                                 my @new = sort(@{$confhash{$provider}{'defaults'}});
15604:                                 my @old = sort(@{$current{'defaults'}});
15605:                                 my @diffs = &Apache::loncommon::compare_arrays(\@new,\@old);
15606:                                 if (@diffs) {
15607:                                     $changes{$provider} = 1; 
15608:                                 }
15609:                             }
15610:                         } elsif (ref($current{'defaults'}) eq 'ARRAY') {
15611:                             if (@{$current{'defaults'}}) {
15612:                                 $changes{$provider} = 1;
15613:                             }
15614:                         }
15615:                     } elsif (ref($confhash{$provider}{'defaults'}) eq 'HASH') {
15616:                         if (ref($current{'defaults'}) eq 'HASH') {
15617:                             unless ($changes{$provider}) {
15618:                                 foreach my $key (keys(%{$confhash{$provider}{'defaults'}})) {
15619:                                     unless ($confhash{$provider}{'defaults'}{$key} eq $current{'defaults'}{$key}) {
15620:                                         $changes{$provider} = 1;
15621:                                         last;
15622:                                     }
15623:                                 }
15624:                             }
15625:                             unless ($changes{$provider}) {
15626:                                 foreach my $key (keys(%{$current{'defaults'}})) {
15627:                                     unless ($current{'defaults'}{$key} eq $confhash{$provider}{'defaults'}{$key}) {
15628:                                         $changes{$provider} = 1;
15629:                                         last;
15630:                                     }
15631:                                 }
15632:                             }
15633:                         } elsif (keys(%{$confhash{$provider}{'defaults'}})) {
15634:                             $changes{$provider} = 1;
15635:                         }
15636:                     }
15637:                 }
15638:             }
15639:             if (ref($crsconf{$provider}) eq 'ARRAY') {
15640:                 if (@{$crsconf{$provider}} > 0) {
15641:                     $confhash{$provider}{'crsconf'} = [];
15642:                     my @checked = &Apache::loncommon::get_env_multiple('form.proctoring_crsconf_'.$provider);
15643:                     foreach my $crsfield (@{$crsconf{$provider}}) {
15644:                         if (grep(/^\Q$crsfield\E$/,@checked)) {
15645:                             push(@{$confhash{$provider}{'crsconf'}},$crsfield);
15646:                         }
15647:                     }
15648:                     if (ref($current{'crsconf'}) eq 'ARRAY') {
15649:                         unless ($changes{$provider}) {  
15650:                             my @new = sort(@{$confhash{$provider}{'crsconf'}});
15651:                             my @old = sort(@{$current{'crsconf'}});
15652:                             my @diffs = &Apache::loncommon::compare_arrays(\@new,\@old);
15653:                             if (@diffs) {
15654:                                 $changes{$provider} = 1;
15655:                             }
15656:                         }
15657:                     } elsif (@{$confhash{$provider}{'crsconf'}}) {
15658:                         $changes{$provider} = 1;
15659:                     }
15660:                 }
15661:             }
15662:             if ($showroles) {
15663:                 $confhash{$provider}{'roles'} = {};
15664:                 foreach my $role (@courseroles) {
15665:                     my $poss = $env{'form.proctoring_roles_'.$role.'_'.$provider};
15666:                     if (grep(/^\Q$poss\E$/,@ltiroles)) {
15667:                         $confhash{$provider}{'roles'}{$role} = $poss;
15668:                     }
15669:                 }
15670:                 unless ($changes{$provider}) {
15671:                     if (ref($current{'roles'}) eq 'HASH') {
15672:                         foreach my $role (keys(%{$current{'roles'}})) {
15673:                             unless ($current{'roles'}{$role} eq $confhash{$provider}{'roles'}{$role}) {
15674:                                 $changes{$provider} = 1;
15675:                                 last
15676:                             }
15677:                         }
15678:                         unless ($changes{$provider}) {
15679:                             foreach my $role (keys(%{$confhash{$provider}{'roles'}})) {
15680:                                 unless ($confhash{$provider}{'roles'}{$role} eq $current{'roles'}{$role}) {
15681:                                     $changes{$provider} = 1;
15682:                                     last;
15683:                                 }
15684:                             }
15685:                         }
15686:                     } elsif (keys(%{$confhash{$provider}{'roles'}})) {
15687:                         $changes{$provider} = 1;
15688:                     }
15689:                 }
15690:             }
15691:             if (ref($current{'custom'}) eq 'HASH') {
15692:                 my @customdels = &Apache::loncommon::get_env_multiple('form.proctoring_customdel_'.$provider);
15693:                 foreach my $key (keys(%{$current{'custom'}})) {
15694:                     if (grep(/^\Q$key\E$/,@customdels)) {
15695:                         $changes{$provider} = 1;
15696:                     } else {
15697:                         $confhash{$provider}{'custom'}{$key} = $env{'form.proctoring_customval_'.$key.'_'.$provider};
15698:                         if ($confhash{$provider}{'custom'}{$key} ne $current{'custom'}{$key}) {
15699:                             $changes{$provider} = 1;
15700:                         }
15701:                     }
15702:                 }
15703:             }
15704:             if ($customadds{$provider}) {
15705:                 my $name = $env{'form.proctoring_custom_name_'.$provider};
15706:                 $name =~ s/(`)/'/g;
15707:                 $name =~ s/^\s+//;
15708:                 $name =~ s/\s+$//;
15709:                 my $value = $env{'form.proctoring_custom_value_'.$provider};
15710:                 $value =~ s/(`)/'/g;
15711:                 $value =~ s/^\s+//;
15712:                 $value =~ s/\s+$//;
15713:                 if ($name ne '') {
15714:                     $confhash{$provider}{'custom'}{$name} = $value;
15715:                     $changes{$provider} = 1;
15716:                 }
15717:             }
15718:         }
15719:     }
15720:     if (@allpos > 0) {
15721:         my $idx = 0;
15722:         foreach my $provider (@allpos) {
15723:             if ($provider ne '') {
15724:                 $confhash{$provider}{'order'} = $idx;
15725:                 unless ($changes{$provider}) {
15726:                     if (ref($domconfig{$action}) eq 'HASH') {
15727:                         if (ref($domconfig{$action}{$provider}) eq 'HASH') {
15728:                             if ($domconfig{$action}{$provider}{'order'} ne $idx) {
15729:                                 $changes{$provider} = 1;
15730:                             }
15731:                         }
15732:                     }
15733:                 }
15734:                 $idx ++;
15735:             }
15736:         }
15737:     }
15738:     my %proc_hash = (
15739:                           $action => { %confhash }
15740:                        );
15741:     my $putresult = &Apache::lonnet::put_dom('configuration',\%proc_hash,
15742:                                              $dom);
15743:     if ($putresult eq 'ok') {
15744:         my %proc_enchash = (
15745:                              $action => { %encconfhash }
15746:                          );
15747:         &Apache::lonnet::put_dom('encconfig',\%proc_enchash,$dom,undef,1);
15748:         if (keys(%changes) > 0) {
15749:             my $cachetime = 24*60*60;
15750:             my %procall = %confhash;
15751:             foreach my $provider (keys(%procall)) {
15752:                 if (ref($encconfhash{$provider}) eq 'HASH') {
15753:                     foreach my $key ('key','secret') {
15754:                         $procall{$provider}{$key} = $encconfhash{$provider}{$key};
15755:                     }
15756:                 }
15757:             }
15758:             &Apache::lonnet::do_cache_new('proctoring',$dom,\%procall,$cachetime);
15759:             if (ref($lastactref) eq 'HASH') {
15760:                 $lastactref->{'proctoring'} = 1;
15761:             }
15762:             $resulttext = &mt('Configuration for Provider(s) with changes:').'<ul>';
15763:             my %bynum;
15764:             foreach my $provider (sort(keys(%changes))) {
15765:                 my $position = $confhash{$provider}{'order'};
15766:                 $bynum{$position} = $provider;
15767:             }
15768:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
15769:                 my $provider = $bynum{$pos};
15770:                 my %lt = &proctoring_titles($provider);
15771:                 my %fieldtitles = &proctoring_fieldtitles($provider);
15772:                 if (!$confhash{$provider}{'available'}) {
15773:                     $resulttext .= '<li>'.&mt('Proctoring integration unavailable for: [_1]','<b>'.$providernames{$provider}.'</b>').'</li>';
15774:                 } else {
15775:                     $resulttext .= '<li>'.&mt('Proctoring integration available for: [_1]','<b>'.$providernames{$provider}.'</b>');
15776:                     if ($confhash{$provider}{'image'}) {
15777:                         $resulttext .= '&nbsp;'.
15778:                                        '<img src="'.$confhash{$provider}{'image'}.'"'.
15779:                                        ' alt="'.&mt('Proctoring icon').'" />';
15780:                     }
15781:                     $resulttext .= '<ul>';
15782:                     my $position = $pos + 1;
15783:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
15784:                     foreach my $key ('version','sigmethod','url','lifetime') {
15785:                         if ($confhash{$provider}{$key} ne '') {
15786:                             $resulttext .= '<li>'.$lt{$key}.':&nbsp;'.$confhash{$provider}{$key}.'</li>';
15787:                         }
15788:                     }
15789:                     if ($encconfhash{$provider}{'key'} ne '') {
15790:                         $resulttext .= '<li>'.$lt{'key'}.':&nbsp;'.$encconfhash{$provider}{'key'}.'</li>';
15791:                     }
15792:                     if ($encconfhash{$provider}{'secret'} ne '') {
15793:                         $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;';
15794:                         my $num = length($encconfhash{$provider}{'secret'});
15795:                         $resulttext .= ('*'x$num).'</li>';
15796:                     }
15797:                     my (@fields,$showroles);
15798:                     if (ref($requserfields{$provider}) eq 'ARRAY') {
15799:                         push(@fields,@{$requserfields{$provider}});
15800:                     }
15801:                     if (ref($confhash{$provider}{'fields'}) eq 'ARRAY') {
15802:                         push(@fields,@{$confhash{$provider}{'fields'}});
15803:                     } elsif (ref($confhash{$provider}{'fields'}) eq 'HASH') {
15804:                         push(@fields,(keys(%{$confhash{$provider}{'fields'}})));
15805:                     }
15806:                     if (@fields) {
15807:                         if (grep(/^roles$/,@fields)) {
15808:                             $showroles = 1;
15809:                         }
15810:                         $resulttext .= '<li>'.$lt{'udsl'}.':&nbsp;"'.
15811:                                        join('", "', map { $lt{$_}; } @fields).'"</li>';
15812:                     }
15813:                     if (ref($requserfields{$provider}) eq 'ARRAY') {
15814:                         if (grep(/^user$/,@{$requserfields{$provider}})) {
15815:                             if ($confhash{$provider}{'incdom'}) {
15816:                                 $resulttext .= '<li>'.&mt('[_1] sent as [_2]',$lt{'user'},$lt{'uname:dom'}).'</li>';
15817:                             } else { 
15818:                                 $resulttext .= '<li>'.&mt('[_1] sent as [_2]',$lt{'user'},$lt{'username'}).'</li>';
15819:                             }
15820:                         }
15821:                     }
15822:                     if (ref($confhash{$provider}{'defaults'}) eq 'ARRAY') {
15823:                         if (@{$confhash{$provider}{'defaults'}} > 0) {
15824:                             $resulttext .= '<li>'.$lt{'defa'};
15825:                             foreach my $field (@{$confhash{$provider}{'defaults'}}) {
15826:                                 $resulttext .= ' "'.$fieldtitles{$field}.'",';
15827:                             }
15828:                             $resulttext =~ s/,$//;
15829:                             $resulttext .= '</li>';
15830:                         }
15831:                     } elsif (ref($confhash{$provider}{'defaults'}) eq 'HASH') {
15832:                         if (keys(%{$confhash{$provider}{'defaults'}})) {
15833:                             $resulttext .= '<li>'.$lt{'defa'}.':&nbsp;<ul>';
15834:                             foreach my $key (sort(keys(%{$confhash{$provider}{'defaults'}}))) {
15835:                                 if ($confhash{$provider}{'defaults'}{$key} ne '') {
15836:                                     $resulttext .= '<li>'.$fieldtitles{$key}.' = '.$confhash{$provider}{'defaults'}{$key}.'</li>';
15837:                                 }
15838:                             }
15839:                             $resulttext .= '</ul></li>';
15840:                         }
15841:                     }
15842:                     if (ref($crsconf{$provider}) eq 'ARRAY') {
15843:                         if (@{$crsconf{$provider}} > 0) {
15844:                             $resulttext .= '<li>'.&mt('Configurable in course:');
15845:                             my $numconfig = 0;
15846:                             if (ref($confhash{$provider}{'crsconf'}) eq 'ARRAY') {
15847:                                 if (@{$confhash{$provider}{'crsconf'}} > 0) {
15848:                                     foreach my $field (@{$confhash{$provider}{'crsconf'}}) {
15849:                                         $numconfig ++;
15850:                                         if ($provider eq 'examity') {
15851:                                             $resulttext .= ' "'.$lt{'crs'.$field}.'",';
15852:                                         } else {
15853:                                             $resulttext .= ' "'.$fieldtitles{$field}.'",';
15854:                                         }
15855:                                     }
15856:                                     $resulttext =~ s/,$//;
15857:                                 }
15858:                             }
15859:                             if (!$numconfig) {
15860:                                 $resulttext .= '&nbsp;'.&mt('None');
15861:                             }
15862:                             $resulttext .= '</li>';
15863:                         }
15864:                     }
15865:                     if ($showroles) {
15866:                         if (ref($confhash{$provider}{'roles'}) eq 'HASH') {
15867:                             my $rolemaps;
15868:                             foreach my $role (@courseroles) {
15869:                                 if ($confhash{$provider}{'roles'}{$role}) {
15870:                                     $rolemaps .= ('&nbsp;'x2).&Apache::lonnet::plaintext($role,'Course').'='.
15871:                                                  $confhash{$provider}{'roles'}{$role}.',';
15872:                                 }
15873:                             }
15874:                             if ($rolemaps) {
15875:                                 $rolemaps =~ s/,$//;
15876:                                 $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
15877:                             }
15878:                         }
15879:                     }
15880:                     if (ref($confhash{$provider}{'custom'}) eq 'HASH') {
15881:                         my $customlist;
15882:                         if (keys(%{$confhash{$provider}{'custom'}})) {
15883:                             foreach my $key (sort(keys(%{$confhash{$provider}{'custom'}}))) {
15884:                                 $customlist .= $key.'='.$confhash{$provider}{'custom'}{$key}.', ';
15885:                             }
15886:                             $customlist =~ s/,$//;
15887:                         }
15888:                         if ($customlist) {
15889:                             $resulttext .= '<li>'.&mt('Custom items').': '.$customlist.'</li>';
15890:                         }
15891:                     } 
15892:                     $resulttext .= '</ul></li>';
15893:                 }
15894:             }
15895:             $resulttext .= '</ul>';
15896:         } else {
15897:             $resulttext = &mt('No changes made.');
15898:         }
15899:     } else {
15900:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
15901:     }
15902:     if ($errors) {
15903:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
15904:                        $errors.'</ul>';
15905:     }
15906:     return $resulttext;
15907: }
15908: 
15909: sub process_proctoring_image {
15910:     my ($r,$dom,$confname,$caller,$provider,$configuserok,$switchserver,$author_ok) = @_;
15911:     my $filename = $env{'form.'.$caller.'.filename'};
15912:     my ($error,$url);
15913:     my ($width,$height) = (21,21);
15914:     if ($configuserok eq 'ok') {
15915:         if ($switchserver) {
15916:             $error = &mt('Upload of Remote Proctoring Provider icon is not permitted to this server: [_1]',
15917:                          $switchserver);
15918:         } elsif ($author_ok eq 'ok') {
15919:             my ($result,$imageurl,$madethumb) =
15920:                 &publishlogo($r,'upload',$caller,$dom,$confname,
15921:                              "proctoring/$provider/icon",$width,$height);
15922:             if ($result eq 'ok') {
15923:                 if ($madethumb) {
15924:                     my ($path,$imagefile) = ($imageurl =~ m{^(.+)/([^/]+)$});
15925:                     my $imagethumb = "$path/tn-".$imagefile;
15926:                     $url = $imagethumb;
15927:                 } else {
15928:                     $url = $imageurl;
15929:                 }
15930:             } else {
15931:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
15932:             }
15933:         } else {
15934:             $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);
15935:         }
15936:     } else {
15937:         $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);
15938:     }
15939:     return ($url,$error);
15940: }
15941: 
15942: sub modify_lti {
15943:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
15944:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
15945:     my ($newid,@allpos,%changes,%confhash,%encconfig,$errors,$resulttext);
15946:     my (%posslti,%posslticrs,%posscrstype);
15947:     my @courseroles = ('cc','in','ta','ep','st');
15948:     my @ltiroles = qw(Learner Instructor ContentDeveloper TeachingAssistant Mentor Member Manager Administrator);
15949:     my @lticourseroles = qw(Instructor TeachingAssistant Mentor Learner);
15950:     my @coursetypes = ('official','unofficial','community','textbook','placement','lti');
15951:     my %coursetypetitles = &Apache::lonlocal::texthash (
15952:                                official   => 'Official',
15953:                                unofficial => 'Unofficial',
15954:                                community  => 'Community',
15955:                                textbook   => 'Textbook',
15956:                                placement  => 'Placement Test',
15957:                                lti        => 'LTI Provider',
15958:     );
15959:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
15960:     my %lt = &lti_names();
15961:     map { $posslti{$_} = 1; } @ltiroles;
15962:     map { $posslticrs{$_} = 1; } @lticourseroles;
15963:     map { $posscrstype{$_} = 1; } @coursetypes;
15964: 
15965:     my %menutitles = &ltimenu_titles();
15966: 
15967:     my (%currltisec,%secchanges,%newltisec,%newltienc,%keyset,%newkeyset);
15968:     $newltisec{'private'}{'keys'} = [];
15969:     $newltisec{'encrypt'} = {};
15970:     $newltisec{'rules'} = {};
15971:     $newltisec{'linkprot'} = {};
15972:     if (ref($domconfig{'ltisec'}) eq 'HASH') {
15973:         %currltisec = %{$domconfig{'ltisec'}};
15974:         if (ref($currltisec{'linkprot'}) eq 'HASH') {
15975:             foreach my $id (keys(%{$currltisec{'linkprot'}})) {
15976:                 unless ($id =~ /^\d+$/) {
15977:                     delete($currltisec{'linkprot'}{$id});
15978:                 }
15979:             }
15980:         }
15981:         if (ref($currltisec{'private'}) eq 'HASH') {
15982:             if (ref($currltisec{'private'}{'keys'}) eq 'ARRAY') {
15983:                 $newltisec{'private'}{'keys'} = $currltisec{'private'}{'keys'};
15984:                 map { $keyset{$_} = 1; } @{$currltisec{'private'}{'keys'}};
15985:             }
15986:         }
15987:     }
15988:     foreach my $item ('crs','dom','consumers') {
15989:         my $formelement;
15990:         if ($item eq 'consumers') { 
15991:             $formelement = 'form.ltisec_'.$item;
15992:         } else {
15993:             $formelement = 'form.ltisec_'.$item.'linkprot';
15994:         }
15995:         if ($env{$formelement}) {
15996:             $newltisec{'encrypt'}{$item} = 1;
15997:             if (ref($currltisec{'encrypt'}) eq 'HASH') {
15998:                 unless ($currltisec{'encrypt'}{$item}) {
15999:                     $secchanges{'encrypt'} = 1;
16000:                 }
16001:             } else {
16002:                 $secchanges{'encrypt'} = 1;
16003:             }
16004:         } elsif (ref($currltisec{'encrypt'}) eq 'HASH') {
16005:             if ($currltisec{'encrypt'}{$item}) {
16006:                 $secchanges{'encrypt'} = 1;
16007:             }
16008:         }
16009:     }
16010:     unless (exists($currltisec{'rules'})) {
16011:         $currltisec{'rules'} = {};
16012:     }
16013:     &password_rule_changes('secrets',$newltisec{'rules'},$currltisec{'rules'},\%secchanges);
16014: 
16015:     my @ids=&Apache::lonnet::current_machine_ids();
16016:     my %servers = &Apache::lonnet::get_servers($dom,'library');
16017:    
16018:     foreach my $hostid (keys(%servers)) {
16019:         if (($hostid ne '') && (grep(/^\Q$hostid\E$/,@ids))) {
16020:             my $newkey;
16021:             my $keyitem = 'form.ltisec_privkey_'.$hostid;
16022:             if (exists($env{$keyitem})) {
16023:                 $env{$keyitem} =~ s/(`)/'/g;
16024:                 if ($keyset{$hostid}) {
16025:                     if ($env{'form.ltisec_changeprivkey_'.$hostid}) {
16026:                         if ($env{$keyitem} ne '') {
16027:                             $secchanges{'private'} = 1;
16028:                             $newkeyset{$hostid} = $env{$keyitem};
16029:                         }
16030:                     }
16031:                 } elsif ($env{$keyitem} ne '') {
16032:                     unless (grep(/^\Q$hostid\E$/,@{$newltisec{'private'}{'keys'}})) { 
16033:                         push(@{$newltisec{'private'}{'keys'}},$hostid);
16034:                     }
16035:                     $secchanges{'private'} = 1;
16036:                     $newkeyset{$hostid} = $env{$keyitem};
16037:                 }
16038:             }
16039:         }
16040:     }
16041: 
16042:     my (%linkprotchg,$linkprotoutput,$is_home);
16043:     my $proterror = &Apache::courseprefs::process_linkprot($dom,'',$currltisec{'linkprot'},
16044:                                                            \%linkprotchg,'domain');
16045:     my $home = &Apache::lonnet::domain($dom,'primary');
16046:     unless (($home eq 'no_host') || ($home eq '')) {
16047:         my @ids=&Apache::lonnet::current_machine_ids();
16048:         foreach my $id (@ids) { if ($id eq $home) { $is_home=1; } }
16049:     }
16050: 
16051:     if (keys(%linkprotchg)) {
16052:         $secchanges{'linkprot'} = 1;
16053:         my %oldlinkprot;
16054:         if (ref($currltisec{'linkprot'}) eq 'HASH') {
16055:             %oldlinkprot = %{$currltisec{'linkprot'}};
16056:         }
16057:         foreach my $id (keys(%linkprotchg)) {
16058:             if (ref($linkprotchg{$id}) eq 'HASH') {
16059:                 foreach my $inner (keys(%{$linkprotchg{$id}})) {
16060:                     if (($inner eq 'secret') || ($inner eq 'key')) {
16061:                         if ($is_home) {
16062:                             $newltienc{$id}{$inner} = $linkprotchg{$id}{$inner};
16063:                         }
16064:                     }
16065:                 }
16066:             } else {
16067:                 $newltisec{'linkprot'}{$id} = $linkprotchg{$id};
16068:             }
16069:         }
16070:         $linkprotoutput = &Apache::courseprefs::store_linkprot($dom,'','domain',\%linkprotchg,\%oldlinkprot);
16071:         if (keys(%linkprotchg)) {
16072:             %{$newltisec{'linkprot'}} = %linkprotchg;
16073:         }
16074:     }
16075:     if (ref($currltisec{'linkprot'}) eq 'HASH') {
16076:         foreach my $id (%{$currltisec{'linkprot'}}) {
16077:             next if ($id !~ /^\d+$/);
16078:             unless (exists($linkprotchg{$id})) {
16079:                 if (ref($currltisec{'linkprot'}{$id}) eq 'HASH') {
16080:                     foreach my $inner (keys(%{$currltisec{'linkprot'}{$id}})) {
16081:                         if (($inner eq 'secret') || ($inner eq 'key')) {
16082:                             if ($is_home) {
16083:                                 $newltienc{$id}{$inner} = $currltisec{'linkprot'}{$id}{$inner};
16084:                             }
16085:                         } else {
16086:                             $newltisec{'linkprot'}{$id}{$inner} = $currltisec{'linkprot'}{$id}{$inner};
16087:                         }
16088:                     }
16089:                 } else {
16090:                     $newltisec{'linkprot'}{$id} = $currltisec{'linkprot'}{$id};
16091:                 }
16092:             }
16093:         }
16094:     }
16095:     if ($proterror) {
16096:         $errors .= '<li>'.$proterror.'</li>';
16097:     }
16098:     my (@items,%deletions,%itemids);
16099:     if ($env{'form.lti_add'}) {
16100:         my $consumer = $env{'form.lti_consumer_add'};
16101:         $consumer =~ s/(`)/'/g;
16102:         ($newid,my $error) = &get_lti_id($dom,$consumer);
16103:         if ($newid) {
16104:             $itemids{'add'} = $newid;
16105:             push(@items,'add');
16106:             $changes{$newid} = 1;
16107:         } else {
16108:             my $error = &mt('Failed to acquire unique ID for new LTI configuration');
16109:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
16110:         }
16111:     }
16112:     if (ref($domconfig{$action}) eq 'HASH') {
16113:         my @todelete = &Apache::loncommon::get_env_multiple('form.lti_del');
16114:         if (@todelete) {
16115:             map { $deletions{$_} = 1; } @todelete;
16116:         }
16117:         my $maxnum = $env{'form.lti_maxnum'};
16118:         for (my $i=0; $i<$maxnum; $i++) {
16119:             my $itemid = $env{'form.lti_id_'.$i};
16120:             $itemid =~ s/\D+//g;
16121:             if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
16122:                 if ($deletions{$itemid}) {
16123:                     $changes{$itemid} = $domconfig{$action}{$itemid}{'consumer'};
16124:                 } else {
16125:                     push(@items,$i);
16126:                     $itemids{$i} = $itemid;
16127:                 }
16128:             }
16129:         }
16130:     }
16131:     foreach my $idx (@items) {
16132:         my $itemid = $itemids{$idx};
16133:         next unless ($itemid);
16134:         my $position = $env{'form.lti_pos_'.$itemid};
16135:         $position =~ s/\D+//g;
16136:         if ($position ne '') {
16137:             $allpos[$position] = $itemid;
16138:         }
16139:         foreach my $item ('consumer','key','secret','lifetime','requser','crsinc') {
16140:             my $formitem = 'form.lti_'.$item.'_'.$idx;
16141:             $env{$formitem} =~ s/(`)/'/g;
16142:             if ($item eq 'lifetime') {
16143:                 $env{$formitem} =~ s/[^\d.]//g;
16144:             }
16145:             if ($env{$formitem} ne '') {
16146:                 if (($item eq 'key') || ($item eq 'secret')) {
16147:                     $encconfig{$itemid}{$item} = $env{$formitem};
16148:                 } else {
16149:                     $confhash{$itemid}{$item} = $env{$formitem};
16150:                     unless (($idx eq 'add') || ($changes{$itemid})) {
16151:                         if ($domconfig{$action}{$itemid}{$item} ne $confhash{$itemid}{$item}) {
16152:                             $changes{$itemid} = 1;
16153:                         }
16154:                     }
16155:                 }
16156:             }
16157:         }
16158:         if ($env{'form.lti_version_'.$idx} eq 'LTI-1p0') {
16159:             $confhash{$itemid}{'version'} = $env{'form.lti_version_'.$idx};
16160:         }
16161:         if ($confhash{$itemid}{'requser'}) {
16162:             if ($env{'form.lti_mapuser_'.$idx} eq 'sourcedid') {
16163:                 $confhash{$itemid}{'mapuser'} = 'lis_person_sourcedid';
16164:             } elsif ($env{'form.lti_mapuser_'.$idx} eq 'email') {
16165:                 $confhash{$itemid}{'mapuser'} = 'lis_person_contact_email_primary';
16166:             } elsif ($env{'form.lti_mapuser_'.$idx} eq 'other') {
16167:                 my $mapuser = $env{'form.lti_customuser_'.$idx};
16168:                 $mapuser =~ s/(`)/'/g;
16169:                 $mapuser =~ s/^\s+|\s+$//g;
16170:                 $confhash{$itemid}{'mapuser'} = $mapuser;
16171:             }
16172:             my @possmakeuser = &Apache::loncommon::get_env_multiple('form.lti_makeuser_'.$idx);
16173:             my @makeuser;
16174:             foreach my $ltirole (sort(@possmakeuser)) {
16175:                 if ($posslti{$ltirole}) {
16176:                     push(@makeuser,$ltirole);
16177:                 }
16178:             }
16179:             $confhash{$itemid}{'makeuser'} = \@makeuser;
16180:             if (@makeuser) {
16181:                 my $lcauth = $env{'form.lti_lcauth_'.$idx};
16182:                 if ($lcauth =~ /^(internal|krb4|krb5|localauth)$/) {
16183:                     $confhash{$itemid}{'lcauth'} = $lcauth;
16184:                     if ($lcauth ne 'internal') {
16185:                         my $lcauthparm = $env{'form.lti_lcauthparm_'.$idx};
16186:                         $lcauthparm =~ s/^(\s+|\s+)$//g;
16187:                         $lcauthparm =~ s/`//g;
16188:                         if ($lcauthparm ne '') {
16189:                             $confhash{$itemid}{'lcauthparm'} = $lcauthparm;
16190:                         }
16191:                     }
16192:                 } else {
16193:                     $confhash{$itemid}{'lcauth'} = 'lti';
16194:                 }
16195:             }
16196:             my @possinstdata =  &Apache::loncommon::get_env_multiple('form.lti_instdata_'.$idx);
16197:             if (@possinstdata) {
16198:                 foreach my $field (@possinstdata) {
16199:                     if (exists($fieldtitles{$field})) {
16200:                         push(@{$confhash{$itemid}{'instdata'}});
16201:                     }
16202:                 }
16203:             }
16204:             if ($env{'form.lti_callback_'.$idx}) {
16205:                 if ($env{'form.lti_callbackparam_'.$idx}) {
16206:                     my $callback = $env{'form.lti_callbackparam_'.$idx};
16207:                     $callback =~ s/^\s+|\s+$//g;
16208:                     $confhash{$itemid}{'callback'} = $callback;
16209:                 }
16210:             }
16211:             foreach my $field ('topmenu','inlinemenu') {
16212:                 if ($env{'form.lti_'.$field.'_'.$idx}) {
16213:                     $confhash{$itemid}{$field} = 1;
16214:                 }
16215:             }
16216:             if ($env{'form.lti_topmenu_'.$idx} || $env{'form.lti_inlinemenu_'.$idx}) {
16217:                 $confhash{$itemid}{lcmenu} = [];
16218:                 my @possmenu = &Apache::loncommon::get_env_multiple('form.lti_menuitem_'.$idx);
16219:                 foreach my $field (@possmenu) {
16220:                     if (exists($menutitles{$field})) {
16221:                         if ($field eq 'grades') {
16222:                             next unless ($env{'form.lti_inlinemenu_'.$idx});
16223:                         }
16224:                         push(@{$confhash{$itemid}{lcmenu}},$field);
16225:                     }
16226:                 }
16227:             }
16228:             if ($confhash{$itemid}{'crsinc'}) {
16229:                 if (($env{'form.lti_mapcrs_'.$idx} eq 'course_offering_sourcedid') ||
16230:                     ($env{'form.lti_mapcrs_'.$idx} eq 'context_id'))  {
16231:                     $confhash{$itemid}{'mapcrs'} = $env{'form.lti_mapcrs_'.$idx};
16232:                 } elsif ($env{'form.lti_mapcrs_'.$idx} eq 'other') {
16233:                     my $mapcrs = $env{'form.lti_mapcrsfield_'.$idx}; 
16234:                     $mapcrs =~ s/(`)/'/g;
16235:                     $mapcrs =~ s/^\s+|\s+$//g;
16236:                     $confhash{$itemid}{'mapcrs'} = $mapcrs;
16237:                 }
16238:                 my @posstypes = &Apache::loncommon::get_env_multiple('form.lti_mapcrstype_'.$idx);
16239:                 my @crstypes;
16240:                 foreach my $type (sort(@posstypes)) {
16241:                     if ($posscrstype{$type}) {
16242:                         push(@crstypes,$type);
16243:                     }
16244:                 }
16245:                 $confhash{$itemid}{'mapcrstype'} = \@crstypes;
16246:                 if ($env{'form.lti_storecrs_'.$idx}) {
16247:                     $confhash{$itemid}{'storecrs'} = 1;
16248:                 }       
16249:                 if ($env{'form.lti_makecrs_'.$idx}) {
16250:                     $confhash{$itemid}{'makecrs'} = 1;
16251:                 }
16252:                 foreach my $ltirole (@lticourseroles) {
16253:                     my $possrole = $env{'form.lti_maprole_'.$ltirole.'_'.$idx};
16254:                     if (grep(/^\Q$possrole\E$/,@courseroles)) {
16255:                         $confhash{$itemid}{'maproles'}{$ltirole} = $possrole;
16256:                     }
16257:                 }
16258:                 my @possenroll = &Apache::loncommon::get_env_multiple('form.lti_selfenroll_'.$idx);
16259:                 my @selfenroll;
16260:                 foreach my $type (sort(@possenroll)) {
16261:                     if ($posslticrs{$type}) {
16262:                         push(@selfenroll,$type);
16263:                     }
16264:                 }
16265:                 $confhash{$itemid}{'selfenroll'} = \@selfenroll;
16266:                 if ($env{'form.lti_crssec_'.$idx}) {
16267:                     if ($env{'form.lti_crssecsrc_'.$idx} eq 'course_section_sourcedid') {
16268:                         $confhash{$itemid}{'section'} = $env{'form.lti_crssecsrc_'.$idx};
16269:                     } elsif ($env{'form.lti_crssecsrc_'.$idx} eq 'other') {
16270:                         my $section = $env{'form.lti_customsection_'.$idx};
16271:                         $section =~ s/(`)/'/g;
16272:                         $section =~ s/^\s+|\s+$//g;
16273:                         if ($section ne '') {
16274:                             $confhash{$itemid}{'section'} = $section;
16275:                         }
16276:                     }
16277:                 }
16278:                 foreach my $field ('passback','roster') {
16279:                     if ($env{'form.lti_'.$field.'_'.$idx}) {
16280:                         $confhash{$itemid}{$field} = 1;
16281:                     }
16282:                 }
16283:                 if ($env{'form.lti_passback_'.$idx}) {
16284:                     if ($env{'form.lti_passbackformat_'.$idx} eq '1.0') {
16285:                         $confhash{$itemid}{'passbackformat'} = '1.0';
16286:                     } else {
16287:                         $confhash{$itemid}{'passbackformat'} = '1.1';
16288:                     }
16289:                 }
16290:             }
16291:             unless (($idx eq 'add') || ($changes{$itemid})) {
16292:                 if ($confhash{$itemid}{'crsinc'}) {
16293:                     foreach my $field ('mapcrs','storecrs','makecrs','section','passback','roster') {
16294:                         if ($domconfig{$action}{$itemid}{$field} ne $confhash{$itemid}{$field}) {
16295:                             $changes{$itemid} = 1;
16296:                         }
16297:                     }
16298:                     unless ($changes{$itemid}) {
16299:                         if ($domconfig{$action}{$itemid}{'passback'} eq $confhash{$itemid}{'passback'}) {
16300:                             if ($domconfig{$action}{$itemid}{'passbackformat'} ne $confhash{$itemid}{'passbackformat'}) {
16301:                                 $changes{$itemid} = 1;
16302:                             }
16303:                         }
16304:                     }
16305:                     foreach my $field ('mapcrstype','selfenroll') {
16306:                         unless ($changes{$itemid}) {
16307:                             if (ref($domconfig{$action}{$itemid}{$field}) eq 'ARRAY') {
16308:                                 if (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
16309:                                     my @diffs = &Apache::loncommon::compare_arrays($domconfig{$action}{$itemid}{$field},
16310:                                                                                    $confhash{$itemid}{$field});
16311:                                     if (@diffs) {
16312:                                         $changes{$itemid} = 1;
16313:                                     }
16314:                                 } elsif (@{$domconfig{$action}{$itemid}{$field}} > 0) {
16315:                                     $changes{$itemid} = 1;
16316:                                 }
16317:                             } elsif (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
16318:                                 if (@{$confhash{$itemid}{$field}} > 0) {
16319:                                     $changes{$itemid} = 1;
16320:                                 }
16321:                             }
16322:                         }
16323:                     }
16324:                     unless ($changes{$itemid}) {
16325:                         if (ref($domconfig{$action}{$itemid}{'maproles'}) eq 'HASH') {
16326:                             if (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
16327:                                 foreach my $ltirole (keys(%{$domconfig{$action}{$itemid}{'maproles'}})) {
16328:                                     if ($domconfig{$action}{$itemid}{'maproles'}{$ltirole} ne 
16329:                                         $confhash{$itemid}{'maproles'}{$ltirole}) {
16330:                                         $changes{$itemid} = 1;
16331:                                         last;
16332:                                     }
16333:                                 }
16334:                                 unless ($changes{$itemid}) {
16335:                                     foreach my $ltirole (keys(%{$confhash{$itemid}{'maproles'}})) {
16336:                                         if ($confhash{$itemid}{'maproles'}{$ltirole} ne 
16337:                                             $domconfig{$action}{$itemid}{'maproles'}{$ltirole}) {
16338:                                             $changes{$itemid} = 1;
16339:                                             last;
16340:                                         }
16341:                                     }
16342:                                 }
16343:                             } elsif (keys(%{$domconfig{$action}{$itemid}{'maproles'}}) > 0) {
16344:                                 $changes{$itemid} = 1;
16345:                             }
16346:                         } elsif (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
16347:                             unless ($changes{$itemid}) {
16348:                                 if (keys(%{$confhash{$itemid}{'maproles'}}) > 0) {
16349:                                     $changes{$itemid} = 1;
16350:                                 }
16351:                             }
16352:                         }
16353:                     }
16354:                 }
16355:                 unless ($changes{$itemid}) {
16356:                     foreach my $field ('mapuser','lcauth','lcauthparm','topmenu','inlinemenu','callback') {
16357:                         if ($domconfig{$action}{$itemid}{$field} ne $confhash{$itemid}{$field}) {
16358:                             $changes{$itemid} = 1;
16359:                         }
16360:                     }
16361:                     unless ($changes{$itemid}) {
16362:                         foreach my $field ('makeuser','lcmenu') {
16363:                             if (ref($domconfig{$action}{$itemid}{$field}) eq 'ARRAY') {
16364:                                 if (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
16365:                                     my @diffs = &Apache::loncommon::compare_arrays($domconfig{$action}{$itemid}{$field},
16366:                                                                                    $confhash{$itemid}{$field});
16367:                                     if (@diffs) {
16368:                                         $changes{$itemid} = 1;
16369:                                     }
16370:                                 } elsif (@{$domconfig{$action}{$itemid}{$field}} > 0) {
16371:                                     $changes{$itemid} = 1;
16372:                                 }
16373:                             } elsif (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
16374:                                 if (@{$confhash{$itemid}{$field}} > 0) {
16375:                                     $changes{$itemid} = 1;
16376:                                 }
16377:                             }
16378:                         }
16379:                     }
16380:                 }
16381:             }
16382:         }
16383:     }
16384:     if (@allpos > 0) {
16385:         my $idx = 0;
16386:         foreach my $itemid (@allpos) {
16387:             if ($itemid ne '') {
16388:                 $confhash{$itemid}{'order'} = $idx;
16389:                 if (ref($domconfig{$action}) eq 'HASH') {
16390:                     if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
16391:                         if ($domconfig{$action}{$itemid}{'order'} ne $idx) {
16392:                             $changes{$itemid} = 1;
16393:                         }
16394:                     }
16395:                 }
16396:                 $idx ++;
16397:             }
16398:         }
16399:     }
16400:     my %ltihash = (
16401:                       $action => { %confhash }
16402:                   );
16403:     my %ltienchash = (
16404:                          $action => { %encconfig }
16405:                      );
16406:     if (keys(%secchanges)) {
16407:         $ltihash{'ltisec'} = \%newltisec;
16408:         if ($secchanges{'linkprot'}) {
16409:             if ($is_home) {
16410:                 $ltienchash{'linkprot'} = \%newltienc;
16411:             }
16412:         }
16413:     }
16414:     my $putresult = &Apache::lonnet::put_dom('configuration',\%ltihash,$dom);
16415:     if ($putresult eq 'ok') {
16416:         my %keystore;
16417:         if (keys(%secchanges)) {
16418:             if ($secchanges{'private'}) {
16419:                 my $who = &escape($env{'user.name'}.':'.$env{'user.domain'});
16420:                 foreach my $hostid (keys(%newkeyset)) {
16421:                     my $storehash = {
16422:                                        key => $newkeyset{$hostid},
16423:                                        who => $env{'user.name'}.':'.$env{'user.domain'},
16424:                                     };
16425:                     $keystore{$hostid} = &Apache::lonnet::store_dom($storehash,'lti','private',
16426:                                                                     $dom,$hostid);
16427:                 }
16428:             }
16429:             if (ref($lastactref) eq 'HASH') {
16430:                 if (($secchanges{'encrypt'}) || ($secchanges{'private'})) {
16431:                     $lastactref->{'domdefaults'} = 1;
16432:                 }
16433:             }
16434:         }
16435:         &Apache::lonnet::put_dom('encconfig',\%ltienchash,$dom,undef,1);
16436:         if ((keys(%changes) == 0) && (keys(%secchanges) == 0)) {
16437:             return &mt('No changes made.');
16438:         }
16439:         $resulttext = &mt('Changes made:').'<ul>';
16440:         if (keys(%secchanges) > 0) {
16441:             foreach my $item (keys(%secchanges)) {
16442:                 if ($item eq 'encrypt') {
16443:                     my %encrypted = (
16444:                               crs  => {
16445:                                         on => &mt('Encryption of stored link protection secrets defined in courses enabled'),
16446:                                         off => &mt('Encryption of stored link protection secrets defined in courses disabled'),
16447:                                       },
16448:                               dom => {
16449:                                        on => &mt('Encryption of stored link protection secrets defined in domain enabled'),
16450:                                        off => &mt('Encryption of stored link protection secrets defined in domain disabled'),
16451:                                      },
16452:                               consumers => {
16453:                                              on => &mt('Encryption of stored consumer secrets defined in domain enabled'),
16454:                                              off => &mt('Encryption of stored consumer secrets defined in domain disabled'),
16455:                                            },
16456:                             );
16457:                     foreach my $type ('crs','dom','consumers') {
16458:                         my $shown = $encrypted{$type}{'off'};
16459:                         if (ref($newltisec{$item}) eq 'HASH') {
16460:                             if ($newltisec{$item}{$type}) {
16461:                                 $shown = $encrypted{$type}{'on'}; 
16462:                             }
16463:                         }
16464:                         $resulttext .= '<li>'.$shown.'</li>';
16465:                     } 
16466:                 } elsif ($item eq 'rules') {
16467:                      my %titles = &Apache::lonlocal::texthash(
16468:                                       min   => 'Minimum password length',
16469:                                       max   => 'Maximum password length',
16470:                                       chars => 'Required characters',
16471:                      );
16472:                      foreach my $rule ('min','max') {
16473:                          if ($newltisec{rules}{$rule} eq '') {
16474:                              if ($rule eq 'min') {
16475:                                  $resulttext .= '<li>'.&mt('[_1] not set.',$titles{$rule});
16476:                                                 ' '.&mt('Default of [_1] will be used',
16477:                                                             $Apache::lonnet::passwdmin).'</li>';
16478:                              } else {
16479:                                  $resulttext .= '<li>'.&mt('[_1] set to none',$titles{$rule}).'</li>';
16480:                              }
16481:                          } else {
16482:                              $resulttext .= '<li>'.&mt('[_1] set to [_2]',$titles{$rule},$newltisec{rules}{$rule}).'</li>';
16483:                          }
16484:                      }
16485:                      if (ref($newltisec{'rules'}{'chars'}) eq 'ARRAY') {
16486:                          if (@{$newltisec{'rules'}{'chars'}} > 0) {
16487:                              my %rulenames = &Apache::lonlocal::texthash(
16488:                                                  uc => 'At least one upper case letter',
16489:                                                  lc => 'At least one lower case letter',
16490:                                                  num => 'At least one number',
16491:                                                  spec => 'At least one non-alphanumeric',
16492:                                              );
16493:                              my $needed = '<ul><li>'.
16494:                                           join('</li><li>',map {$rulenames{$_} } @{$newltisec{'rules'}{'chars'}}).
16495:                                           '</li></ul>';
16496:                              $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$titles{'chars'},$needed).'</li>';
16497:                          } else {
16498:                              $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
16499:                          }
16500:                      } else {
16501:                          $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
16502:                      }
16503:                 } elsif ($item eq 'private') {
16504:                     if (keys(%newkeyset)) {
16505:                         foreach my $hostid (sort(keys(%newkeyset))) {
16506:                             if ($keystore{$hostid} eq 'ok') {
16507:                                 $resulttext .= '<li>'.&mt('Encryption key for storage of shared secrets saved for [_1]',$hostid).'</li>';
16508:                             }
16509:                         }
16510:                     }
16511:                 } elsif ($item eq 'linkprot') {
16512:                     $resulttext .= $linkprotoutput;
16513:                 }
16514:             }
16515:         }
16516:         if (keys(%changes) > 0) {
16517:             my $cachetime = 24*60*60;
16518:             my %ltiall = %confhash;
16519:             foreach my $id (keys(%ltiall)) {
16520:                 if (ref($encconfig{$id}) eq 'HASH') {
16521:                     foreach my $item ('key','secret') {
16522:                         $ltiall{$id}{$item} = $encconfig{$id}{$item};
16523:                     }
16524:                 }
16525:             }
16526:             &Apache::lonnet::do_cache_new('lti',$dom,\%ltiall,$cachetime);
16527:             if (ref($lastactref) eq 'HASH') {
16528:                 $lastactref->{'lti'} = 1;
16529:             }
16530:             my %bynum;
16531:             foreach my $itemid (sort(keys(%changes))) {
16532:                 my $position = $confhash{$itemid}{'order'};
16533:                 $bynum{$position} = $itemid;
16534:             }
16535:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
16536:                 my $itemid = $bynum{$pos};
16537:                 if (ref($confhash{$itemid}) ne 'HASH') {
16538:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
16539:                 } else {
16540:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'consumer'}.'</b><ul>';
16541:                     my $position = $pos + 1;
16542:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
16543:                     foreach my $item ('version','lifetime') {
16544:                         if ($confhash{$itemid}{$item} ne '') {
16545:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{$item}.'</li>';
16546:                         }
16547:                     }
16548:                     if ($encconfig{$itemid}{'key'} ne '') {
16549:                         $resulttext .= '<li>'.$lt{'key'}.':&nbsp;'.$encconfig{$itemid}{'key'}.'</li>';
16550:                     }
16551:                     if ($encconfig{$itemid}{'secret'} ne '') {
16552:                         $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;';
16553:                         my $num = length($encconfig{$itemid}{'secret'});
16554:                         $resulttext .= ('*'x$num).'</li>';
16555:                     }
16556:                     if ($confhash{$itemid}{'requser'}) {
16557:                         if ($confhash{$itemid}{'callback'}) {
16558:                             $resulttext .= '<li>'.&mt('Callback setting').': '.$confhash{$itemid}{'callback'}.'</li>';
16559:                         } else {
16560:                             $resulttext .= '<li>'.&mt('Callback to logout LON-CAPA on log out from Consumer').'</li>';
16561:                         }
16562:                         if ($confhash{$itemid}{'mapuser'}) {
16563:                             my $shownmapuser;
16564:                             if ($confhash{$itemid}{'mapuser'} eq 'lis_person_sourcedid') {
16565:                                 $shownmapuser = $lt{'sourcedid'}.' (lis_person_sourcedid)';
16566:                             } elsif ($confhash{$itemid}{'mapuser'} eq 'lis_person_contact_email_primary') {
16567:                                 $shownmapuser = $lt{'email'}.' (lis_person_contact_email_primary)';
16568:                             } else {
16569:                                 $shownmapuser = &mt('Other').' ('.$confhash{$itemid}{'mapuser'}.')';
16570:                             }
16571:                             $resulttext .= '<li>'.&mt('LON-CAPA username').': '.$shownmapuser.'</li>';
16572:                         }
16573:                         if (ref($confhash{$itemid}{'makeuser'}) eq 'ARRAY') {
16574:                             if (@{$confhash{$itemid}{'makeuser'}} > 0) { 
16575:                                 $resulttext .= '<li>'.&mt('Following roles may create user accounts: [_1]',
16576:                                                           join(', ',@{$confhash{$itemid}{'makeuser'}})).'<br />';
16577:                                 if ($confhash{$itemid}{'lcauth'} eq 'lti') {
16578:                                     $resulttext .= &mt('New users will only be able to authenticate via LTI').'</li>';
16579:                                 } else {
16580:                                     $resulttext .= &mt('New users will be assigned LON-CAPA authentication: [_1]',
16581:                                                        $confhash{$itemid}{'lcauth'});
16582:                                     if ($confhash{$itemid}{'lcauth'} eq 'internal') {
16583:                                         $resulttext .= '; '.&mt('a randomly generated password will be created');
16584:                                     } elsif ($confhash{$itemid}{'lcauth'} eq 'localauth') {
16585:                                         if ($confhash{$itemid}{'lcauthparm'} ne '') {
16586:                                             $resulttext .= ' '.&mt('with argument: [_1]',$confhash{$itemid}{'lcauthparm'});
16587:                                         }
16588:                                     } else {
16589:                                         $resulttext .= '; '.&mt('Kerberos domain: [_1]',$confhash{$itemid}{'lcauthparm'});
16590:                                     }
16591:                                 }
16592:                                 $resulttext .= '</li>';
16593:                             } else {
16594:                                 $resulttext .= '<li>'.&mt('User account creation not permitted.').'</li>';
16595:                             }
16596:                         }
16597:                         if (ref($confhash{$itemid}{'instdata'}) eq 'ARRAY') {
16598:                             if (@{$confhash{$itemid}{'instdata'}} > 0) {
16599:                                 $resulttext .= '<li>'.&mt('Institutional data will be used when creating a new user for: [_1]',
16600:                                                           join(', ',map { $fieldtitles{$_}; } @{$confhash{$itemid}{'instdata'}})).'</li>';
16601:                             } else {
16602:                                 $resulttext .= '<li>'.&mt('No institutional data used when creating a new user.').'</li>';
16603:                             }
16604:                         }
16605:                         foreach my $item ('topmenu','inlinemenu') {
16606:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;';
16607:                             if ($confhash{$itemid}{$item}) {
16608:                                 $resulttext .= &mt('Yes');
16609:                             } else {
16610:                                 $resulttext .= &mt('No');
16611:                             }
16612:                             $resulttext .= '</li>';
16613:                         }
16614:                         if (ref($confhash{$itemid}{'lcmenu'}) eq 'ARRAY') {
16615:                             if (@{$confhash{$itemid}{'lcmenu'}} > 0) {
16616:                                 $resulttext .= '<li>'.&mt('Menu items:').' '.
16617:                                                join(', ', map { $menutitles{$_}; } (@{$confhash{$itemid}{'lcmenu'}})).'</li>';
16618:                             } else {
16619:                                 $resulttext .= '<li>'.&mt('No menu items displayed in header or online menu').'</li>';
16620:                             }
16621:                         }
16622:                         if ($confhash{$itemid}{'crsinc'}) {
16623:                             if (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
16624:                                 my $rolemaps;
16625:                                 foreach my $role (@ltiroles) {
16626:                                     if ($confhash{$itemid}{'maproles'}{$role}) {
16627:                                         $rolemaps .= ('&nbsp;'x2).$role.'='.
16628:                                                      &Apache::lonnet::plaintext($confhash{$itemid}{'maproles'}{$role},
16629:                                                                                 'Course').',';
16630:                                     }
16631:                                 }
16632:                                 if ($rolemaps) {
16633:                                     $rolemaps =~ s/,$//;
16634:                                     $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
16635:                                 }
16636:                             }
16637:                             if ($confhash{$itemid}{'mapcrs'}) {
16638:                                 $resulttext .= '<li>'.&mt('Unique course identifier').': '.$confhash{$itemid}{'mapcrs'}.'</li>';
16639:                             }
16640:                             if (ref($confhash{$itemid}{'mapcrstype'}) eq 'ARRAY') {
16641:                                 if (@{$confhash{$itemid}{'mapcrstype'}} > 0) {
16642:                                     $resulttext .= '<li>'.&mt('Mapping for the following LON-CAPA course types: [_1]',
16643:                                                    join(', ',map { $coursetypetitles{$_}; } @coursetypes)).
16644:                                                    '</li>';
16645:                                 } else {
16646:                                     $resulttext .= '<li>'.&mt('No mapping to LON-CAPA courses').'</li>';
16647:                                 }
16648:                             }
16649:                             if ($confhash{$itemid}{'storecrs'}) {
16650:                                 $resulttext .= '<li>'.&mt('Store mapping of course identifier to LON-CAPA CourseID').': '.$confhash{$itemid}{'storecrs'}.'</li>';
16651:                             }
16652:                             if ($confhash{$itemid}{'makecrs'}) {
16653:                                 $resulttext .= '<li>'.&mt('Instructor may create course (if absent).').'</li>';
16654:                             } else {
16655:                                 $resulttext .= '<li>'.&mt('Instructor may not create course (if absent).').'</li>';
16656:                             }
16657:                             if (ref($confhash{$itemid}{'selfenroll'}) eq 'ARRAY') {
16658:                                 if (@{$confhash{$itemid}{'selfenroll'}} > 0) {
16659:                                     $resulttext .= '<li>'.&mt('Self-enrollment for following roles: [_1]',
16660:                                                               join(', ',@{$confhash{$itemid}{'selfenroll'}})).
16661:                                                    '</li>';
16662:                                 } else {
16663:                                     $resulttext .= '<li>'.&mt('Self-enrollment not permitted').'</li>';
16664:                                 }
16665:                             }
16666:                             if ($confhash{$itemid}{'section'}) {
16667:                                 if ($confhash{$itemid}{'section'} eq 'course_section_sourcedid') {
16668:                                     $resulttext .= '<li>'.&mt('User section from standard field:').
16669:                                                          ' (course_section_sourcedid)'.'</li>';  
16670:                                 } else {
16671:                                     $resulttext .= '<li>'.&mt('User section from:').' '.
16672:                                                           $confhash{$itemid}{'section'}.'</li>';
16673:                                 }
16674:                             } else {
16675:                                 $resulttext .= '<li>'.&mt('No section assignment').'</li>';
16676:                             }
16677:                             foreach my $item ('passback','roster','topmenu','inlinemenu') {
16678:                                 $resulttext .= '<li>'.$lt{$item}.':&nbsp;';
16679:                                 if ($confhash{$itemid}{$item}) {
16680:                                     $resulttext .= &mt('Yes');
16681:                                     if ($item eq 'passback') {
16682:                                         if ($confhash{$itemid}{'passbackformat'} eq '1.0') {
16683:                                             $resulttext .= '&nbsp;('.&mt('Outcomes Extension (1.0)').')';
16684:                                         } elsif ($confhash{$itemid}{'passbackformat'} eq '1.1') {
16685:                                             $resulttext .= '&nbsp;('.&mt('Outcomes Service (1.1)').')';
16686:                                         }
16687:                                     }
16688:                                 } else {
16689:                                     $resulttext .= &mt('No');
16690:                                 }
16691:                                 $resulttext .= '</li>';
16692:                             }
16693:                             if (ref($confhash{$itemid}{'lcmenu'}) eq 'ARRAY') {
16694:                                 if (@{$confhash{$itemid}{'lcmenu'}} > 0) {
16695:                                     $resulttext .= '<li>'.&mt('Menu items:').' '.
16696:                                                    join(', ', map { $menutitles{$_}; } (@{$confhash{$itemid}{'lcmenu'}})).'</li>'; 
16697:                                 } else {
16698:                                     $resulttext .= '<li>'.&mt('No menu items displayed in header or online menu').'</li>'; 
16699:                                 }
16700:                             }
16701:                         }
16702:                     }
16703:                     $resulttext .= '</ul></li>';
16704:                 }
16705:             }
16706:         }
16707:         $resulttext .= '</ul>';
16708:     } else {
16709:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
16710:     }
16711:     if ($errors) {
16712:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
16713:                        $errors.'</ul>';
16714:     }
16715:     return $resulttext;
16716: }
16717: 
16718: sub get_lti_id {
16719:     my ($domain,$consumer) = @_;
16720:     # get lock on lti db
16721:     my $lockhash = {
16722:                       lock => $env{'user.name'}.
16723:                               ':'.$env{'user.domain'},
16724:                    };
16725:     my $tries = 0;
16726:     my $gotlock = &Apache::lonnet::newput_dom('lti',$lockhash,$domain);
16727:     my ($id,$error);
16728: 
16729:     while (($gotlock ne 'ok') && ($tries<10)) {
16730:         $tries ++;
16731:         sleep (0.1);
16732:         $gotlock = &Apache::lonnet::newput_dom('lti',$lockhash,$domain);
16733:     }
16734:     if ($gotlock eq 'ok') {
16735:         my %currids = &Apache::lonnet::dump_dom('lti',$domain);
16736:         if ($currids{'lock'}) {
16737:             delete($currids{'lock'});
16738:             if (keys(%currids)) {
16739:                 my @curr = sort { $a <=> $b } keys(%currids);
16740:                 if ($curr[-1] =~ /^\d+$/) {
16741:                     $id = 1 + $curr[-1];
16742:                 }
16743:             } else {
16744:                 $id = 1;
16745:             }
16746:             if ($id) {
16747:                 unless (&Apache::lonnet::newput_dom('lti',{ $id => $consumer },$domain) eq 'ok') {
16748:                     $error = 'nostore';
16749:                 }
16750:             } else {
16751:                 $error = 'nonumber';
16752:             }
16753:         }
16754:         my $dellockoutcome = &Apache::lonnet::del_dom('lti',['lock'],$domain);
16755:     } else {
16756:         $error = 'nolock';
16757:     }
16758:     return ($id,$error);
16759: }
16760: 
16761: sub modify_autoenroll {
16762:     my ($dom,$lastactref,%domconfig) = @_;
16763:     my ($resulttext,%changes);
16764:     my %currautoenroll;
16765:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
16766:         foreach my $key (keys(%{$domconfig{'autoenroll'}})) {
16767:             $currautoenroll{$key} = $domconfig{'autoenroll'}{$key};
16768:         }
16769:     }
16770:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
16771:     my %title = ( run => 'Auto-enrollment active',
16772:                   sender => 'Sender for notification messages',
16773:                   coowners => 'Automatic assignment of co-ownership to instructors of record (institutional data)',
16774:                   autofailsafe => 'Failsafe for no drops if institutional data missing for a section');
16775:     my @offon = ('off','on');
16776:     my $sender_uname = $env{'form.sender_uname'};
16777:     my $sender_domain = $env{'form.sender_domain'};
16778:     if ($sender_domain eq '') {
16779:         $sender_uname = '';
16780:     } elsif ($sender_uname eq '') {
16781:         $sender_domain = '';
16782:     }
16783:     my $coowners = $env{'form.autoassign_coowners'};
16784:     my $autofailsafe = $env{'form.autoenroll_autofailsafe'};
16785:     $autofailsafe =~ s{^\s+|\s+$}{}g;
16786:     if ($autofailsafe =~ /\D/) {
16787:         undef($autofailsafe);
16788:     }
16789:     my $failsafe = $env{'form.autoenroll_failsafe'};
16790:     unless (($failsafe eq 'zero') || ($failsafe eq 'any')) {
16791:         $failsafe = 'off';
16792:         undef($autofailsafe);
16793:     }
16794:     my %autoenrollhash =  (
16795:                        autoenroll => { 'run' => $env{'form.autoenroll_run'},
16796:                                        'sender_uname' => $sender_uname,
16797:                                        'sender_domain' => $sender_domain,
16798:                                        'co-owners' => $coowners,
16799:                                        'autofailsafe' => $autofailsafe,
16800:                                        'failsafe' => $failsafe,
16801:                                 }
16802:                      );
16803:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autoenrollhash,
16804:                                              $dom);
16805:     if ($putresult eq 'ok') {
16806:         if (exists($currautoenroll{'run'})) {
16807:              if ($currautoenroll{'run'} ne $env{'form.autoenroll_run'}) {
16808:                  $changes{'run'} = 1;
16809:              }
16810:         } elsif ($autorun) {
16811:             if ($env{'form.autoenroll_run'} ne '1') {
16812:                  $changes{'run'} = 1;
16813:             }
16814:         }
16815:         if ($currautoenroll{'sender_uname'} ne $sender_uname) {
16816:             $changes{'sender'} = 1;
16817:         }
16818:         if ($currautoenroll{'sender_domain'} ne $sender_domain) {
16819:             $changes{'sender'} = 1;
16820:         }
16821:         if ($currautoenroll{'co-owners'} ne '') {
16822:             if ($currautoenroll{'co-owners'} ne $coowners) {
16823:                 $changes{'coowners'} = 1;
16824:             }
16825:         } elsif ($coowners) {
16826:             $changes{'coowners'} = 1;
16827:         }
16828:         if ($currautoenroll{'autofailsafe'} ne $autofailsafe) {
16829:             $changes{'autofailsafe'} = 1;
16830:         }
16831:         if ($currautoenroll{'failsafe'} ne $failsafe) {
16832:             $changes{'failsafe'} = 1;
16833:         }
16834:         if (keys(%changes) > 0) {
16835:             $resulttext = &mt('Changes made:').'<ul>';
16836:             if ($changes{'run'}) {
16837:                 $resulttext .= '<li>'.&mt("$title{'run'} set to $offon[$env{'form.autoenroll_run'}]").'</li>';
16838:             }
16839:             if ($changes{'sender'}) {
16840:                 if ($sender_uname eq '' || $sender_domain eq '') {
16841:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to default (course owner).").'</li>';
16842:                 } else {
16843:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to [_1]",$sender_uname.':'.$sender_domain).'</li>';
16844:                 }
16845:             }
16846:             if ($changes{'coowners'}) {
16847:                 $resulttext .= '<li>'.&mt("$title{'coowners'} set to $offon[$env{'form.autoassign_coowners'}]").'</li>';
16848:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
16849:                 if (ref($lastactref) eq 'HASH') {
16850:                     $lastactref->{'domainconfig'} = 1;
16851:                 }
16852:             }
16853:             if ($changes{'autofailsafe'}) {
16854:                 if ($autofailsafe ne '') {
16855:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section set to: [_1]',$autofailsafe).'</li>';
16856:                 } else {
16857:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section not in use').'</li>';
16858:                 }
16859:             }
16860:             if ($changes{'failsafe'}) {
16861:                 if ($failsafe eq 'off') {
16862:                     unless ($changes{'autofailsafe'}) {
16863:                         $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section not in use').'</li>';
16864:                     }
16865:                 } elsif ($failsafe eq 'zero') {
16866:                     $resulttext .= '<li>'.&mt('Failsafe applies if retrieved section enrollment is zero').'</li>';
16867:                 } else {
16868:                     $resulttext .= '<li>'.&mt('Failsafe applies if retrieved section enrollment is zero or greater').'</li>';
16869:                 }
16870:             }
16871:             if (($changes{'autofailsafe'}) || ($changes{'failsafe'})) {
16872:                 &Apache::lonnet::get_domain_defaults($dom,1);
16873:                 if (ref($lastactref) eq 'HASH') {
16874:                     $lastactref->{'domdefaults'} = 1;
16875:                 }
16876:             }
16877:             $resulttext .= '</ul>';
16878:         } else {
16879:             $resulttext = &mt('No changes made to auto-enrollment settings');
16880:         }
16881:     } else {
16882:         $resulttext = '<span class="LC_error">'.
16883: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
16884:     }
16885:     return $resulttext;
16886: }
16887: 
16888: sub modify_autoupdate {
16889:     my ($dom,%domconfig) = @_;
16890:     my ($resulttext,%currautoupdate,%fields,%changes);
16891:     if (ref($domconfig{'autoupdate'}) eq 'HASH') {
16892:         foreach my $key (keys(%{$domconfig{'autoupdate'}})) {
16893:             $currautoupdate{$key} = $domconfig{'autoupdate'}{$key};
16894:         }
16895:     }
16896:     my @offon = ('off','on');
16897:     my %title = &Apache::lonlocal::texthash (
16898:                     run        => 'Auto-update:',
16899:                     classlists => 'Updates to user information in classlists?',
16900:                     unexpired  => 'Skip updates for users without active or future roles?',
16901:                     lastactive => 'Skip updates for inactive users?',
16902:                 );
16903:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
16904:     my %fieldtitles = &Apache::lonlocal::texthash (
16905:                         id => 'Student/Employee ID',
16906:                         permanentemail => 'E-mail address',
16907:                         lastname => 'Last Name',
16908:                         firstname => 'First Name',
16909:                         middlename => 'Middle Name',
16910:                         generation => 'Generation',
16911:                       );
16912:     $othertitle = &mt('All users');
16913:     if (keys(%{$usertypes}) >  0) {
16914:         $othertitle = &mt('Other users');
16915:     }
16916:     foreach my $key (keys(%env)) {
16917:         if ($key =~ /^form\.updateable_(.+)_([^_]+)$/) {
16918:             my ($usertype,$item) = ($1,$2);
16919:             if (grep(/^\Q$item\E$/,keys(%fieldtitles))) {
16920:                 if ($usertype eq 'default') {   
16921:                     push(@{$fields{$1}},$2);
16922:                 } elsif (ref($types) eq 'ARRAY') {
16923:                     if (grep(/^\Q$usertype\E$/,@{$types})) {
16924:                         push(@{$fields{$1}},$2);
16925:                     }
16926:                 }
16927:             }
16928:         }
16929:     }
16930:     my @lockablenames = &Apache::loncommon::get_env_multiple('form.lockablenames');
16931:     @lockablenames = sort(@lockablenames);
16932:     if (ref($currautoupdate{'lockablenames'}) eq 'ARRAY') {
16933:         my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
16934:         if (@changed) {
16935:             $changes{'lockablenames'} = 1;
16936:         }
16937:     } else {
16938:         if (@lockablenames) {
16939:             $changes{'lockablenames'} = 1;
16940:         }
16941:     }
16942:     my %updatehash = (
16943:                       autoupdate => { run => $env{'form.autoupdate_run'},
16944:                                       classlists => $env{'form.classlists'},
16945:                                       unexpired  => $env{'form.unexpired'},
16946:                                       fields => {%fields},
16947:                                       lockablenames => \@lockablenames,
16948:                                     }
16949:                      );
16950:     my $lastactivedays;
16951:     if ($env{'form.lastactive'}) {
16952:         $lastactivedays = $env{'form.lastactivedays'};
16953:         $lastactivedays =~ s/^\s+|\s+$//g;
16954:         unless ($lastactivedays =~ /^\d+$/) {
16955:             undef($lastactivedays);
16956:             $env{'form.lastactive'} = 0;
16957:         }
16958:     }
16959:     $updatehash{'autoupdate'}{'lastactive'} = $lastactivedays;
16960:     foreach my $key (keys(%currautoupdate)) {
16961:         if (($key eq 'run') || ($key eq 'classlists') || ($key eq 'unexpired') || ($key eq 'lastactive')) {
16962:             if (exists($updatehash{autoupdate}{$key})) {
16963:                 if ($currautoupdate{$key} ne $updatehash{autoupdate}{$key}) {
16964:                     $changes{$key} = 1;
16965:                 }
16966:             }
16967:         } elsif ($key eq 'fields') {
16968:             if (ref($currautoupdate{$key}) eq 'HASH') {
16969:                 foreach my $item (@{$types},'default') {
16970:                     if (ref($currautoupdate{$key}{$item}) eq 'ARRAY') {
16971:                         my $change = 0;
16972:                         foreach my $type (@{$currautoupdate{$key}{$item}}) {
16973:                             if (!exists($fields{$item})) {
16974:                                 $change = 1;
16975:                                 last;
16976:                             } elsif (ref($fields{$item}) eq 'ARRAY') {
16977:                                 if (!grep(/^\Q$type\E$/,@{$fields{$item}})) {
16978:                                     $change = 1;
16979:                                     last;
16980:                                 }
16981:                             }
16982:                         }
16983:                         if ($change) {
16984:                             push(@{$changes{$key}},$item);
16985:                         }
16986:                     } 
16987:                 }
16988:             }
16989:         } elsif ($key eq 'lockablenames') {
16990:             if (ref($currautoupdate{$key}) eq 'ARRAY') {
16991:                 my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
16992:                 if (@changed) {
16993:                     $changes{'lockablenames'} = 1;
16994:                 }
16995:             } else {
16996:                 if (@lockablenames) {
16997:                     $changes{'lockablenames'} = 1;
16998:                 }
16999:             }
17000:         }
17001:     }
17002:     unless (grep(/^\Qlockablenames\E$/,keys(%currautoupdate))) {
17003:         if (@lockablenames) {
17004:             $changes{'lockablenames'} = 1;
17005:         }
17006:     }
17007:     unless (grep(/^unexpired$/,keys(%currautoupdate))) {
17008:         if ($updatehash{'autoupdate'}{'unexpired'}) {
17009:             $changes{'unexpired'} = 1;
17010:         }
17011:     }
17012:     unless (grep(/^lastactive$/,keys(%currautoupdate))) {
17013:         if ($updatehash{'autoupdate'}{'lastactive'} ne '') {
17014:             $changes{'lastactive'} = 1;
17015:         }
17016:     }
17017:     foreach my $item (@{$types},'default') {
17018:         if (defined($fields{$item})) {
17019:             if (ref($currautoupdate{'fields'}) eq 'HASH') {
17020:                 if (ref($currautoupdate{'fields'}{$item}) eq 'ARRAY') {
17021:                     my $change = 0;
17022:                     if (ref($fields{$item}) eq 'ARRAY') {
17023:                         foreach my $type (@{$fields{$item}}) {
17024:                             if (!grep(/^\Q$type\E$/,@{$currautoupdate{'fields'}{$item}})) {
17025:                                 $change = 1;
17026:                                 last;
17027:                             }
17028:                         }
17029:                     }
17030:                     if ($change) {
17031:                         push(@{$changes{'fields'}},$item);
17032:                     }
17033:                 } else {
17034:                     push(@{$changes{'fields'}},$item);
17035:                 }
17036:             } else {
17037:                 push(@{$changes{'fields'}},$item);
17038:             }
17039:         }
17040:     }
17041:     my $putresult = &Apache::lonnet::put_dom('configuration',\%updatehash,
17042:                                              $dom);
17043:     if ($putresult eq 'ok') {
17044:         if (keys(%changes) > 0) {
17045:             $resulttext = &mt('Changes made:').'<ul>';
17046:             foreach my $key (sort(keys(%changes))) {
17047:                 if ($key eq 'lockablenames') {
17048:                     $resulttext .= '<li>';
17049:                     if (@lockablenames) {
17050:                         $usertypes->{'default'} = $othertitle;
17051:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update), available for the following affiliations:").' '.
17052:                                    join(', ', map { $usertypes->{$_}; } @lockablenames).'</li>';
17053:                     } else {
17054:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update) is unavailable.");
17055:                     }
17056:                     $resulttext .= '</li>';
17057:                 } elsif (ref($changes{$key}) eq 'ARRAY') {
17058:                     foreach my $item (@{$changes{$key}}) {
17059:                         my @newvalues;
17060:                         foreach my $type (@{$fields{$item}}) {
17061:                             push(@newvalues,$fieldtitles{$type});
17062:                         }
17063:                         my $newvaluestr;
17064:                         if (@newvalues > 0) {
17065:                             $newvaluestr = join(', ',@newvalues);
17066:                         } else {
17067:                             $newvaluestr = &mt('none');
17068:                         }
17069:                         if ($item eq 'default') {
17070:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$othertitle,$newvaluestr).'</li>';
17071:                         } else {
17072:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$usertypes->{$item},$newvaluestr).'</li>';
17073:                         }
17074:                     }
17075:                 } else {
17076:                     my $newvalue;
17077:                     if ($key eq 'run') {
17078:                         $newvalue = $offon[$env{'form.autoupdate_run'}];
17079:                     } elsif ($key eq 'lastactive') {
17080:                         $newvalue = $offon[$env{'form.lastactive'}];
17081:                         unless ($lastactivedays eq '') {
17082:                             $newvalue .= '; '.&mt('inactive = no activity in last [quant,_1,day]',$lastactivedays);
17083:                         }
17084:                     } else {
17085:                         $newvalue = $offon[$env{'form.'.$key}];
17086:                     }
17087:                     $resulttext .= '<li>'.&mt("[_1] set to $newvalue",$title{$key}).'</li>';
17088:                 }
17089:             }
17090:             $resulttext .= '</ul>';
17091:         } else {
17092:             $resulttext = &mt('No changes made to autoupdates');
17093:         }
17094:     } else {
17095:         $resulttext = '<span class="LC_error">'.
17096: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
17097:     }
17098:     return $resulttext;
17099: }
17100: 
17101: sub modify_autocreate {
17102:     my ($dom,%domconfig) = @_;
17103:     my ($resulttext,%changes,%currautocreate,%newvals,%autocreatehash);
17104:     if (ref($domconfig{'autocreate'}) eq 'HASH') {
17105:         foreach my $key (keys(%{$domconfig{'autocreate'}})) {
17106:             $currautocreate{$key} = $domconfig{'autocreate'}{$key};
17107:         }
17108:     }
17109:     my %title= ( xml => 'Auto-creation of courses in XML course description files',
17110:                  req => 'Auto-creation of validated requests for official courses',
17111:                  xmldc => 'Identity of course creator of courses from XML files',
17112:                );
17113:     my @types = ('xml','req');
17114:     foreach my $item (@types) {
17115:         $newvals{$item} = $env{'form.autocreate_'.$item};
17116:         $newvals{$item} =~ s/\D//g;
17117:         $newvals{$item} = 0 if ($newvals{$item} eq '');
17118:     }
17119:     $newvals{'xmldc'} = $env{'form.autocreate_xmldc'};
17120:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
17121:     unless (exists($domcoords{$newvals{'xmldc'}})) {
17122:         $newvals{'xmldc'} = '';
17123:     } 
17124:     %autocreatehash =  (
17125:                         autocreate => { xml => $newvals{'xml'},
17126:                                         req => $newvals{'req'},
17127:                                       }
17128:                        );
17129:     if ($newvals{'xmldc'} ne '') {
17130:         $autocreatehash{'autocreate'}{'xmldc'} = $newvals{'xmldc'};
17131:     }
17132:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autocreatehash,
17133:                                              $dom);
17134:     if ($putresult eq 'ok') {
17135:         my @items = @types;
17136:         if ($newvals{'xml'}) {
17137:             push(@items,'xmldc');
17138:         }
17139:         foreach my $item (@items) {
17140:             if (exists($currautocreate{$item})) {
17141:                 if ($currautocreate{$item} ne $newvals{$item}) {
17142:                     $changes{$item} = 1;
17143:                 }
17144:             } elsif ($newvals{$item}) {
17145:                 $changes{$item} = 1;
17146:             }
17147:         }
17148:         if (keys(%changes) > 0) {
17149:             my @offon = ('off','on'); 
17150:             $resulttext = &mt('Changes made:').'<ul>';
17151:             foreach my $item (@types) {
17152:                 if ($changes{$item}) {
17153:                     my $newtxt = $offon[$newvals{$item}];
17154:                     $resulttext .= '<li>'.
17155:                                    &mt("$title{$item} set to [_1]$newtxt [_2]",
17156:                                        '<b>','</b>').
17157:                                    '</li>';
17158:                 }
17159:             }
17160:             if ($changes{'xmldc'}) {
17161:                 my ($dcname,$dcdom) = split(':',$newvals{'xmldc'});
17162:                 my $newtxt = &Apache::loncommon::plainname($dcname,$dcdom);
17163:                 $resulttext .= '<li>'.&mt("$title{'xmldc'} set to [_1]",'<b>'.$newtxt.'</b>').'</li>'; 
17164:             }
17165:             $resulttext .= '</ul>';
17166:         } else {
17167:             $resulttext = &mt('No changes made to auto-creation settings');
17168:         }
17169:     } else {
17170:         $resulttext = '<span class="LC_error">'.
17171:             &mt('An error occurred: [_1]',$putresult).'</span>';
17172:     }
17173:     return $resulttext;
17174: }
17175: 
17176: sub modify_directorysrch {
17177:     my ($dom,$lastactref,%domconfig) = @_;
17178:     my ($resulttext,%changes);
17179:     my %currdirsrch;
17180:     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
17181:         foreach my $key (keys(%{$domconfig{'directorysrch'}})) {
17182:             $currdirsrch{$key} = $domconfig{'directorysrch'}{$key};
17183:         }
17184:     }
17185:     my %title = ( available => 'Institutional directory search available',
17186:                   localonly => 'Other domains can search institution',
17187:                   lcavailable => 'LON-CAPA directory search available',
17188:                   lclocalonly => 'Other domains can search LON-CAPA domain',
17189:                   searchby => 'Search types',
17190:                   searchtypes => 'Search latitude');
17191:     my @offon = ('off','on');
17192:     my @otherdoms = ('Yes','No');
17193: 
17194:     my @searchtypes = &Apache::loncommon::get_env_multiple('form.searchtypes');  
17195:     my @cansearch = &Apache::loncommon::get_env_multiple('form.cansearch');
17196:     my @searchby = &Apache::loncommon::get_env_multiple('form.searchby');
17197: 
17198:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
17199:     if (keys(%{$usertypes}) == 0) {
17200:         @cansearch = ('default');
17201:     } else {
17202:         if (ref($currdirsrch{'cansearch'}) eq 'ARRAY') {
17203:             foreach my $type (@{$currdirsrch{'cansearch'}}) {
17204:                 if (!grep(/^\Q$type\E$/,@cansearch)) {
17205:                     push(@{$changes{'cansearch'}},$type);
17206:                 }
17207:             }
17208:             foreach my $type (@cansearch) {
17209:                 if (!grep(/^\Q$type\E$/,@{$currdirsrch{'cansearch'}})) {
17210:                     push(@{$changes{'cansearch'}},$type);
17211:                 }
17212:             }
17213:         } else {
17214:             push(@{$changes{'cansearch'}},@cansearch);
17215:         }
17216:     }
17217: 
17218:     if (ref($currdirsrch{'searchby'}) eq 'ARRAY') {
17219:         foreach my $by (@{$currdirsrch{'searchby'}}) {
17220:             if (!grep(/^\Q$by\E$/,@searchby)) {
17221:                 push(@{$changes{'searchby'}},$by);
17222:             }
17223:         }
17224:         foreach my $by (@searchby) {
17225:             if (!grep(/^\Q$by\E$/,@{$currdirsrch{'searchby'}})) {
17226:                 push(@{$changes{'searchby'}},$by);
17227:             }
17228:         }
17229:     } else {
17230:         push(@{$changes{'searchby'}},@searchby);
17231:     }
17232: 
17233:     if (ref($currdirsrch{'searchtypes'}) eq 'ARRAY') {
17234:         foreach my $type (@{$currdirsrch{'searchtypes'}}) {
17235:             if (!grep(/^\Q$type\E$/,@searchtypes)) {
17236:                 push(@{$changes{'searchtypes'}},$type);
17237:             }
17238:         }
17239:         foreach my $type (@searchtypes) {
17240:             if (!grep(/^\Q$type\E$/,@{$currdirsrch{'searchtypes'}})) {
17241:                 push(@{$changes{'searchtypes'}},$type);
17242:             }
17243:         }
17244:     } else {
17245:         if (exists($currdirsrch{'searchtypes'})) {
17246:             foreach my $type (@searchtypes) {  
17247:                 if ($type ne $currdirsrch{'searchtypes'}) { 
17248:                     push(@{$changes{'searchtypes'}},$type);
17249:                 }
17250:             }
17251:             if (!grep(/^\Q$currdirsrch{'searchtypes'}\E/,@searchtypes)) {
17252:                 push(@{$changes{'searchtypes'}},$currdirsrch{'searchtypes'});
17253:             }   
17254:         } else {
17255:             push(@{$changes{'searchtypes'}},@searchtypes); 
17256:         }
17257:     }
17258: 
17259:     my %dirsrch_hash =  (
17260:             directorysrch => { available => $env{'form.dirsrch_available'},
17261:                                cansearch => \@cansearch,
17262:                                localonly => $env{'form.dirsrch_instlocalonly'},
17263:                                lclocalonly => $env{'form.dirsrch_domlocalonly'},
17264:                                lcavailable => $env{'form.dirsrch_domavailable'},
17265:                                searchby => \@searchby,
17266:                                searchtypes => \@searchtypes,
17267:                              }
17268:             );
17269:     my $putresult = &Apache::lonnet::put_dom('configuration',\%dirsrch_hash,
17270:                                              $dom);
17271:     if ($putresult eq 'ok') {
17272:         if (exists($currdirsrch{'available'})) {
17273:              if ($currdirsrch{'available'} ne $env{'form.dirsrch_available'}) {
17274:                  $changes{'available'} = 1;
17275:              }
17276:         } else {
17277:             if ($env{'form.dirsrch_available'} eq '1') {
17278:                 $changes{'available'} = 1;
17279:             }
17280:         }
17281:         if (exists($currdirsrch{'lcavailable'})) {
17282:             if ($currdirsrch{'lcavailable'} ne $env{'form.dirsrch_domavailable'}) {
17283:                 $changes{'lcavailable'} = 1;
17284:             }
17285:         } else {
17286:             if ($env{'form.dirsrch_lcavailable'} eq '1') {
17287:                 $changes{'lcavailable'} = 1;
17288:             }
17289:         }
17290:         if (exists($currdirsrch{'localonly'})) {
17291:             if ($currdirsrch{'localonly'} ne $env{'form.dirsrch_instlocalonly'}) {
17292:                 $changes{'localonly'} = 1;
17293:             }
17294:         } else {
17295:             if ($env{'form.dirsrch_instlocalonly'} eq '1') {
17296:                 $changes{'localonly'} = 1;
17297:             }
17298:         }
17299:         if (exists($currdirsrch{'lclocalonly'})) {
17300:             if ($currdirsrch{'lclocalonly'} ne $env{'form.dirsrch_domlocalonly'}) {
17301:                 $changes{'lclocalonly'} = 1;
17302:             }
17303:         } else {
17304:             if ($env{'form.dirsrch_domlocalonly'} eq '1') {
17305:                 $changes{'lclocalonly'} = 1;
17306:             }
17307:         }
17308:         if (keys(%changes) > 0) {
17309:             $resulttext = &mt('Changes made:').'<ul>';
17310:             if ($changes{'available'}) {
17311:                 $resulttext .= '<li>'.&mt("$title{'available'} set to: $offon[$env{'form.dirsrch_available'}]").'</li>';
17312:             }
17313:             if ($changes{'lcavailable'}) {
17314:                 $resulttext .= '<li>'.&mt("$title{'lcavailable'} set to: $offon[$env{'form.dirsrch_domavailable'}]").'</li>';
17315:             }
17316:             if ($changes{'localonly'}) {
17317:                 $resulttext .= '<li>'.&mt("$title{'localonly'} set to: $otherdoms[$env{'form.dirsrch_instlocalonly'}]").'</li>';
17318:             }
17319:             if ($changes{'lclocalonly'}) {
17320:                 $resulttext .= '<li>'.&mt("$title{'lclocalonly'} set to: $otherdoms[$env{'form.dirsrch_domlocalonly'}]").'</li>';
17321:             }
17322:             if (ref($changes{'cansearch'}) eq 'ARRAY') {
17323:                 my $chgtext;
17324:                 if (ref($usertypes) eq 'HASH') {
17325:                     if (keys(%{$usertypes}) > 0) {
17326:                         foreach my $type (@{$types}) {
17327:                             if (grep(/^\Q$type\E$/,@cansearch)) {
17328:                                 $chgtext .= $usertypes->{$type}.'; ';
17329:                             }
17330:                         }
17331:                         if (grep(/^default$/,@cansearch)) {
17332:                             $chgtext .= $othertitle;
17333:                         } else {
17334:                             $chgtext =~ s/\; $//;
17335:                         }
17336:                         $resulttext .=
17337:                             '<li>'.
17338:                             &mt("Users from domain '[_1]' permitted to search the institutional directory set to: [_2]",
17339:                                 '<span class="LC_cusr_emph">'.$dom.'</span>',$chgtext).
17340:                             '</li>';
17341:                     }
17342:                 }
17343:             }
17344:             if (ref($changes{'searchby'}) eq 'ARRAY') {
17345:                 my ($searchtitles,$titleorder) = &sorted_searchtitles();
17346:                 my $chgtext;
17347:                 foreach my $type (@{$titleorder}) {
17348:                     if (grep(/^\Q$type\E$/,@searchby)) {
17349:                         if (defined($searchtitles->{$type})) {
17350:                             $chgtext .= $searchtitles->{$type}.'; ';
17351:                         }
17352:                     }
17353:                 }
17354:                 $chgtext =~ s/\; $//;
17355:                 $resulttext .= '<li>'.&mt("$title{'searchby'} set to: [_1]",$chgtext).'</li>';
17356:             }
17357:             if (ref($changes{'searchtypes'}) eq 'ARRAY') {
17358:                 my ($srchtypes_desc,$srchtypeorder) = &sorted_searchtypes(); 
17359:                 my $chgtext;
17360:                 foreach my $type (@{$srchtypeorder}) {
17361:                     if (grep(/^\Q$type\E$/,@searchtypes)) {
17362:                         if (defined($srchtypes_desc->{$type})) {
17363:                             $chgtext .= $srchtypes_desc->{$type}.'; ';
17364:                         }
17365:                     }
17366:                 }
17367:                 $chgtext =~ s/\; $//;
17368:                 $resulttext .= '<li>'.&mt($title{'searchtypes'}.' set to: "[_1]"',$chgtext).'</li>';
17369:             }
17370:             $resulttext .= '</ul>';
17371:             &Apache::lonnet::do_cache_new('directorysrch',$dom,$dirsrch_hash{'directorysrch'},3600);
17372:             if (ref($lastactref) eq 'HASH') {
17373:                 $lastactref->{'directorysrch'} = 1;
17374:             }
17375:         } else {
17376:             $resulttext = &mt('No changes made to directory search settings');
17377:         }
17378:     } else {
17379:         $resulttext = '<span class="LC_error">'.
17380:                       &mt('An error occurred: [_1]',$putresult).'</span>';
17381:     }
17382:     return $resulttext;
17383: }
17384: 
17385: sub modify_contacts {
17386:     my ($dom,$lastactref,%domconfig) = @_;
17387:     my ($resulttext,%currsetting,%newsetting,%changes,%contacts_hash);
17388:     if (ref($domconfig{'contacts'}) eq 'HASH') {
17389:         foreach my $key (keys(%{$domconfig{'contacts'}})) {
17390:             $currsetting{$key} = $domconfig{'contacts'}{$key};
17391:         }
17392:     }
17393:     my (%others,%to,%bcc,%includestr,%includeloc);
17394:     my @contacts = ('supportemail','adminemail');
17395:     my @mailings = ('errormail','packagesmail','helpdeskmail','otherdomsmail',
17396:                     'lonstatusmail','requestsmail','updatesmail','idconflictsmail','hostipmail');
17397:     my @toggles = ('reporterrors','reportupdates','reportstatus');
17398:     my @lonstatus = ('threshold','sysmail','weights','excluded');
17399:     my ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
17400:     foreach my $type (@mailings) {
17401:         @{$newsetting{$type}} = 
17402:             &Apache::loncommon::get_env_multiple('form.'.$type);
17403:         foreach my $item (@contacts) {
17404:             if (grep(/^\Q$item\E$/,@{$newsetting{$type}})) {
17405:                 $contacts_hash{contacts}{$type}{$item} = 1;
17406:             } else {
17407:                 $contacts_hash{contacts}{$type}{$item} = 0;
17408:             }
17409:         }
17410:         $others{$type} = $env{'form.'.$type.'_others'};
17411:         $contacts_hash{contacts}{$type}{'others'} = $others{$type};
17412:         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
17413:             $bcc{$type} = $env{'form.'.$type.'_bcc'};
17414:             $contacts_hash{contacts}{$type}{'bcc'} = $bcc{$type};
17415:             if (($env{'form.'.$type.'_includestr'} ne '') && ($env{'form.'.$type.'_includeloc'} =~ /^s|b$/)) {
17416:                 $includestr{$type} = $env{'form.'.$type.'_includestr'};
17417:                 $includeloc{$type} = $env{'form.'.$type.'_includeloc'};
17418:                 $contacts_hash{contacts}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
17419:             }
17420:         }
17421:     }
17422:     foreach my $item (@contacts) {
17423:         $to{$item} = $env{'form.'.$item};
17424:         $contacts_hash{'contacts'}{$item} = $to{$item};
17425:     }
17426:     foreach my $item (@toggles) {
17427:         if ($env{'form.'.$item} =~ /^(0|1)$/) {
17428:             $contacts_hash{'contacts'}{$item} = $env{'form.'.$item};
17429:         }
17430:     }
17431:     my ($lonstatus_defs,$lonstatus_names) = &Apache::loncommon::lon_status_items();
17432:     foreach my $item (@lonstatus) {
17433:         if ($item eq 'excluded') {
17434:             my (%serverhomes,@excluded);
17435:             map { $serverhomes{$_} = 1; } values(%Apache::lonnet::serverhomeIDs);
17436:             my @possexcluded = &Apache::loncommon::get_env_multiple('form.errorexcluded');
17437:             if (@possexcluded) {
17438:                 foreach my $id (sort(@possexcluded)) {
17439:                     if ($serverhomes{$id}) {
17440:                         push(@excluded,$id);
17441:                     }
17442:                 }
17443:             }
17444:             if (@excluded) {
17445:                 $contacts_hash{'contacts'}{'lonstatus'}{$item} = \@excluded;
17446:             }
17447:         } elsif ($item eq 'weights') {
17448:             foreach my $type ('E','W','N','U') {
17449:                 $env{'form.error'.$item.'_'.$type} =~ s/^\s+|\s+$//g;
17450:                 if ($env{'form.error'.$item.'_'.$type} =~ /^\d+$/) {
17451:                     unless ($env{'form.error'.$item.'_'.$type} == $lonstatus_defs->{$type}) {
17452:                         $contacts_hash{'contacts'}{'lonstatus'}{$item}{$type} =
17453:                             $env{'form.error'.$item.'_'.$type};
17454:                     }
17455:                 }
17456:             }
17457:         } elsif (($item eq 'threshold') || ($item eq 'sysmail')) {
17458:             $env{'form.error'.$item} =~ s/^\s+|\s+$//g;
17459:             if ($env{'form.error'.$item} =~ /^\d+$/) {
17460:                 unless ($env{'form.error'.$item} == $lonstatus_defs->{$item}) {
17461:                     $contacts_hash{'contacts'}{'lonstatus'}{$item} = $env{'form.error'.$item};
17462:                 }
17463:             }
17464:         }
17465:     }
17466:     if ((ref($fields) eq 'ARRAY') && (ref($possoptions) eq 'HASH')) {
17467:         foreach my $field (@{$fields}) {
17468:             if (ref($possoptions->{$field}) eq 'ARRAY') {
17469:                 my $value = $env{'form.helpform_'.$field};
17470:                 $value =~ s/^\s+|\s+$//g;
17471:                 if (grep(/^\Q$value\E$/,@{$possoptions->{$field}})) {
17472:                     $contacts_hash{'contacts'}{'helpform'}{$field} = $value;
17473:                     if ($field eq 'screenshot') {
17474:                         $env{'form.helpform_maxsize'} =~ s/^\s+|\s+$//g;
17475:                         if ($env{'form.helpform_maxsize'} =~ /^\d+\.?\d*$/) {
17476:                             $contacts_hash{'contacts'}{'helpform'}{'maxsize'} = $env{'form.helpform_maxsize'};
17477:                         }
17478:                     }
17479:                 }
17480:             }
17481:         }
17482:     }
17483:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
17484:     my (@statuses,%usertypeshash,@overrides);
17485:     if ((ref($types) eq 'ARRAY') && (@{$types} > 0)) {
17486:         @statuses = @{$types};
17487:         if (ref($usertypes) eq 'HASH') {
17488:             %usertypeshash = %{$usertypes};
17489:         }
17490:     }
17491:     if (@statuses) {
17492:         my @possoverrides = &Apache::loncommon::get_env_multiple('form.overrides');
17493:         foreach my $type (@possoverrides) {
17494:             if (($type ne '') && (grep(/^\Q$type\E$/,@statuses))) {
17495:                 push(@overrides,$type);
17496:             }
17497:         }
17498:         if (@overrides) {
17499:             foreach my $type (@overrides) {
17500:                 my @standard = &Apache::loncommon::get_env_multiple('form.override_'.$type);
17501:                 foreach my $item (@contacts) {
17502:                     if (grep(/^\Q$item\E$/,@standard)) {
17503:                         $contacts_hash{'contacts'}{'overrides'}{$type}{$item} = 1;
17504:                         $newsetting{'override_'.$type}{$item} = 1;
17505:                     } else {
17506:                         $contacts_hash{'contacts'}{'overrides'}{$type}{$item} = 0;
17507:                         $newsetting{'override_'.$type}{$item} = 0;
17508:                     }
17509:                 }
17510:                 $contacts_hash{'contacts'}{'overrides'}{$type}{'others'} = $env{'form.override_'.$type.'_others'};
17511:                 $contacts_hash{'contacts'}{'overrides'}{$type}{'bcc'} = $env{'form.override_'.$type.'_bcc'};
17512:                 $newsetting{'override_'.$type}{'others'} = $env{'form.override_'.$type.'_others'};
17513:                 $newsetting{'override_'.$type}{'bcc'} = $env{'form.override_'.$type.'_bcc'};
17514:                 if (($env{'form.override_'.$type.'_includestr'} ne '') && ($env{'form.override_'.$type.'_includeloc'} =~ /^s|b$/)) {
17515:                     $includestr{$type} = $env{'form.override_'.$type.'_includestr'};
17516:                     $includeloc{$type} = $env{'form.override_'.$type.'_includeloc'};
17517:                     $contacts_hash{'contacts'}{'overrides'}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
17518:                     $newsetting{'override_'.$type}{'include'} = $contacts_hash{'contacts'}{'overrides'}{$type}{'include'};
17519:                 }
17520:             }     
17521:         }
17522:     }
17523:     if (keys(%currsetting) > 0) {
17524:         foreach my $item (@contacts) {
17525:             if ($to{$item} ne $currsetting{$item}) {
17526:                 $changes{$item} = 1;
17527:             }
17528:         }
17529:         foreach my $type (@mailings) {
17530:             foreach my $item (@contacts) {
17531:                 if (ref($currsetting{$type}) eq 'HASH') {
17532:                     if ($currsetting{$type}{$item} ne $contacts_hash{contacts}{$type}{$item}) {
17533:                         push(@{$changes{$type}},$item);
17534:                     }
17535:                 } else {
17536:                     push(@{$changes{$type}},@{$newsetting{$type}});
17537:                 }
17538:             }
17539:             if ($others{$type} ne $currsetting{$type}{'others'}) {
17540:                 push(@{$changes{$type}},'others');
17541:             }
17542:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
17543:                 if ($bcc{$type} ne $currsetting{$type}{'bcc'}) {
17544:                     push(@{$changes{$type}},'bcc'); 
17545:                 }
17546:                 my ($currloc,$currstr) = split(/:/,$currsetting{$type}{'include'},2);
17547:                 if (($includeloc{$type} ne $currloc) || (&escape($includestr{$type}) ne $currstr)) {
17548:                     push(@{$changes{$type}},'include');
17549:                 }
17550:             }
17551:         }
17552:         if (ref($fields) eq 'ARRAY') {
17553:             if (ref($currsetting{'helpform'}) eq 'HASH') {
17554:                 foreach my $field (@{$fields}) {
17555:                     if ($currsetting{'helpform'}{$field} ne $contacts_hash{'contacts'}{'helpform'}{$field}) {
17556:                         push(@{$changes{'helpform'}},$field);
17557:                     }
17558:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
17559:                         if ($currsetting{'helpform'}{'maxsize'} ne $contacts_hash{'contacts'}{'helpform'}{'maxsize'}) {
17560:                             push(@{$changes{'helpform'}},'maxsize');
17561:                         }
17562:                     }
17563:                 }
17564:             } else {
17565:                 foreach my $field (@{$fields}) {
17566:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
17567:                         push(@{$changes{'helpform'}},$field);
17568:                     }
17569:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
17570:                         if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
17571:                             push(@{$changes{'helpform'}},'maxsize');
17572:                         }
17573:                     }
17574:                 }
17575:             }
17576:         }
17577:         if (@statuses) {
17578:             if (ref($currsetting{'overrides'}) eq 'HASH') { 
17579:                 foreach my $key (keys(%{$currsetting{'overrides'}})) {
17580:                     if (ref($currsetting{'overrides'}{$key}) eq 'HASH') {
17581:                         if (ref($newsetting{'override_'.$key}) eq 'HASH') {
17582:                             foreach my $item (@contacts,'bcc','others','include') {
17583:                                 if ($currsetting{'overrides'}{$key}{$item} ne $newsetting{'override_'.$key}{$item}) { 
17584:                                     push(@{$changes{'overrides'}},$key);
17585:                                     last;
17586:                                 }
17587:                             }
17588:                         } else {
17589:                             push(@{$changes{'overrides'}},$key);
17590:                         }
17591:                     }
17592:                 }
17593:                 foreach my $key (@overrides) {
17594:                     unless (exists($currsetting{'overrides'}{$key})) {
17595:                         push(@{$changes{'overrides'}},$key);
17596:                     }
17597:                 }
17598:             } else {
17599:                 foreach my $key (@overrides) {
17600:                     push(@{$changes{'overrides'}},$key); 
17601:                 }
17602:             }
17603:         }
17604:         if (ref($currsetting{'lonstatus'}) eq 'HASH') {
17605:             foreach my $key ('excluded','weights','threshold','sysmail') {
17606:                 if ($key eq 'excluded') {
17607:                     if ((ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') &&
17608:                         (ref($contacts_hash{contacts}{lonstatus}{excluded}) eq 'ARRAY')) {
17609:                         if ((ref($currsetting{'lonstatus'}{$key}) eq 'ARRAY') &&
17610:                             (@{$currsetting{'lonstatus'}{$key}})) {
17611:                             my @diffs =
17612:                                 &Apache::loncommon::compare_arrays($contacts_hash{contacts}{lonstatus}{excluded},
17613:                                                                    $currsetting{'lonstatus'}{$key});
17614:                             if (@diffs) {
17615:                                 push(@{$changes{'lonstatus'}},$key);
17616:                             }
17617:                         } elsif (@{$contacts_hash{contacts}{lonstatus}{excluded}}) {
17618:                             push(@{$changes{'lonstatus'}},$key);
17619:                         }
17620:                     } elsif ((ref($currsetting{'lonstatus'}{$key}) eq 'ARRAY') &&
17621:                              (@{$currsetting{'lonstatus'}{$key}})) {
17622:                         push(@{$changes{'lonstatus'}},$key);
17623:                     }
17624:                 } elsif ($key eq 'weights') {
17625:                     if ((ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') &&
17626:                         (ref($contacts_hash{contacts}{lonstatus}{$key}) eq 'HASH')) {
17627:                         if (ref($currsetting{'lonstatus'}{$key}) eq 'HASH') {
17628:                             foreach my $type ('E','W','N','U') {
17629:                                 unless ($contacts_hash{contacts}{lonstatus}{$key}{$type} eq
17630:                                         $currsetting{'lonstatus'}{$key}{$type}) {
17631:                                     push(@{$changes{'lonstatus'}},$key);
17632:                                     last;
17633:                                 }
17634:                             }
17635:                         } else {
17636:                             foreach my $type ('E','W','N','U') {
17637:                                 if ($contacts_hash{contacts}{lonstatus}{$key}{$type} ne '') {
17638:                                     push(@{$changes{'lonstatus'}},$key);
17639:                                     last;
17640:                                 }
17641:                             }
17642:                         }
17643:                     } elsif (ref($currsetting{'lonstatus'}{$key}) eq 'HASH') {
17644:                         foreach my $type ('E','W','N','U') {
17645:                             if ($currsetting{'lonstatus'}{$key}{$type} ne '') {
17646:                                 push(@{$changes{'lonstatus'}},$key);
17647:                                 last;
17648:                             }
17649:                         }
17650:                     }
17651:                 } elsif (($key eq 'threshold') || ($key eq 'sysmail')) {
17652:                     if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
17653:                         if ($currsetting{'lonstatus'}{$key} =~ /^\d+$/) {
17654:                             if ($currsetting{'lonstatus'}{$key} != $contacts_hash{contacts}{lonstatus}{$key}) {
17655:                                 push(@{$changes{'lonstatus'}},$key);
17656:                             }
17657:                         } elsif ($contacts_hash{contacts}{lonstatus}{$key} =~ /^\d+$/) {
17658:                             push(@{$changes{'lonstatus'}},$key);
17659:                         }
17660:                     } elsif ($currsetting{'lonstatus'}{$key} =~ /^\d+$/) {
17661:                         push(@{$changes{'lonstatus'}},$key);
17662:                     }
17663:                 }
17664:             }
17665:         } else {
17666:             if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
17667:                 foreach my $key ('excluded','weights','threshold','sysmail') {
17668:                     if (exists($contacts_hash{contacts}{lonstatus}{$key})) {
17669:                         push(@{$changes{'lonstatus'}},$key);
17670:                     }
17671:                 }
17672:             }
17673:         }
17674:     } else {
17675:         my %default;
17676:         $default{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
17677:         $default{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
17678:         $default{'errormail'} = 'adminemail';
17679:         $default{'packagesmail'} = 'adminemail';
17680:         $default{'helpdeskmail'} = 'supportemail';
17681:         $default{'otherdomsmail'} = 'supportemail';
17682:         $default{'lonstatusmail'} = 'adminemail';
17683:         $default{'requestsmail'} = 'adminemail';
17684:         $default{'updatesmail'} = 'adminemail';
17685:         $default{'hostipmail'} = 'adminemail';
17686:         foreach my $item (@contacts) {
17687:            if ($to{$item} ne $default{$item}) {
17688:                $changes{$item} = 1;
17689:            }
17690:         }
17691:         foreach my $type (@mailings) {
17692:             if ((@{$newsetting{$type}} != 1) || ($newsetting{$type}[0] ne $default{$type})) {
17693:                 push(@{$changes{$type}},@{$newsetting{$type}});
17694:             }
17695:             if ($others{$type} ne '') {
17696:                 push(@{$changes{$type}},'others');
17697:             }
17698:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
17699:                 if ($bcc{$type} ne '') {
17700:                     push(@{$changes{$type}},'bcc');
17701:                 }
17702:                 if (($includeloc{$type} =~ /^b|s$/) && ($includestr{$type} ne '')) {
17703:                     push(@{$changes{$type}},'include');
17704:                 }
17705:             }
17706:         }
17707:         if (ref($fields) eq 'ARRAY') {
17708:             foreach my $field (@{$fields}) {
17709:                 if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
17710:                     push(@{$changes{'helpform'}},$field);
17711:                 }
17712:                 if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
17713:                     if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
17714:                         push(@{$changes{'helpform'}},'maxsize');
17715:                     }
17716:                 }
17717:             }
17718:         }
17719:         if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
17720:             foreach my $key ('excluded','weights','threshold','sysmail') {
17721:                 if (exists($contacts_hash{contacts}{lonstatus}{$key})) {
17722:                     push(@{$changes{'lonstatus'}},$key);
17723:                 }
17724:             }
17725:         }
17726:     }
17727:     foreach my $item (@toggles) {
17728:         if (($env{'form.'.$item} == 1) && ($currsetting{$item} == 0)) {
17729:             $changes{$item} = 1;
17730:         } elsif ((!$env{'form.'.$item}) &&
17731:                  (($currsetting{$item} eq '') || ($currsetting{$item} == 1))) {
17732:             $changes{$item} = 1;
17733:         }
17734:     }
17735:     my $putresult = &Apache::lonnet::put_dom('configuration',\%contacts_hash,
17736:                                              $dom);
17737:     if ($putresult eq 'ok') {
17738:         if (keys(%changes) > 0) {
17739:             &Apache::loncommon::devalidate_domconfig_cache($dom);
17740:             if (ref($lastactref) eq 'HASH') {
17741:                 $lastactref->{'domainconfig'} = 1;
17742:             }
17743:             my ($titles,$short_titles)  = &contact_titles();
17744:             $resulttext = &mt('Changes made:').'<ul>';
17745:             foreach my $item (@contacts) {
17746:                 if ($changes{$item}) {
17747:                     $resulttext .= '<li>'.$titles->{$item}.
17748:                                     &mt(' set to: ').
17749:                                     '<span class="LC_cusr_emph">'.
17750:                                     $to{$item}.'</span></li>';
17751:                 }
17752:             }
17753:             foreach my $type (@mailings) {
17754:                 if (ref($changes{$type}) eq 'ARRAY') {
17755:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
17756:                         $resulttext .= '<li>'.$titles->{$type}.' -- '.&mt('sent to').': ';
17757:                     } else {
17758:                         $resulttext .= '<li>'.$titles->{$type}.': ';
17759:                     }
17760:                     my @text;
17761:                     foreach my $item (@{$newsetting{$type}}) {
17762:                         push(@text,$short_titles->{$item});
17763:                     }
17764:                     if ($others{$type} ne '') {
17765:                         push(@text,$others{$type});
17766:                     }
17767:                     if (@text) {
17768:                         $resulttext .= '<span class="LC_cusr_emph">'.
17769:                                        join(', ',@text).'</span>';
17770:                     }
17771:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
17772:                         if ($bcc{$type} ne '') {
17773:                             my $bcctext;
17774:                             if (@text) {
17775:                                 $bcctext = '&nbsp;'.&mt('with Bcc to');
17776:                             } else {
17777:                                 $bcctext = '(Bcc)';
17778:                             }
17779:                             $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$bcc{$type}.'</span>';
17780:                         } elsif (!@text) {
17781:                             $resulttext .= &mt('No one');
17782:                         }   
17783:                         if ($includestr{$type} ne '') {
17784:                             if ($includeloc{$type} eq 'b') {
17785:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail body:').' '.$includestr{$type};
17786:                             } elsif ($includeloc{$type} eq 's') {
17787:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail subject:').' '.$includestr{$type};
17788:                             }
17789:                         }
17790:                     } elsif (!@text) {
17791:                         $resulttext .= &mt('No recipients');
17792:                     }
17793:                     $resulttext .= '</li>';
17794:                 }
17795:             }
17796:             if (ref($changes{'overrides'}) eq 'ARRAY') {
17797:                 my @deletions;
17798:                 foreach my $type (@{$changes{'overrides'}}) {
17799:                     if ($usertypeshash{$type}) {
17800:                         if (grep(/^\Q$type\E/,@overrides)) {
17801:                             $resulttext .= '<li>'.&mt("Overrides based on requester's affiliation set for [_1]",
17802:                                                       $usertypeshash{$type}).'<ul><li>';
17803:                             if (ref($newsetting{'override_'.$type}) eq 'HASH') {
17804:                                 my @text;
17805:                                 foreach my $item (@contacts) {
17806:                                     if ($newsetting{'override_'.$type}{$item}) { 
17807:                                         push(@text,$short_titles->{$item});
17808:                                     }
17809:                                 }
17810:                                 if ($newsetting{'override_'.$type}{'others'} ne '') {
17811:                                     push(@text,$newsetting{'override_'.$type}{'others'});
17812:                                 }
17813:   
17814:                                 if (@text) {
17815:                                     $resulttext .= &mt('Helpdesk e-mail sent to: [_1]',
17816:                                                        '<span class="LC_cusr_emph">'.join(', ',@text).'</span>');
17817:                                 }
17818:                                 if ($newsetting{'override_'.$type}{'bcc'} ne '') {
17819:                                     my $bcctext;
17820:                                     if (@text) {
17821:                                         $bcctext = '&nbsp;'.&mt('with Bcc to');
17822:                                     } else {
17823:                                         $bcctext = '(Bcc)';
17824:                                     }
17825:                                     $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$newsetting{'override_'.$type}{'bcc'}.'</span>';
17826:                                 } elsif (!@text) {
17827:                                      $resulttext .= &mt('Helpdesk e-mail sent to no one');
17828:                                 }
17829:                                 $resulttext .= '</li>';
17830:                                 if ($newsetting{'override_'.$type}{'include'} ne '') {
17831:                                     my ($loc,$str) = split(/:/,$newsetting{'override_'.$type}{'include'});
17832:                                     if ($loc eq 'b') {
17833:                                         $resulttext .= '<li>'.&mt('Text automatically added to e-mail body:').' '.&unescape($str).'</li>';
17834:                                     } elsif ($loc eq 's') {
17835:                                         $resulttext .= '<li>'.&mt('Text automatically added to e-mail subject:').' '.&unescape($str).'</li>';
17836:                                     }
17837:                                 }
17838:                             }
17839:                             $resulttext .= '</li></ul></li>';
17840:                         } else {
17841:                             push(@deletions,$usertypeshash{$type});
17842:                         }
17843:                     }
17844:                 }
17845:                 if (@deletions) {
17846:                     $resulttext .= '<li>'.&mt("Overrides based on requester's affiliation discontinued for: [_1]",
17847:                                               join(', ',@deletions)).'</li>';
17848:                 }
17849:             }
17850:             my @offon = ('off','on');
17851:             my $corelink = &core_link_msu();
17852:             if ($changes{'reporterrors'}) {
17853:                 $resulttext .= '<li>'.
17854:                                &mt('E-mail error reports to [_1] set to "'.
17855:                                    $offon[$env{'form.reporterrors'}].'".',
17856:                                    $corelink).
17857:                                '</li>';
17858:             }
17859:             if ($changes{'reportupdates'}) {
17860:                 $resulttext .= '<li>'.
17861:                                 &mt('E-mail record of completed LON-CAPA updates to [_1] set to "'.
17862:                                     $offon[$env{'form.reportupdates'}].'".',
17863:                                     $corelink).
17864:                                 '</li>';
17865:             }
17866:             if ($changes{'reportstatus'}) {
17867:                 $resulttext .= '<li>'.
17868:                                 &mt('E-mail status if errors above threshold to [_1] set to "'.
17869:                                     $offon[$env{'form.reportstatus'}].'".',
17870:                                     $corelink).
17871:                                 '</li>';
17872:             }
17873:             if (ref($changes{'lonstatus'}) eq 'ARRAY') {
17874:                 $resulttext .= '<li>'.
17875:                                &mt('Nightly status check e-mail settings').':<ul>';
17876:                 my (%defval,%use_def,%shown);
17877:                 $defval{'threshold'} = $lonstatus_defs->{'threshold'};
17878:                 $defval{'sysmail'} = $lonstatus_defs->{'sysmail'};
17879:                 $defval{'weights'} =
17880:                     join(', ',map { $lonstatus_names->{$_}.'='.$lonstatus_defs->{$_}; } ('E','W','N','U'));
17881:                 $defval{'excluded'} = &mt('None');
17882:                 if (ref($contacts_hash{'contacts'}{'lonstatus'}) eq 'HASH') {
17883:                     foreach my $item ('threshold','sysmail','weights','excluded') {
17884:                         if (exists($contacts_hash{'contacts'}{'lonstatus'}{$item})) {
17885:                             if (($item eq 'threshold') || ($item eq 'sysmail')) {
17886:                                 $shown{$item} = $contacts_hash{'contacts'}{'lonstatus'}{$item};
17887:                             } elsif ($item eq 'weights') {
17888:                                 if (ref($contacts_hash{'contacts'}{'lonstatus'}{$item}) eq 'HASH') {
17889:                                     foreach my $type ('E','W','N','U') {
17890:                                         $shown{$item} .= $lonstatus_names->{$type}.'=';
17891:                                         if (exists($contacts_hash{'contacts'}{'lonstatus'}{$item}{$type})) {
17892:                                             $shown{$item} .= $contacts_hash{'contacts'}{'lonstatus'}{$item}{$type};
17893:                                         } else {
17894:                                             $shown{$item} .= $lonstatus_defs->{$type};
17895:                                         }
17896:                                         $shown{$item} .= ', ';
17897:                                     }
17898:                                     $shown{$item} =~ s/, $//;
17899:                                 } else {
17900:                                     $shown{$item} = $defval{$item};
17901:                                 }
17902:                             } elsif ($item eq 'excluded') {
17903:                                 if (ref($contacts_hash{'contacts'}{'lonstatus'}{$item}) eq 'ARRAY') {
17904:                                     $shown{$item} = join(', ',@{$contacts_hash{'contacts'}{'lonstatus'}{$item}});
17905:                                 } else {
17906:                                     $shown{$item} = $defval{$item};
17907:                                 }
17908:                             }
17909:                         } else {
17910:                             $shown{$item} = $defval{$item};
17911:                         }
17912:                     }
17913:                 } else {
17914:                     foreach my $item ('threshold','weights','excluded','sysmail') {
17915:                         $shown{$item} = $defval{$item};
17916:                     }
17917:                 }
17918:                 foreach my $item ('threshold','weights','excluded','sysmail') {
17919:                     $resulttext .= '<li>'.&mt($titles->{'error'.$item}.' -- [_1]',
17920:                                           $shown{$item}).'</li>';
17921:                 }
17922:                 $resulttext .= '</ul></li>';
17923:             }
17924:             if ((ref($changes{'helpform'}) eq 'ARRAY') && (ref($fields) eq 'ARRAY')) {
17925:                 my (@optional,@required,@unused,$maxsizechg);
17926:                 foreach my $field (@{$changes{'helpform'}}) {
17927:                     if ($field eq 'maxsize') {
17928:                         $maxsizechg = 1;
17929:                         next;
17930:                     }
17931:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'yes') {
17932:                         push(@optional,$field);
17933:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'no') {
17934:                         push(@unused,$field);
17935:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'req') {
17936:                         push(@required,$field);
17937:                     }
17938:                 }
17939:                 if (@optional) {
17940:                     $resulttext .= '<li>'.
17941:                                    &mt('Help form fields changed to "Optional": [_1].',
17942:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @optional)).'</span>'.
17943:                                    '</li>';
17944:                 }
17945:                 if (@required) {
17946:                     $resulttext .= '<li>'.
17947:                                    &mt('Help form fields changed to "Required": [_1].',
17948:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @required)).'</span>'.
17949:                                    '</li>';
17950:                 }
17951:                 if (@unused) {
17952:                     $resulttext .= '<li>'.
17953:                                    &mt('Help form fields changed to "Not shown": [_1].',
17954:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @unused)).'</span>'.
17955:                                    '</li>';
17956:                 }
17957:                 if ($maxsizechg) {
17958:                     $resulttext .= '<li>'.
17959:                                    &mt('Max size for file uploaded to help form by logged-in user set to [_1] MB.',
17960:                                        $contacts_hash{'contacts'}{'helpform'}{'maxsize'}).
17961:                                    '</li>';
17962:                 }
17963:             }
17964:             $resulttext .= '</ul>';
17965:         } else {
17966:             $resulttext = &mt('No changes made to contacts and form settings');
17967:         }
17968:     } else {
17969:         $resulttext = '<span class="LC_error">'.
17970:             &mt('An error occurred: [_1].',$putresult).'</span>';
17971:     }
17972:     return $resulttext;
17973: }
17974: 
17975: sub modify_privacy {
17976:     my ($dom,%domconfig) = @_;
17977:     my ($resulttext,%current,%changes);
17978:     if (ref($domconfig{'privacy'}) eq 'HASH') {
17979:         %current = %{$domconfig{'privacy'}};
17980:     }
17981:     my @fields = ('lastname','firstname','middlename','generation','permanentemail','id');
17982:     my @items = ('domain','author','course','community');
17983:     my %names = &Apache::lonlocal::texthash (
17984:                    domain => 'Assigned domain role(s)',
17985:                    author => 'Assigned co-author role(s)',
17986:                    course => 'Assigned course role(s)',
17987:                    community => 'Assigned community role(s)',
17988:                 );
17989:     my %roles = &Apache::lonlocal::texthash (
17990:                    domain => 'Domain role',
17991:                    author => 'Co-author role',
17992:                    course => 'Course role',
17993:                    community => 'Community role',
17994:                 );
17995:     my %titles = &Apache::lonlocal::texthash (
17996:                   approval => 'Approval for role in different domain',
17997:                   othdom   => 'User information available in other domain',
17998:                   priv     => 'Information viewable by privileged user in same domain',
17999:                   unpriv   => 'Information viewable by unprivileged user in same domain',
18000:                   instdom  => 'Other domain shares institution/provider',
18001:                   extdom   => 'Other domain has different institution/provider',
18002:                   none     => 'Not allowed',
18003:                   user     => 'User authorizes',
18004:                   domain   => 'Domain Coordinator authorizes',
18005:                   auto     => 'Unrestricted',
18006:                   notify   => 'Notify when role needs authorization',
18007:     );
18008:     my %fieldnames = &Apache::lonlocal::texthash (
18009:                         id => 'Student/Employee ID',
18010:                         permanentemail => 'E-mail address',
18011:                         lastname => 'Last Name',
18012:                         firstname => 'First Name',
18013:                         middlename => 'Middle Name',
18014:                         generation => 'Generation',
18015:     );
18016:     my ($othertitle,$usertypes,$types) =
18017:         &Apache::loncommon::sorted_inst_types($dom);
18018:     my (%by_ip,%by_location,@intdoms,@instdoms);
18019:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
18020: 
18021:     my %privacyhash = (
18022:                        'approval' => {
18023:                                        instdom => {},
18024:                                        extdom  => {},
18025:                                      },
18026:                        'othdom'   => {},
18027:                        'priv'     => {},
18028:                        'unpriv'   => {},
18029:                       );
18030:     foreach my $item (@items) {
18031:         if (@instdoms > 1) {
18032:             if ($env{'form.privacy_approval_instdom_'.$item} =~ /^(none|user|domain|auto)$/) {
18033:                 $privacyhash{'approval'}{'instdom'}{$item} = $env{'form.privacy_approval_instdom_'.$item};
18034:             }
18035:             if (ref($current{'approval'}) eq 'HASH') {
18036:                 if (ref($current{'approval'}{'instdom'}) eq 'HASH') {
18037:                     unless ($privacyhash{'approval'}{'instdom'}{$item} eq $current{'approval'}{'instdom'}{$item}) {
18038:                         $changes{'approval'} = 1;
18039:                     }
18040:                 }
18041:             } elsif ($privacyhash{'approval'}{'instdom'}{$item} ne 'auto') {
18042:                 $changes{'approval'} = 1;
18043:             }
18044:         }
18045:         if (keys(%by_location) > 0) {
18046:             if ($env{'form.privacy_approval_extdom_'.$item} =~ /^(none|user|domain|auto)$/) {
18047:                 $privacyhash{'approval'}{'extdom'}{$item} = $env{'form.privacy_approval_extdom_'.$item};
18048:             }
18049:             if (ref($current{'approval'}) eq 'HASH') {
18050:                 if (ref($current{'approval'}{'extdom'}) eq 'HASH') {
18051:                     unless ($privacyhash{'approval'}{'extdom'}{$item} eq $current{'approval'}{'extdom'}{$item}) {
18052:                         $changes{'approval'} = 1;
18053:                     }
18054:                 }
18055:             } elsif ($privacyhash{'approval'}{'extdom'}{$item} ne 'auto') {
18056:                 $changes{'approval'} = 1;
18057:             }
18058:         }
18059:         foreach my $status ('priv','unpriv') {
18060:             my @possibles = sort(&Apache::loncommon::get_env_multiple('form.privacy_'.$status.'_'.$item));
18061:             my @newvalues;
18062:             foreach my $field (@possibles) {
18063:                 if (grep(/^\Q$field\E$/,@fields)) {
18064:                     $privacyhash{$status}{$item}{$field} = 1;
18065:                     push(@newvalues,$field);
18066:                 }
18067:             }
18068:             @newvalues = sort(@newvalues);
18069:             if (ref($current{$status}) eq 'HASH') {
18070:                 if (ref($current{$status}{$item}) eq 'HASH') {
18071:                     my @currvalues = sort(keys(%{$current{$status}{$item}}));
18072:                     my @diffs = &Apache::loncommon::compare_arrays(\@currvalues,\@newvalues);
18073:                     if (@diffs > 0) {
18074:                         $changes{$status} = 1;
18075:                     }
18076:                 }
18077:             } else {
18078:                 my @stdfields;
18079:                 foreach my $field (@fields) {
18080:                     if ($field eq 'id') {
18081:                         next if ($status eq 'unpriv');
18082:                         next if (($status eq 'priv') && ($item eq 'community'));
18083:                     }
18084:                     push(@stdfields,$field);
18085:                 }
18086:                 my @diffs = &Apache::loncommon::compare_arrays(\@stdfields,\@newvalues);
18087:                 if (@diffs > 0) {
18088:                     $changes{$status} = 1;
18089:                 }
18090:             }
18091:         }
18092:     }
18093:     if ((@instdoms > 1) || (keys(%by_location) > 0)) {
18094:         my @statuses;
18095:         if (ref($types) eq 'ARRAY') {
18096:             @statuses = @{$types};
18097:         }
18098:         foreach my $type (@statuses,'default') {
18099:             my @possfields = &Apache::loncommon::get_env_multiple('form.privacy_othdom_'.$type);
18100:             my @newvalues;
18101:             foreach my $field (sort(@possfields)) {
18102:                 if (grep(/^\Q$field\E$/,@fields)) {
18103:                     $privacyhash{'othdom'}{$type}{$field} = 1;
18104:                     push(@newvalues,$field);
18105:                 }
18106:             }
18107:             @newvalues = sort(@newvalues);
18108:             if (ref($current{'othdom'}) eq 'HASH') {
18109:                 if (ref($current{'othdom'}{$type}) eq 'HASH') {
18110:                     my @currvalues = sort(keys(%{$current{'othdom'}{$type}}));
18111:                     my @diffs = &Apache::loncommon::compare_arrays(\@currvalues,\@newvalues);
18112:                     if (@diffs > 0) {
18113:                         $changes{'othdom'} = 1;
18114:                     }
18115:                 }
18116:             } else {
18117:                 my @stdfields = ('lastname','firstname','middlename','generation','permanentemail');
18118:                 my @diffs = &Apache::loncommon::compare_arrays(\@stdfields,\@newvalues);
18119:                 if (@diffs > 0) {
18120:                     $changes{'othdom'} = 1;
18121:                 }
18122:             }
18123:         }
18124:         my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
18125:         my %notify;
18126:         foreach my $possdc (&Apache::loncommon::get_env_multiple('form.privacy_notify')) {
18127:             if (exists($domcoords{$possdc})) {
18128:                 $notify{$possdc} = 1;
18129:             }
18130:         }
18131:         my $notify = join(',',sort(keys(%notify)));
18132:         if ($current{'notify'} ne $notify) {
18133:             $changes{'notify'} = 1;
18134:         }
18135:         $privacyhash{'notify'} = $notify;
18136:     }
18137:     my %confighash = (
18138:                         privacy => \%privacyhash,
18139:                      );
18140:     my $putresult = &Apache::lonnet::put_dom('configuration',\%confighash,$dom);
18141:     if ($putresult eq 'ok') {
18142:         if (keys(%changes) > 0) {
18143:             $resulttext = &mt('Changes made: ').'<ul>';
18144:             foreach my $key ('approval','notify','othdom','priv','unpriv') {
18145:                 if ($changes{$key}) {
18146:                     $resulttext .= '<li>'.$titles{$key}.':<ul>';
18147:                     if ($key eq 'approval') {
18148:                         if (keys(%{$privacyhash{$key}{instdom}})) {
18149:                             $resulttext .= '<li>'.$titles{'instdom'}.'<ul>';
18150:                             foreach my $item (@items) {
18151:                                 $resulttext .=  '<li>'.$roles{$item}.': '.$titles{$privacyhash{$key}{instdom}{$item}}.'</li>';
18152:                             }
18153:                             $resulttext .= '</ul></li>';
18154:                         }
18155:                         if (keys(%{$privacyhash{$key}{extdom}})) {
18156:                             $resulttext .= '<li>'.$titles{'extdom'}.'<ul>';
18157:                             foreach my $item (@items) {
18158:                                 $resulttext .=  '<li>'.$roles{$item}.': '.$titles{$privacyhash{$key}{extdom}{$item}}.'</li>';
18159:                             }
18160:                             $resulttext .= '</ul></li>';
18161:                         }
18162:                     } elsif ($key eq 'notify') {
18163:                         if ($privacyhash{$key}) {
18164:                             foreach my $dc (split(/,/,$privacyhash{$key})) {
18165:                                 my ($dcname,$dcdom) = split(/:/,$dc);
18166:                                 $resulttext .= '<li>'.&Apache::loncommon::plainname($dcname,$dcdom).'</li>';
18167:                             }
18168:                         } else {
18169:                             $resulttext .= '<li>'.&mt('No DCs to notify').'</li>';
18170:                         }
18171:                     } elsif ($key eq 'othdom') {
18172:                         my @statuses;
18173:                         if (ref($types) eq 'ARRAY') {
18174:                             @statuses = @{$types};
18175:                         }
18176:                         if (ref($privacyhash{$key}) eq 'HASH') {
18177:                             foreach my $status (@statuses,'default') {
18178:                                 if ($status eq 'default') {
18179:                                     $resulttext .= '<li>'.$othertitle.': ';
18180:                                 } elsif (ref($usertypes) eq 'HASH') {
18181:                                     $resulttext .= '<li>'.$usertypes->{$status}.': ';
18182:                                 } else {
18183:                                     next;
18184:                                 }
18185:                                 if (ref($privacyhash{$key}{$status}) eq 'HASH') {
18186:                                     if (keys(%{$privacyhash{$key}{$status}})) {
18187:                                         $resulttext .= join(', ', map { $fieldnames{$_}; } (sort(keys(%{$privacyhash{$key}{$status}}))));
18188:                                     } else {
18189:                                         $resulttext .= &mt('none');
18190:                                     }
18191:                                 }
18192:                                 $resulttext .= '</li>';
18193:                             }
18194:                         }
18195:                     } else {
18196:                         foreach my $item (@items) {
18197:                             if (ref($privacyhash{$key}{$item}) eq 'HASH') {
18198:                                 $resulttext .= '<li>'.$names{$item}.': ';
18199:                                 if (keys(%{$privacyhash{$key}{$item}})) {
18200:                                     $resulttext .= join(', ', map { $fieldnames{$_}; } (sort(keys(%{$privacyhash{$key}{$item}}))));
18201:                                 } else {
18202:                                     $resulttext .= &mt('none');
18203:                                 }
18204:                                 $resulttext .= '</li>';
18205:                             }
18206:                         }
18207:                     }
18208:                     $resulttext .= '</ul></li>';
18209:                 }
18210:             }
18211:         } else {
18212:             $resulttext = &mt('No changes made to user information settings');
18213:         }
18214:     } else {
18215:         $resulttext = '<span class="LC_error">'.
18216:             &mt('An error occurred: [_1]',$putresult).'</span>';
18217:     }
18218:     return $resulttext;
18219: }
18220: 
18221: sub modify_passwords {
18222:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
18223:     my ($resulttext,%current,%changes,%newvalues,@oktypes,$errors,
18224:         $updatedefaults,$updateconf);
18225:     my $customfn = 'resetpw.html';
18226:     if (ref($domconfig{'passwords'}) eq 'HASH') {
18227:         %current = %{$domconfig{'passwords'}};
18228:     }
18229:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
18230:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
18231:     if (ref($types) eq 'ARRAY') {
18232:         @oktypes = @{$types};
18233:     }
18234:     push(@oktypes,'default');
18235: 
18236:     my %titles = &Apache::lonlocal::texthash (
18237:         intauth_cost   => 'Encryption cost for bcrypt (positive integer)',
18238:         intauth_check  => 'Check bcrypt cost if authenticated',
18239:         intauth_switch => 'Existing crypt-based switched to bcrypt on authentication',
18240:         permanent      => 'Permanent e-mail address',
18241:         critical       => 'Critical notification address',
18242:         notify         => 'Notification address',
18243:         min            => 'Minimum password length',
18244:         max            => 'Maximum password length',
18245:         chars          => 'Required characters',
18246:         expire         => 'Password expiration (days)',
18247:         numsaved       => 'Number of previous passwords to save',
18248:         reset          => 'Resetting Forgotten Password',
18249:         intauth        => 'Encryption of Stored Passwords (Internal Auth)',
18250:         rules          => 'Rules for LON-CAPA Passwords',
18251:         crsownerchg    => 'Course Owner Changing Student Passwords',
18252:         username       => 'Username',
18253:         email          => 'E-mail address',
18254:     );
18255: 
18256: #
18257: # Retrieve current domain configuration for internal authentication from $domconfig{'defaults'}.
18258: #
18259:     my (%curr_defaults,%save_defaults);
18260:     if (ref($domconfig{'defaults'}) eq 'HASH') {
18261:         foreach my $key (keys(%{$domconfig{'defaults'}})) {
18262:             if ($key =~ /^intauth_(cost|check|switch)$/) {
18263:                 $curr_defaults{$key} = $domconfig{'defaults'}{$key};
18264:             } else {
18265:                 $save_defaults{$key} = $domconfig{'defaults'}{$key};
18266:             }
18267:         }
18268:     }
18269:     my %staticdefaults = (
18270:         'resetlink'      => 2,
18271:         'resetcase'      => \@oktypes,
18272:         'resetprelink'   => 'both',
18273:         'resetemail'     => ['critical','notify','permanent'],
18274:         'intauth_cost'   => 10,
18275:         'intauth_check'  => 0,
18276:         'intauth_switch' => 0,
18277:     );
18278:     $staticdefaults{'min'} = $Apache::lonnet::passwdmin;
18279:     foreach my $type (@oktypes) {
18280:         $staticdefaults{'resetpostlink'}{$type} = ['email','username'];
18281:     }
18282:     my $linklife = $env{'form.passwords_link'};
18283:     $linklife =~ s/^\s+|\s+$//g;
18284:     if (($linklife =~ /^\d+(|\.\d*)$/) && ($linklife > 0)) {
18285:         $newvalues{'resetlink'} = $linklife;
18286:         if ($current{'resetlink'}) {
18287:             if ($current{'resetlink'} ne $linklife) {
18288:                 $changes{'reset'} = 1;
18289:             }
18290:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
18291:             if ($staticdefaults{'resetlink'} ne $linklife) {
18292:                 $changes{'reset'} = 1;
18293:             }
18294:         }
18295:     } elsif ($current{'resetlink'}) {
18296:         $changes{'reset'} = 1;
18297:     }
18298:     my @casesens;
18299:     my @posscase = &Apache::loncommon::get_env_multiple('form.passwords_case_sensitive');
18300:     foreach my $case (sort(@posscase)) {
18301:         if (grep(/^\Q$case\E$/,@oktypes)) {
18302:             push(@casesens,$case);
18303:         }
18304:     }
18305:     $newvalues{'resetcase'} = \@casesens;
18306:     if (ref($current{'resetcase'}) eq 'ARRAY') {
18307:         my @diffs = &Apache::loncommon::compare_arrays($current{'resetcase'},\@casesens);
18308:         if (@diffs > 0) {
18309:             $changes{'reset'} = 1;
18310:         }
18311:     } elsif (!ref($domconfig{passwords}) eq 'HASH') {
18312:         my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetcase'},\@casesens);
18313:         if (@diffs > 0) {
18314:             $changes{'reset'} = 1;
18315:         }
18316:     }
18317:     if ($env{'form.passwords_prelink'} =~ /^(both|either)$/) {
18318:         $newvalues{'resetprelink'} = $env{'form.passwords_prelink'};
18319:         if (exists($current{'resetprelink'})) {
18320:             if ($current{'resetprelink'} ne $newvalues{'resetprelink'}) {
18321:                 $changes{'reset'} = 1;
18322:             }
18323:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
18324:             if ($staticdefaults{'resetprelink'} ne $newvalues{'resetprelink'}) {
18325:                 $changes{'reset'} = 1;
18326:             }
18327:         }
18328:     } elsif ($current{'resetprelink'}) {
18329:         $changes{'reset'} = 1;
18330:     }
18331:     foreach my $type (@oktypes) {
18332:         my @possplink = &Apache::loncommon::get_env_multiple('form.passwords_postlink_'.$type);
18333:         my @postlink;
18334:         foreach my $item (sort(@possplink)) {
18335:             if ($item =~ /^(email|username)$/) {
18336:                 push(@postlink,$item);
18337:             }
18338:         }
18339:         $newvalues{'resetpostlink'}{$type} = \@postlink;
18340:         unless ($changes{'reset'}) {
18341:             if (ref($current{'resetpostlink'}) eq 'HASH') {
18342:                 if (ref($current{'resetpostlink'}{$type}) eq 'ARRAY') {
18343:                     my @diffs = &Apache::loncommon::compare_arrays($current{'resetpostlink'}{$type},\@postlink);
18344:                     if (@diffs > 0) {
18345:                         $changes{'reset'} = 1;
18346:                     }
18347:                 } else {
18348:                     $changes{'reset'} = 1;
18349:                 }
18350:             } elsif (!ref($domconfig{passwords}) eq 'HASH') {
18351:                 my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetpostlink'}{$type},\@postlink);
18352:                 if (@diffs > 0) {
18353:                     $changes{'reset'} = 1;
18354:                 }
18355:             }
18356:         }
18357:     }
18358:     my @possemailsrc = &Apache::loncommon::get_env_multiple('form.passwords_emailsrc');
18359:     my @resetemail;
18360:     foreach my $item (sort(@possemailsrc)) {
18361:         if ($item =~ /^(permanent|critical|notify)$/) {
18362:             push(@resetemail,$item);
18363:         }
18364:     }
18365:     $newvalues{'resetemail'} = \@resetemail;
18366:     unless ($changes{'reset'}) {
18367:         if (ref($current{'resetemail'}) eq 'ARRAY') {
18368:             my @diffs = &Apache::loncommon::compare_arrays($current{'resetemail'},\@resetemail);
18369:             if (@diffs > 0) {
18370:                 $changes{'reset'} = 1;
18371:             }
18372:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
18373:             my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetemail'},\@resetemail);
18374:             if (@diffs > 0) {
18375:                 $changes{'reset'} = 1;
18376:             }
18377:         }
18378:     }
18379:     if ($env{'form.passwords_stdtext'} == 0) {
18380:         $newvalues{'resetremove'} = 1;
18381:         unless ($current{'resetremove'}) {
18382:             $changes{'reset'} = 1;
18383:         }
18384:     } elsif ($current{'resetremove'}) {
18385:         $changes{'reset'} = 1;
18386:     }
18387:     if ($env{'form.passwords_customfile.filename'} ne '') {
18388:         my $servadm = $r->dir_config('lonAdmEMail');
18389:         my ($configuserok,$author_ok,$switchserver) =
18390:             &config_check($dom,$confname,$servadm);
18391:         my $error;
18392:         if ($configuserok eq 'ok') {
18393:             if ($switchserver) {
18394:                 $error = &mt("Upload of file containing domain-specific text is not permitted to this server: [_1]",$switchserver);
18395:             } else {
18396:                 if ($author_ok eq 'ok') {
18397:                     my ($result,$customurl) =
18398:                         &publishlogo($r,'upload','passwords_customfile',$dom,
18399:                                      $confname,'customtext/resetpw','','',$customfn);
18400:                     if ($result eq 'ok') {
18401:                         $newvalues{'resetcustom'} = $customurl;
18402:                         $changes{'reset'} = 1;
18403:                     } else {
18404:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$customfn,$result);
18405:                     }
18406:                 } else {
18407:                     $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);
18408:                 }
18409:             }
18410:         } else {
18411:             $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);
18412:         }
18413:         if ($error) {
18414:             &Apache::lonnet::logthis($error);
18415:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
18416:         }
18417:     } elsif ($current{'resetcustom'}) {
18418:         if ($env{'form.passwords_custom_del'}) {
18419:             $changes{'reset'} = 1;
18420:         } else {
18421:             $newvalues{'resetcustom'} = $current{'resetcustom'};
18422:         }
18423:     }
18424:     $env{'form.intauth_cost'} =~ s/^\s+|\s+$//g;
18425:     if (($env{'form.intauth_cost'} ne '') && ($env{'form.intauth_cost'} =~ /^\d+$/)) {
18426:         $save_defaults{'intauth_cost'} = $env{'form.intauth_cost'};
18427:         if ($save_defaults{'intauth_cost'} ne $curr_defaults{'intauth_cost'}) {
18428:             $changes{'intauth'} = 1;
18429:         }
18430:     } else {
18431:         $save_defaults{'intauth_cost'} = $curr_defaults{'intauth_cost'};
18432:     }
18433:     if ($env{'form.intauth_check'} =~ /^(0|1|2)$/) {
18434:         $save_defaults{'intauth_check'} = $env{'form.intauth_check'};
18435:         if ($save_defaults{'intauth_check'} ne $curr_defaults{'intauth_check'}) {
18436:             $changes{'intauth'} = 1;
18437:         }
18438:     } else {
18439:         $save_defaults{'intauth_check'} = $curr_defaults{'intauth_check'};
18440:     }
18441:     if ($env{'form.intauth_switch'} =~ /^(0|1|2)$/) {
18442:         $save_defaults{'intauth_switch'} = $env{'form.intauth_switch'};
18443:         if ($save_defaults{'intauth_switch'} ne $curr_defaults{'intauth_switch'}) {
18444:             $changes{'intauth'} = 1;
18445:         }
18446:     } else {
18447:         $save_defaults{'intauth_check'} = $curr_defaults{'intauth_check'};
18448:     }
18449:     foreach my $item ('cost','check','switch') {
18450:         if ($save_defaults{'intauth_'.$item} ne $domdefaults{'intauth_'.$item}) {
18451:             $domdefaults{'intauth_'.$item} = $save_defaults{'intauth_'.$item};
18452:             $updatedefaults = 1;
18453:         }
18454:     }
18455:     &password_rule_changes('passwords',\%newvalues,\%current,\%changes);
18456:     my %crsownerchg = (
18457:                         by => [],
18458:                         for => [],
18459:                       );
18460:     foreach my $item ('by','for') {
18461:         my @posstypes = &Apache::loncommon::get_env_multiple('form.passwords_crsowner_'.$item);
18462:         foreach my $type (sort(@posstypes)) {
18463:             if (grep(/^\Q$type\E$/,@oktypes)) {
18464:                 push(@{$crsownerchg{$item}},$type);
18465:             }
18466:         }
18467:     }
18468:     $newvalues{'crsownerchg'} = \%crsownerchg;
18469:     if (ref($current{'crsownerchg'}) eq 'HASH') {
18470:         foreach my $item ('by','for') {
18471:             if (ref($current{'crsownerchg'}{$item}) eq 'ARRAY') {
18472:                 my @diffs = &Apache::loncommon::compare_arrays($current{'crsownerchg'}{$item},$crsownerchg{$item});
18473:                 if (@diffs > 0) {
18474:                     $changes{'crsownerchg'} = 1;
18475:                     last;
18476:                 }
18477:             }
18478:         }
18479:     } elsif (!(ref($domconfig{passwords}) eq 'HASH')) {
18480:         foreach my $item ('by','for') {
18481:             if (@{$crsownerchg{$item}} > 0) {
18482:                 $changes{'crsownerchg'} = 1;
18483:                 last;
18484:             }
18485:         }
18486:     }
18487: 
18488:     my %confighash = (
18489:                         defaults  => \%save_defaults,
18490:                         passwords => \%newvalues,
18491:                      );
18492:     &process_captcha('passwords',\%changes,$confighash{'passwords'},$domconfig{'passwords'});
18493: 
18494:     my $putresult = &Apache::lonnet::put_dom('configuration',\%confighash,$dom);
18495:     if ($putresult eq 'ok') {
18496:         if (keys(%changes) > 0) {
18497:             $resulttext = &mt('Changes made: ').'<ul>';
18498:             foreach my $key ('reset','intauth','rules','crsownerchg') {
18499:                 if ($changes{$key}) {
18500:                     unless ($key eq 'intauth') {
18501:                         $updateconf = 1;
18502:                     }
18503:                     $resulttext .= '<li>'.$titles{$key}.':<ul>';
18504:                     if ($key eq 'reset') {
18505:                         if ($confighash{'passwords'}{'captcha'} eq 'original') {
18506:                             $resulttext .= '<li>'.&mt('CAPTCHA validation set to use: original CAPTCHA').'</li>';
18507:                         } elsif ($confighash{'passwords'}{'captcha'} eq 'recaptcha') {
18508:                             $resulttext .= '<li>'.&mt('CAPTCHA validation set to use: reCAPTCHA').' '.
18509:                                            &mt('version: [_1]',$confighash{'passwords'}{'recaptchaversion'}).'<br />';
18510:                             if (ref($confighash{'passwords'}{'recaptchakeys'}) eq 'HASH') {
18511:                                 $resulttext .= &mt('Public key: [_1]',$confighash{'passwords'}{'recaptchakeys'}{'public'}).'</br>'.
18512:                                                &mt('Private key: [_1]',$confighash{'passwords'}{'recaptchakeys'}{'private'}).'</li>';
18513:                             }
18514:                         } else {
18515:                             $resulttext .= '<li>'.&mt('No CAPTCHA validation').'</li>';
18516:                         }
18517:                         if ($confighash{'passwords'}{'resetlink'}) {
18518:                             $resulttext .= '<li>'.&mt('Reset link expiration set to [quant,_1,hour]',$confighash{'passwords'}{'resetlink'}).'</li>';
18519:                         } else {
18520:                             $resulttext .= '<li>'.&mt('No reset link expiration set.').' '.
18521:                                                   &mt('Will default to 2 hours').'</li>';
18522:                         }
18523:                         if (ref($confighash{'passwords'}{'resetcase'}) eq 'ARRAY') {
18524:                             if (@{$confighash{'passwords'}{'resetcase'}} == 0) {
18525:                                 $resulttext .= '<li>'.&mt('User input for username and/or e-mail address not case sensitive for "Forgot Password" web form').'</li>';
18526:                             } else {
18527:                                 my $casesens;
18528:                                 foreach my $type (@{$confighash{'passwords'}{'resetcase'}}) {
18529:                                     if ($type eq 'default') {
18530:                                         $casesens .= $othertitle.', ';
18531:                                     } elsif ($usertypes->{$type} ne '') {
18532:                                         $casesens .= $usertypes->{$type}.', ';
18533:                                     }
18534:                                 }
18535:                                 $casesens =~ s/\Q, \E$//;
18536:                                 $resulttext .= '<li>'.&mt('"Forgot Password" web form input for username and/or e-mail address is case-sensitive for: [_1]',$casesens).'</li>';
18537:                             }
18538:                         } else {
18539:                             $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>';
18540:                         }
18541:                         if ($confighash{'passwords'}{'resetprelink'} eq 'either') {
18542:                             $resulttext .= '<li>'.&mt('Users can enter either a username or an e-mail address in "Forgot Password" web form').'</li>';
18543:                         } else {
18544:                             $resulttext .= '<li>'.&mt('Users can enter both a username and an e-mail address in "Forgot Password" web form').'</li>';
18545:                         }
18546:                         if (ref($confighash{'passwords'}{'resetpostlink'}) eq 'HASH') {
18547:                             my $output;
18548:                             if (ref($types) eq 'ARRAY') {
18549:                                 foreach my $type (@{$types}) {
18550:                                     if (ref($confighash{'passwords'}{'resetpostlink'}{$type}) eq 'ARRAY') {
18551:                                         if (@{$confighash{'passwords'}{'resetpostlink'}{$type}} == 0) {
18552:                                             $output .= $usertypes->{$type}.' -- '.&mt('none');
18553:                                         } else {
18554:                                             $output .= $usertypes->{$type}.' -- '.
18555:                                                        join(', ',map { $titles{$_}; } (@{$confighash{'passwords'}{'resetpostlink'}{$type}})).'; ';
18556:                                         }
18557:                                     }
18558:                                 }
18559:                             }
18560:                             if (ref($confighash{'passwords'}{'resetpostlink'}{'default'}) eq 'ARRAY') {
18561:                                 if (@{$confighash{'passwords'}{'resetpostlink'}{'default'}} == 0) {
18562:                                     $output .= $othertitle.' -- '.&mt('none');
18563:                                 } else {
18564:                                     $output .= $othertitle.' -- '.
18565:                                                join(', ',map { $titles{$_}; } (@{$confighash{'passwords'}{'resetpostlink'}{'default'}}));
18566:                                 }
18567:                             }
18568:                             if ($output) {
18569:                                 $resulttext .= '<li>'.&mt('Information required for new password form (by user type) set to: [_1]',$output).'</li>';
18570:                             } else {
18571:                                 $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>';
18572:                             }
18573:                         } else {
18574:                             $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>';
18575:                         }
18576:                         if (ref($confighash{'passwords'}{'resetemail'}) eq 'ARRAY') {
18577:                             if (@{$confighash{'passwords'}{'resetemail'}} > 0) {
18578:                                 $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$confighash{'passwords'}{'resetemail'}})).'</li>';
18579:                             } else {
18580:                                 $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$staticdefaults{'resetemail'}})).'</li>';
18581:                             }
18582:                         } else {
18583:                             $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$staticdefaults{'resetemail'}})).'</li>';
18584:                         }
18585:                         if ($confighash{'passwords'}{'resetremove'}) {
18586:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" web form not shown').'</li>';
18587:                         } else {
18588:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" web form is shown').'</li>';
18589:                         }
18590:                         if ($confighash{'passwords'}{'resetcustom'}) {
18591:                             my $customlink = &Apache::loncommon::modal_link($confighash{'passwords'}{'resetcustom'},
18592:                                                                             &mt('custom text'),600,500,undef,undef,
18593:                                                                             undef,undef,'background-color:#ffffff');
18594:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" form includes: [_1]',$customlink).'</li>';
18595:                         } else {
18596:                             $resulttext .= '<li>'.&mt('No custom text included in preamble to "Forgot Password" form').'</li>';
18597:                         }
18598:                     } elsif ($key eq 'intauth') {
18599:                         foreach my $item ('cost','switch','check') {
18600:                             my $value = $save_defaults{$key.'_'.$item};
18601:                             if ($item eq 'switch') {
18602:                                 my %optiondesc = &Apache::lonlocal::texthash (
18603:                                                      0 => 'No',
18604:                                                      1 => 'Yes',
18605:                                                      2 => 'Yes, and copy existing passwd file to passwd.bak file',
18606:                                                  );
18607:                                 if ($value =~ /^(0|1|2)$/) {
18608:                                     $value = $optiondesc{$value};
18609:                                 } else {
18610:                                     $value = &mt('none -- defaults to No');
18611:                                 }
18612:                             } elsif ($item eq 'check') {
18613:                                 my %optiondesc = &Apache::lonlocal::texthash (
18614:                                                      0 => 'No',
18615:                                                      1 => 'Yes, allow login then update passwd file using default cost (if higher)',
18616:                                                      2 => 'Yes, disallow login if stored cost is less than domain default',
18617:                                                  );
18618:                                 if ($value =~ /^(0|1|2)$/) {
18619:                                     $value = $optiondesc{$value};
18620:                                 } else {
18621:                                     $value = &mt('none -- defaults to No');
18622:                                 }
18623:                             }
18624:                             $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$titles{$key.'_'.$item},$value).'</li>';
18625:                         }
18626:                     } elsif ($key eq 'rules') {
18627:                         foreach my $rule ('min','max','expire','numsaved') {
18628:                             if ($confighash{'passwords'}{$rule} eq '') {
18629:                                 if ($rule eq 'min') {
18630:                                     $resulttext .= '<li>'.&mt('[_1] not set.',$titles{$rule});
18631:                                                    ' '.&mt('Default of [_1] will be used',
18632:                                                            $Apache::lonnet::passwdmin).'</li>';
18633:                                 } else {
18634:                                     $resulttext .= '<li>'.&mt('[_1] set to none',$titles{$rule}).'</li>';
18635:                                 }
18636:                             } else {
18637:                                 $resulttext .= '<li>'.&mt('[_1] set to [_2]',$titles{$rule},$confighash{'passwords'}{$rule}).'</li>';
18638:                             }
18639:                         }
18640:                         if (ref($confighash{'passwords'}{'chars'}) eq 'ARRAY') {
18641:                             if (@{$confighash{'passwords'}{'chars'}} > 0) {
18642:                                 my %rulenames = &Apache::lonlocal::texthash(
18643:                                                      uc => 'At least one upper case letter',
18644:                                                      lc => 'At least one lower case letter',
18645:                                                      num => 'At least one number',
18646:                                                      spec => 'At least one non-alphanumeric',
18647:                                                    );
18648:                                 my $needed = '<ul><li>'.
18649:                                              join('</li><li>',map {$rulenames{$_} } @{$confighash{'passwords'}{'chars'}}).
18650:                                              '</li></ul>'; 
18651:                                 $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$titles{'chars'},$needed).'</li>';
18652:                             } else {
18653:                                 $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
18654:                             }
18655:                         } else {
18656:                             $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
18657:                         }
18658:                     } elsif ($key eq 'crsownerchg') {
18659:                         if (ref($confighash{'passwords'}{'crsownerchg'}) eq 'HASH') {
18660:                             if ((@{$confighash{'passwords'}{'crsownerchg'}{'by'}} == 0) ||
18661:                                 (@{$confighash{'passwords'}{'crsownerchg'}{'for'}} == 0)) {
18662:                                 $resulttext .= '<li>'.&mt('Course owner may not change student passwords.').'</li>';
18663:                             } else {
18664:                                 my %crsownerstr;
18665:                                 foreach my $item ('by','for') {
18666:                                     if (ref($confighash{'passwords'}{'crsownerchg'}{$item}) eq 'ARRAY') {
18667:                                         foreach my $type (@{$confighash{'passwords'}{'crsownerchg'}{$item}}) {
18668:                                             if ($type eq 'default') {
18669:                                                 $crsownerstr{$item} .= $othertitle.', ';
18670:                                             } elsif ($usertypes->{$type} ne '') {
18671:                                                 $crsownerstr{$item} .= $usertypes->{$type}.', ';
18672:                                             }
18673:                                         }
18674:                                         $crsownerstr{$item} =~ s/\Q, \E$//;
18675:                                     }
18676:                                 }
18677:                                 $resulttext .= '<li>'.&mt('Course owner (with status: [_1]) may change passwords for students (with status: [_2]).',
18678:                                            $crsownerstr{'by'},$crsownerstr{'for'}).'</li>';
18679:                             }
18680:                         } else {
18681:                             $resulttext .= '<li>'.&mt('Course owner may not change student passwords.').'</li>';
18682:                         }
18683:                     }
18684:                     $resulttext .= '</ul></li>';
18685:                 }
18686:             }
18687:             $resulttext .= '</ul>';
18688:         } else {
18689:             $resulttext = &mt('No changes made to password settings');
18690:         }
18691:         my $cachetime = 24*60*60;
18692:         if ($updatedefaults) {
18693:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
18694:             if (ref($lastactref) eq 'HASH') {
18695:                 $lastactref->{'domdefaults'} = 1;
18696:             }
18697:         }
18698:         if ($updateconf) {
18699:             &Apache::lonnet::do_cache_new('passwdconf',$dom,$confighash{'passwords'},$cachetime);
18700:             if (ref($lastactref) eq 'HASH') {
18701:                 $lastactref->{'passwdconf'} = 1;
18702:             }
18703:         }
18704:     } else {
18705:         $resulttext = '<span class="LC_error">'.
18706:             &mt('An error occurred: [_1]',$putresult).'</span>';
18707:     }
18708:     if ($errors) {
18709:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
18710:                        $errors.'</ul></p>';
18711:     }
18712:     return $resulttext;
18713: }
18714: 
18715: sub password_rule_changes {
18716:     my ($prefix,$newvalues,$current,$changes) = @_;
18717:     return unless ((ref($newvalues) eq 'HASH') &&
18718:                    (ref($current) eq 'HASH') &&
18719:                    (ref($changes) eq 'HASH'));
18720:     my (@rules,%staticdefaults);
18721:     if ($prefix eq 'passwords') {
18722:         @rules = ('min','max','expire','numsaved');
18723:     } elsif ($prefix eq 'secrets') {
18724:         @rules = ('min','max');
18725:     }
18726:     $staticdefaults{'min'} = $Apache::lonnet::passwdmin;
18727:     foreach my $rule (@rules) {
18728:         $env{'form.'.$prefix.'_'.$rule} =~ s/^\s+|\s+$//g;
18729:         my $ruleok;
18730:         if ($rule eq 'expire') {
18731:             if (($env{'form.'.$prefix.'_'.$rule} =~ /^\d+(|\.\d*)$/) &&
18732:                 ($env{'form.'.$prefix.'_'.$rule} ne '0')) {
18733:                 $ruleok = 1;
18734:             }
18735:         } elsif ($rule eq 'min') {
18736:             if ($env{'form.'.$prefix.'_'.$rule} =~ /^\d+$/) {
18737:                 if ($env{'form.'.$prefix.'_'.$rule} >= $staticdefaults{$rule}) {
18738:                     $ruleok = 1;
18739:                 }
18740:             }
18741:         } elsif (($env{'form.'.$prefix.'_'.$rule} =~ /^\d+$/) &&
18742:                  ($env{'form.'.$prefix.'_'.$rule} ne '0')) {
18743:             $ruleok = 1;
18744:         }
18745:         if ($ruleok) {
18746:             $newvalues->{$rule} = $env{'form.'.$prefix.'_'.$rule};
18747:             if (exists($current->{$rule})) {
18748:                 if ($newvalues->{$rule} ne $current->{$rule}) {
18749:                     $changes->{'rules'} = 1;
18750:                 }
18751:             } elsif ($rule eq 'min') {
18752:                 if ($staticdefaults{$rule} ne $newvalues->{$rule}) {
18753:                     $changes->{'rules'} = 1;
18754:                 }
18755:             } else {
18756:                 $changes->{'rules'} = 1;
18757:             }
18758:         } elsif (exists($current->{$rule})) {
18759:             $changes->{'rules'} = 1;
18760:         }
18761:     }
18762:     my @posschars = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_chars');
18763:     my @chars;
18764:     foreach my $item (sort(@posschars)) {
18765:         if ($item =~ /^(uc|lc|num|spec)$/) {
18766:             push(@chars,$item);
18767:         }
18768:     }
18769:     $newvalues->{'chars'} = \@chars;
18770:     unless ($changes->{'rules'}) {
18771:         if (ref($current->{'chars'}) eq 'ARRAY') {
18772:             my @diffs = &Apache::loncommon::compare_arrays($current->{'chars'},\@chars);
18773:             if (@diffs > 0) {
18774:                 $changes->{'rules'} = 1;
18775:             }
18776:         } else {
18777:             if (@chars > 0) {
18778:                 $changes->{'rules'} = 1;
18779:             }
18780:         }
18781:     }
18782:     return;
18783: }
18784: 
18785: sub modify_usercreation {
18786:     my ($dom,%domconfig) = @_;
18787:     my ($resulttext,%curr_usercreation,%changes,%authallowed,%cancreate,%save_usercreate);
18788:     my $warningmsg;
18789:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
18790:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
18791:             if ($key eq 'cancreate') {
18792:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
18793:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
18794:                         if (($item eq 'requestcrs') || ($item eq 'course') || ($item eq 'author')) {
18795:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
18796:                         } else {
18797:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
18798:                         }
18799:                     }
18800:                 }
18801:             } elsif ($key eq 'email_rule') {
18802:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
18803:             } else {
18804:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
18805:             }
18806:         }
18807:     }
18808:     my @username_rule = &Apache::loncommon::get_env_multiple('form.username_rule');
18809:     my @id_rule = &Apache::loncommon::get_env_multiple('form.id_rule');
18810:     my @contexts = ('author','course','requestcrs');
18811:     foreach my $item(@contexts) {
18812:         $cancreate{$item} = $env{'form.can_createuser_'.$item};
18813:     }
18814:     if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
18815:         foreach my $item (@contexts) {
18816:             if ($curr_usercreation{'cancreate'}{$item} ne $cancreate{$item}) {
18817:                 push(@{$changes{'cancreate'}},$item);
18818:             }
18819:         }
18820:     } elsif (ref($curr_usercreation{'cancreate'}) eq 'ARRAY') {
18821:         foreach my $item (@contexts) {
18822:             if (!grep(/^\Q$item\E$/,@{$curr_usercreation{'cancreate'}})) {
18823:                 if ($cancreate{$item} ne 'any') {
18824:                     push(@{$changes{'cancreate'}},$item);
18825:                 }
18826:             } else {
18827:                 if ($cancreate{$item} ne 'none') {
18828:                     push(@{$changes{'cancreate'}},$item);
18829:                 }
18830:             }
18831:         }
18832:     } else {
18833:         foreach my $item (@contexts)  {
18834:             push(@{$changes{'cancreate'}},$item);
18835:         }
18836:     }
18837: 
18838:     if (ref($curr_usercreation{'username_rule'}) eq 'ARRAY') {
18839:         foreach my $type (@{$curr_usercreation{'username_rule'}}) {
18840:             if (!grep(/^\Q$type\E$/,@username_rule)) {
18841:                 push(@{$changes{'username_rule'}},$type);
18842:             }
18843:         }
18844:         foreach my $type (@username_rule) {
18845:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'username_rule'}})) {
18846:                 push(@{$changes{'username_rule'}},$type);
18847:             }
18848:         }
18849:     } else {
18850:         push(@{$changes{'username_rule'}},@username_rule);
18851:     }
18852: 
18853:     if (ref($curr_usercreation{'id_rule'}) eq 'ARRAY') {
18854:         foreach my $type (@{$curr_usercreation{'id_rule'}}) {
18855:             if (!grep(/^\Q$type\E$/,@id_rule)) {
18856:                 push(@{$changes{'id_rule'}},$type);
18857:             }
18858:         }
18859:         foreach my $type (@id_rule) {
18860:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'id_rule'}})) {
18861:                 push(@{$changes{'id_rule'}},$type);
18862:             }
18863:         }
18864:     } else {
18865:         push(@{$changes{'id_rule'}},@id_rule);
18866:     }
18867: 
18868:     my @authen_contexts = ('author','course','domain');
18869:     my @authtypes = ('int','krb4','krb5','loc','lti');
18870:     my %authhash;
18871:     foreach my $item (@authen_contexts) {
18872:         my @authallowed =  &Apache::loncommon::get_env_multiple('form.'.$item.'_auth');
18873:         foreach my $auth (@authtypes) {
18874:             if (grep(/^\Q$auth\E$/,@authallowed)) {
18875:                 $authhash{$item}{$auth} = 1;
18876:             } else {
18877:                 $authhash{$item}{$auth} = 0;
18878:             }
18879:         }
18880:     }
18881:     if (ref($curr_usercreation{'authtypes'}) eq 'HASH') {
18882:         foreach my $item (@authen_contexts) {
18883:             if (ref($curr_usercreation{'authtypes'}{$item}) eq 'HASH') {
18884:                 foreach my $auth (@authtypes) {
18885:                     if ($authhash{$item}{$auth} ne $curr_usercreation{'authtypes'}{$item}{$auth}) {
18886:                         push(@{$changes{'authtypes'}},$item);
18887:                         last;
18888:                     }
18889:                 }
18890:             }
18891:         }
18892:     } else {
18893:         foreach my $item (@authen_contexts) {
18894:             push(@{$changes{'authtypes'}},$item);
18895:         }
18896:     }
18897: 
18898:     $save_usercreate{'cancreate'}{'course'} = $cancreate{'course'}; 
18899:     $save_usercreate{'cancreate'}{'author'} = $cancreate{'author'};
18900:     $save_usercreate{'cancreate'}{'requestcrs'} = $cancreate{'requestcrs'};
18901:     $save_usercreate{'id_rule'} = \@id_rule;
18902:     $save_usercreate{'username_rule'} = \@username_rule,
18903:     $save_usercreate{'authtypes'} = \%authhash;
18904: 
18905:     my %usercreation_hash =  (
18906:         usercreation     => \%save_usercreate,
18907:     );
18908: 
18909:     my $putresult = &Apache::lonnet::put_dom('configuration',\%usercreation_hash,
18910:                                              $dom);
18911: 
18912:     if ($putresult eq 'ok') {
18913:         if (keys(%changes) > 0) {
18914:             $resulttext = &mt('Changes made:').'<ul>';
18915:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
18916:                 my %lt = &usercreation_types();
18917:                 foreach my $type (@{$changes{'cancreate'}}) {
18918:                     my $chgtext = $lt{$type}.', ';
18919:                     if ($cancreate{$type} eq 'none') {
18920:                         $chgtext .= &mt('creation of new users is not permitted, except by a Domain Coordinator.');
18921:                     } elsif ($cancreate{$type} eq 'any') {
18922:                         $chgtext .= &mt('creation of new users is permitted for both institutional and non-institutional usernames.');
18923:                     } elsif ($cancreate{$type} eq 'official') {
18924:                         $chgtext .= &mt('creation of new users is only permitted for institutional usernames.');
18925:                     } elsif ($cancreate{$type} eq 'unofficial') {
18926:                         $chgtext .= &mt('creation of new users is only permitted for non-institutional usernames.');
18927:                     }
18928:                     $resulttext .= '<li>'.$chgtext.'</li>';
18929:                 }
18930:             }
18931:             if (ref($changes{'username_rule'}) eq 'ARRAY') {
18932:                 my ($rules,$ruleorder) = 
18933:                     &Apache::lonnet::inst_userrules($dom,'username');
18934:                 my $chgtext = '<ul>';
18935:                 foreach my $type (@username_rule) {
18936:                     if (ref($rules->{$type}) eq 'HASH') {
18937:                         $chgtext .= '<li>'.$rules->{$type}{'name'}.'</li>';
18938:                     }
18939:                 }
18940:                 $chgtext .= '</ul>';
18941:                 if (@username_rule > 0) {
18942:                     $resulttext .= '<li>'.&mt('Usernames with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';     
18943:                 } else {
18944:                     $resulttext .= '<li>'.&mt('There are now no username formats restricted to verified users in the institutional directory.').'</li>'; 
18945:                 }
18946:             }
18947:             if (ref($changes{'id_rule'}) eq 'ARRAY') {
18948:                 my ($idrules,$idruleorder) = 
18949:                     &Apache::lonnet::inst_userrules($dom,'id');
18950:                 my $chgtext = '<ul>';
18951:                 foreach my $type (@id_rule) {
18952:                     if (ref($idrules->{$type}) eq 'HASH') {
18953:                         $chgtext .= '<li>'.$idrules->{$type}{'name'}.'</li>';
18954:                     }
18955:                 }
18956:                 $chgtext .= '</ul>';
18957:                 if (@id_rule > 0) {
18958:                     $resulttext .= '<li>'.&mt('IDs with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';
18959:                 } else {
18960:                     $resulttext .= '<li>'.&mt('There are now no ID formats restricted to verified users in the institutional directory.').'</li>';
18961:                 }
18962:             }
18963:             my %authname = &authtype_names();
18964:             my %context_title = &context_names();
18965:             if (ref($changes{'authtypes'}) eq 'ARRAY') {
18966:                 my $chgtext = '<ul>';
18967:                 foreach my $type (@{$changes{'authtypes'}}) {
18968:                     my @allowed;
18969:                     $chgtext .= '<li><span class="LC_cusr_emph">'.$context_title{$type}.'</span> - '.&mt('assignable authentication types: ');
18970:                     foreach my $auth (@authtypes) {
18971:                         if ($authhash{$type}{$auth}) {
18972:                             push(@allowed,$authname{$auth});
18973:                         }
18974:                     }
18975:                     if (@allowed > 0) {
18976:                         $chgtext .= join(', ',@allowed).'</li>';
18977:                     } else {
18978:                         $chgtext .= &mt('none').'</li>';
18979:                     }
18980:                 }
18981:                 $chgtext .= '</ul>';
18982:                 $resulttext .= '<li>'.&mt('Authentication types available for assignment to new users').'<br />'.$chgtext;
18983:                 $resulttext .= '</li>';
18984:             }
18985:             $resulttext .= '</ul>';
18986:         } else {
18987:             $resulttext = &mt('No changes made to user creation settings');
18988:         }
18989:     } else {
18990:         $resulttext = '<span class="LC_error">'.
18991:             &mt('An error occurred: [_1]',$putresult).'</span>';
18992:     }
18993:     if ($warningmsg ne '') {
18994:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
18995:     }
18996:     return $resulttext;
18997: }
18998: 
18999: sub modify_selfcreation {
19000:     my ($dom,$lastactref,%domconfig) = @_;
19001:     my ($resulttext,$warningmsg,%curr_usercreation,%curr_usermodify,%curr_inststatus,%changes,%cancreate);
19002:     my (%save_usercreate,%save_usermodify,%save_inststatus,@types,%usertypes);
19003:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
19004:     my ($othertitle,$usertypesref,$typesref) = &Apache::loncommon::sorted_inst_types($dom);
19005:     if (ref($typesref) eq 'ARRAY') {
19006:         @types = @{$typesref};
19007:     }
19008:     if (ref($usertypesref) eq 'HASH') {
19009:         %usertypes = %{$usertypesref};
19010:     }
19011:     $usertypes{'default'} = $othertitle;
19012: #
19013: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usercreation'}.
19014: #
19015:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
19016:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
19017:             if ($key eq 'cancreate') {
19018:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
19019:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
19020:                         if (($item eq 'selfcreate') || ($item eq 'statustocreate') ||
19021:                             ($item eq 'captcha') || ($item eq 'recaptchakeys') ||
19022:                             ($item eq 'recaptchaversion') || ($item eq 'notify') ||
19023:                             ($item eq 'emailusername') || ($item eq 'shibenv') ||
19024:                             ($item eq 'selfcreateprocessing') || ($item eq 'emailverified') ||
19025:                             ($item eq 'emailoptions') || ($item eq 'emaildomain')) {
19026:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
19027:                         } else {
19028:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
19029:                         }
19030:                     }
19031:                 }
19032:             } elsif ($key eq 'email_rule') {
19033:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
19034:             } else {
19035:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
19036:             }
19037:         }
19038:     }
19039: #
19040: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usermodification'}.
19041: #
19042:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
19043:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
19044:             if ($key eq 'selfcreate') {
19045:                 $curr_usermodify{$key} = $domconfig{'usermodification'}{$key};
19046:             } else {
19047:                 $save_usermodify{$key} = $domconfig{'usermodification'}{$key};
19048:             }
19049:         }
19050:     }
19051: #
19052: # Retrieve current domain configuration for institutional status types from $domconfig{'inststatus'}.
19053: #
19054:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
19055:         foreach my $key (keys(%{$domconfig{'inststatus'}})) {
19056:             if ($key eq 'inststatusguest') {
19057:                 $curr_inststatus{$key} = $domconfig{'inststatus'}{$key};
19058:             } else {
19059:                 $save_inststatus{$key} = $domconfig{'inststatus'}{$key};
19060:             }
19061:         }
19062:     }
19063: 
19064:     my @contexts = ('selfcreate');
19065:     @{$cancreate{'selfcreate'}} = ();
19066:     %{$cancreate{'emailusername'}} = ();
19067:     if (@types) {
19068:         @{$cancreate{'statustocreate'}} = ();
19069:     }
19070:     %{$cancreate{'selfcreateprocessing'}} = ();
19071:     %{$cancreate{'shibenv'}} = ();
19072:     %{$cancreate{'emailverified'}} = ();
19073:     %{$cancreate{'emailoptions'}} = ();
19074:     %{$cancreate{'emaildomain'}} = ();
19075:     my %selfcreatetypes = (
19076:                              sso   => 'users authenticated by institutional single sign on',
19077:                              login => 'users authenticated by institutional log-in',
19078:                              email => 'users verified by e-mail',
19079:                           );
19080: #
19081: # Populate $cancreate{'selfcreate'} array reference with types of user, for which self-creation of user accounts
19082: # is permitted.
19083: #
19084:     my ($emailrules,$emailruleorder) = &Apache::lonnet::inst_userrules($dom,'email');
19085: 
19086:     my (@statuses,%email_rule);
19087:     foreach my $item ('login','sso','email') {
19088:         if ($item eq 'email') {
19089:             if ($env{'form.cancreate_email'}) {
19090:                 if (@types) {
19091:                     my @poss_statuses = &Apache::loncommon::get_env_multiple('form.selfassign');
19092:                     foreach my $status (@poss_statuses) {
19093:                         if (grep(/^\Q$status\E$/,(@types,'default'))) {
19094:                             push(@statuses,$status);
19095:                         }
19096:                     }
19097:                     $save_inststatus{'inststatusguest'} = \@statuses;
19098:                 } else {
19099:                     push(@statuses,'default');
19100:                 }
19101:                 if (@statuses) {
19102:                     my %curr_rule;
19103:                     if (ref($curr_usercreation{'email_rule'}) eq 'ARRAY') {
19104:                         foreach my $type (@statuses) {
19105:                             $curr_rule{$type} = $curr_usercreation{'email_rule'};
19106:                         }
19107:                     } elsif (ref($curr_usercreation{'email_rule'}) eq 'HASH') {
19108:                         foreach my $type (@statuses) {
19109:                             $curr_rule{$type} = $curr_usercreation{'email_rule'}{$type};
19110:                         }
19111:                     }
19112:                     push(@{$cancreate{'selfcreate'}},'email');
19113:                     push(@contexts,('selfcreateprocessing','emailverified','emailoptions'));
19114:                     my %curremaildom;
19115:                     if (ref($curr_usercreation{'cancreate'}{'emaildomain'}) eq 'HASH') {
19116:                         %curremaildom = %{$curr_usercreation{'cancreate'}{'emaildomain'}};
19117:                     }
19118:                     foreach my $type (@statuses) {
19119:                         if ($env{'form.cancreate_emailprocess_'.$type} =~ /^(?:approval|automatic)$/) {
19120:                             $cancreate{'selfcreateprocessing'}{$type} = $env{'form.cancreate_emailprocess_'.$type};
19121:                         }
19122:                         if ($env{'form.cancreate_usernameoptions_'.$type} =~ /^(?:all|first|free)$/) {
19123:                             $cancreate{'emailverified'}{$type} = $env{'form.cancreate_usernameoptions_'.$type};
19124:                         }
19125:                         if ($env{'form.cancreate_emailoptions_'.$type} =~ /^(any|inst|noninst|custom)$/) {
19126: #
19127: # Retrieve rules (if any) governing types of e-mail address which may be used to verify a username.
19128: #
19129:                             my $chosen = $1;
19130:                             if (($chosen eq 'inst') || ($chosen eq 'noninst')) {
19131:                                 my $emaildom;
19132:                                 if ($env{'form.cancreate_emaildomain_'.$chosen.'_'.$type} =~ /^\@[^\@]+$/) {
19133:                                     $emaildom = $env{'form.cancreate_emaildomain_'.$chosen.'_'.$type}; 
19134:                                     $cancreate{'emaildomain'}{$type}{$chosen} = $emaildom;
19135:                                     if (ref($curremaildom{$type}) eq 'HASH') {
19136:                                         if (exists($curremaildom{$type}{$chosen})) {
19137:                                             if ($curremaildom{$type}{$chosen} ne $emaildom) {
19138:                                                 push(@{$changes{'cancreate'}},'emaildomain');
19139:                                             }
19140:                                         } elsif ($emaildom ne '') {
19141:                                             push(@{$changes{'cancreate'}},'emaildomain');
19142:                                         }
19143:                                     } elsif ($emaildom ne '') {
19144:                                         push(@{$changes{'cancreate'}},'emaildomain');
19145:                                     } 
19146:                                 }
19147:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
19148:                             } elsif ($chosen eq 'custom') {
19149:                                 my @possemail_rules = &Apache::loncommon::get_env_multiple('form.email_rule_'.$type);
19150:                                 $email_rule{$type} = [];
19151:                                 if (ref($emailrules) eq 'HASH') {
19152:                                     foreach my $rule (@possemail_rules) {
19153:                                         if (exists($emailrules->{$rule})) {
19154:                                             push(@{$email_rule{$type}},$rule);
19155:                                         }
19156:                                     }
19157:                                 }
19158:                                 if (@{$email_rule{$type}}) {
19159:                                     $cancreate{'emailoptions'}{$type} = 'custom';
19160:                                     if (ref($curr_rule{$type}) eq 'ARRAY') {
19161:                                         if (@{$curr_rule{$type}} > 0) {
19162:                                             foreach my $rule (@{$curr_rule{$type}}) {
19163:                                                 if (!grep(/^\Q$rule\E$/,@{$email_rule{$type}})) {
19164:                                                     push(@{$changes{'email_rule'}},$type);
19165:                                                 }
19166:                                             }
19167:                                         }
19168:                                         foreach my $type (@{$email_rule{$type}}) {
19169:                                             if (!grep(/^\Q$type\E$/,@{$curr_rule{$type}})) {
19170:                                                 push(@{$changes{'email_rule'}},$type);
19171:                                             }
19172:                                         }
19173:                                     } else {
19174:                                         push(@{$changes{'email_rule'}},$type);
19175:                                     }
19176:                                 }
19177:                             } else {
19178:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
19179:                             }
19180:                         }
19181:                     }
19182:                     if (@types) {
19183:                         if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
19184:                             my @changed = &Apache::loncommon::compare_arrays(\@statuses,$curr_inststatus{'inststatusguest'});
19185:                             if (@changed) {
19186:                                 push(@{$changes{'inststatus'}},'inststatusguest');
19187:                             }
19188:                         } else {
19189:                             push(@{$changes{'inststatus'}},'inststatusguest');
19190:                         }
19191:                     }
19192:                 } else {
19193:                     delete($env{'form.cancreate_email'});
19194:                     if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
19195:                         if (@{$curr_inststatus{'inststatusguest'}} > 0) {
19196:                             push(@{$changes{'inststatus'}},'inststatusguest');
19197:                         }
19198:                     }
19199:                 }
19200:             } else {
19201:                 $save_inststatus{'inststatusguest'} = [];
19202:                 if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
19203:                     if (@{$curr_inststatus{'inststatusguest'}} > 0) {
19204:                         push(@{$changes{'inststatus'}},'inststatusguest');
19205:                     }
19206:                 }
19207:             }
19208:         } else {
19209:             if ($env{'form.cancreate_'.$item}) {
19210:                 push(@{$cancreate{'selfcreate'}},$item);
19211:             }
19212:         }
19213:     }
19214:     my (%userinfo,%savecaptcha);
19215:     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
19216: #
19217: # Populate $cancreate{'emailusername'}{$type} hash ref with information fields (if new user will provide data
19218: # value set to one), if self-creation with e-mail address permitted, where $type is user type: faculty, staff, student etc.
19219: #
19220: 
19221:     if ($env{'form.cancreate_email'}) {
19222:         push(@contexts,'emailusername');
19223:         if (@statuses) {
19224:             foreach my $type (@statuses) {
19225:                 if (ref($infofields) eq 'ARRAY') {
19226:                     foreach my $field (@{$infofields}) {
19227:                         if ($env{'form.canmodify_emailusername_'.$type.'_'.$field} =~ /^(required|optional)$/) {
19228:                             $cancreate{'emailusername'}{$type}{$field} = $1;
19229:                         }
19230:                     }
19231:                 }
19232:             }
19233:         }
19234: #
19235: # Populate $cancreate{'notify'} hash ref with names of Domain Coordinators who are to be notified of
19236: # queued requests for self-creation of account verified by e-mail.
19237: #
19238: 
19239:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.selfcreationnotifyapproval');
19240:         @approvalnotify = sort(@approvalnotify);
19241:         $cancreate{'notify'}{'approval'} = join(',',@approvalnotify);
19242:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
19243:             if (ref($curr_usercreation{'cancreate'}{'notify'}) eq 'HASH') {
19244:                 if ($curr_usercreation{'cancreate'}{'notify'}{'approval'} ne $cancreate{'notify'}{'approval'}) {
19245:                     push(@{$changes{'cancreate'}},'notify');
19246:                 }
19247:             } else {
19248:                 if ($cancreate{'notify'}{'approval'}) {
19249:                     push(@{$changes{'cancreate'}},'notify');
19250:                 }
19251:             }
19252:         } elsif ($cancreate{'notify'}{'approval'}) {
19253:             push(@{$changes{'cancreate'}},'notify');
19254:         }
19255: 
19256:         &process_captcha('cancreate',\%changes,\%savecaptcha,$curr_usercreation{'cancreate'});
19257:     }
19258: #  
19259: # Check if domain default is set appropriately, if self-creation of accounts is to be available for
19260: # institutional log-in.
19261: #
19262:     if (grep(/^login$/,@{$cancreate{'selfcreate'}})) {
19263:         if (!((($domdefaults{'auth_def'} =~/^krb/) && ($domdefaults{'auth_arg_def'} ne '')) || 
19264:                ($domdefaults{'auth_def'} eq 'localauth'))) {
19265:             $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.').' '.
19266:                           &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.');
19267:         }
19268:     }
19269:     my @fields = ('lastname','firstname','middlename','generation',
19270:                   'permanentemail','id');
19271:     my @shibfields = (@fields,'inststatus');
19272:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
19273: #
19274: # Where usernames may created for institutional log-in and/or institutional single sign on:
19275: # (a) populate $cancreate{'statustocreate'} array reference with institutional status types who
19276: # may self-create accounts 
19277: # (b) populate $save_usermodify{'selfcreate'} hash reference with status types, and information fields
19278: # which the user may supply, if institutional data is unavailable.
19279: #
19280:     if (($env{'form.cancreate_login'}) || ($env{'form.cancreate_sso'})) {
19281:         if (@types) {
19282:             @{$cancreate{'statustocreate'}} = &Apache::loncommon::get_env_multiple('form.statustocreate');
19283:             push(@contexts,'statustocreate');
19284:             foreach my $type (@types) {
19285:                 my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$type);
19286:                 foreach my $field (@fields) {
19287:                     if (grep(/^\Q$field\E$/,@modifiable)) {
19288:                         $save_usermodify{'selfcreate'}{$type}{$field} = 1;
19289:                     } else {
19290:                         $save_usermodify{'selfcreate'}{$type}{$field} = 0;
19291:                     }
19292:                 }
19293:             }
19294:             if (ref($curr_usermodify{'selfcreate'}) eq 'HASH') {
19295:                 foreach my $type (@types) {
19296:                     if (ref($curr_usermodify{'selfcreate'}{$type}) eq 'HASH') {
19297:                         foreach my $field (@fields) {
19298:                             if ($save_usermodify{'selfcreate'}{$type}{$field} ne
19299:                                 $curr_usermodify{'selfcreate'}{$type}{$field}) {
19300:                                 push(@{$changes{'selfcreate'}},$type);
19301:                                 last;
19302:                             }
19303:                         }
19304:                     }
19305:                 }
19306:             } else {
19307:                 foreach my $type (@types) {
19308:                     push(@{$changes{'selfcreate'}},$type);
19309:                 }
19310:             }
19311:         }
19312:         foreach my $field (@shibfields) {
19313:             if ($env{'form.shibenv_'.$field} ne '') {
19314:                 $cancreate{'shibenv'}{$field} = $env{'form.shibenv_'.$field};
19315:             }
19316:         }
19317:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
19318:             if (ref($curr_usercreation{'cancreate'}{'shibenv'}) eq 'HASH') {
19319:                 foreach my $field (@shibfields) {
19320:                     if ($env{'form.shibenv_'.$field} ne $curr_usercreation{'cancreate'}{'shibenv'}{$field}) {
19321:                         push(@{$changes{'cancreate'}},'shibenv');
19322:                     }
19323:                 }
19324:             } else {
19325:                 foreach my $field (@shibfields) {
19326:                     if ($env{'form.shibenv_'.$field}) {
19327:                         push(@{$changes{'cancreate'}},'shibenv');
19328:                         last;
19329:                     }
19330:                 }
19331:             }
19332:         }
19333:     }
19334:     foreach my $item (@contexts) {
19335:         if (ref($curr_usercreation{'cancreate'}{$item}) eq 'ARRAY') {
19336:             foreach my $curr (@{$curr_usercreation{'cancreate'}{$item}}) {
19337:                 if (ref($cancreate{$item}) eq 'ARRAY') {
19338:                     if (!grep(/^$curr$/,@{$cancreate{$item}})) {
19339:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19340:                             push(@{$changes{'cancreate'}},$item);
19341:                         }
19342:                     }
19343:                 }
19344:             }
19345:             if (ref($cancreate{$item}) eq 'ARRAY') {
19346:                 foreach my $type (@{$cancreate{$item}}) {
19347:                     if (!grep(/^$type$/,@{$curr_usercreation{'cancreate'}{$item}})) {
19348:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19349:                             push(@{$changes{'cancreate'}},$item);
19350:                         }
19351:                     }
19352:                 }
19353:             }
19354:         } elsif (ref($curr_usercreation{'cancreate'}{$item}) eq 'HASH') {
19355:             if (ref($cancreate{$item}) eq 'HASH') {
19356:                 foreach my $type (keys(%{$curr_usercreation{'cancreate'}{$item}})) {
19357:                     if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
19358:                         foreach my $field (keys(%{$curr_usercreation{'cancreate'}{$item}{$type}})) {
19359:                             unless ($curr_usercreation{'cancreate'}{$item}{$type}{$field} eq $cancreate{$item}{$type}{$field}) {
19360:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19361:                                     push(@{$changes{'cancreate'}},$item);
19362:                                 }
19363:                             }
19364:                         }
19365:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
19366:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
19367:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19368:                                 push(@{$changes{'cancreate'}},$item);
19369:                             }
19370:                         }
19371:                     }
19372:                 }
19373:                 foreach my $type (keys(%{$cancreate{$item}})) {
19374:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
19375:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
19376:                             if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
19377:                                 unless ($curr_usercreation{'cancreate'}{$item}{$type}{$field} eq $cancreate{$item}{$type}{$field}) {
19378:                                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19379:                                         push(@{$changes{'cancreate'}},$item);
19380:                                     }
19381:                                 }
19382:                             } else {
19383:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19384:                                     push(@{$changes{'cancreate'}},$item);
19385:                                 }
19386:                             }
19387:                         }
19388:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
19389:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
19390:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19391:                                 push(@{$changes{'cancreate'}},$item);
19392:                             }
19393:                         }
19394:                     }
19395:                 }
19396:             }
19397:         } elsif ($curr_usercreation{'cancreate'}{$item}) {
19398:             if (ref($cancreate{$item}) eq 'ARRAY') {
19399:                 if (!grep(/^\Q$curr_usercreation{'cancreate'}{$item}\E$/,@{$cancreate{$item}})) {
19400:                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19401:                         push(@{$changes{'cancreate'}},$item);
19402:                     }
19403:                 }
19404:             }
19405:         } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
19406:             if (ref($cancreate{$item}) eq 'HASH') {
19407:                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19408:                     push(@{$changes{'cancreate'}},$item);
19409:                 }
19410:             }
19411:         } elsif ($item eq 'emailusername') {
19412:             if (ref($cancreate{$item}) eq 'HASH') {
19413:                 foreach my $type (keys(%{$cancreate{$item}})) {
19414:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
19415:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
19416:                             if ($cancreate{$item}{$type}{$field}) {
19417:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19418:                                     push(@{$changes{'cancreate'}},$item);
19419:                                 }
19420:                                 last;
19421:                             }
19422:                         }
19423:                     }
19424:                 }
19425:             }
19426:         }
19427:     }
19428: #
19429: # Populate %save_usercreate hash with updates to self-creation configuration.
19430: #
19431:     $save_usercreate{'cancreate'}{'captcha'} = $savecaptcha{'captcha'};
19432:     $save_usercreate{'cancreate'}{'recaptchakeys'} = $savecaptcha{'recaptchakeys'};
19433:     $save_usercreate{'cancreate'}{'recaptchaversion'} = $savecaptcha{'recaptchaversion'};
19434:     $save_usercreate{'cancreate'}{'selfcreate'} = $cancreate{'selfcreate'};
19435:     if (ref($cancreate{'notify'}) eq 'HASH') {
19436:         $save_usercreate{'cancreate'}{'notify'} = $cancreate{'notify'};
19437:     }
19438:     if (ref($cancreate{'selfcreateprocessing'}) eq 'HASH') {
19439:         $save_usercreate{'cancreate'}{'selfcreateprocessing'} = $cancreate{'selfcreateprocessing'};
19440:     }
19441:     if (ref($cancreate{'emailverified'}) eq 'HASH') {
19442:         $save_usercreate{'cancreate'}{'emailverified'} = $cancreate{'emailverified'};
19443:     }
19444:     if (ref($cancreate{'emailoptions'}) eq 'HASH') {
19445:         $save_usercreate{'cancreate'}{'emailoptions'} = $cancreate{'emailoptions'};
19446:     }
19447:     if (ref($cancreate{'emaildomain'}) eq 'HASH') {
19448:         $save_usercreate{'cancreate'}{'emaildomain'} = $cancreate{'emaildomain'};
19449:     }
19450:     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
19451:         $save_usercreate{'cancreate'}{'statustocreate'} = $cancreate{'statustocreate'};
19452:     }
19453:     if (ref($cancreate{'shibenv'}) eq 'HASH') {
19454:         $save_usercreate{'cancreate'}{'shibenv'} = $cancreate{'shibenv'};
19455:     }
19456:     $save_usercreate{'cancreate'}{'emailusername'} = $cancreate{'emailusername'};
19457:     $save_usercreate{'email_rule'} = \%email_rule;
19458: 
19459:     my %userconfig_hash = (
19460:             usercreation     => \%save_usercreate,
19461:             usermodification => \%save_usermodify,
19462:             inststatus       => \%save_inststatus,
19463:     );
19464: 
19465:     my $putresult = &Apache::lonnet::put_dom('configuration',\%userconfig_hash,
19466:                                              $dom);
19467: #
19468: # Accumulate details of changes to domain configuration for self-creation of usernames in $resulttext
19469: #
19470:     if ($putresult eq 'ok') {
19471:         if (keys(%changes) > 0) {
19472:             $resulttext = &mt('Changes made:').'<ul>';
19473:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
19474:                 my %lt = &selfcreation_types();
19475:                 foreach my $type (@{$changes{'cancreate'}}) {
19476:                     my $chgtext = '';
19477:                     if ($type eq 'selfcreate') {
19478:                         if (@{$cancreate{$type}} == 0) {
19479:                             $chgtext .= &mt('Self creation of a new user account is not permitted.');
19480:                         } else {
19481:                             $chgtext .= &mt('Self-creation of a new account is permitted for:').
19482:                                         '<ul>';
19483:                             foreach my $case (@{$cancreate{$type}}) {
19484:                                 $chgtext .= '<li>'.$selfcreatetypes{$case}.'</li>';
19485:                             }
19486:                             $chgtext .= '</ul>';
19487:                             if (ref($cancreate{$type}) eq 'ARRAY') {
19488:                                 if (grep(/^(login|sso)$/,@{$cancreate{$type}})) {
19489:                                     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
19490:                                         if (@{$cancreate{'statustocreate'}} == 0) {
19491:                                             $chgtext .= '<span class="LC_warning">'.
19492:                                                         &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts via log-in or single sign-on.").
19493:                                                         '</span><br />';
19494:                                         }
19495:                                     }
19496:                                 }
19497:                                 if (grep(/^email$/,@{$cancreate{$type}})) {
19498:                                     if (!@statuses) {
19499:                                         $chgtext .= '<span class="LC_warning">'.
19500:                                                     &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.").
19501:                                                     '</span><br />';
19502: 
19503:                                     }
19504:                                 }
19505:                             }
19506:                         }
19507:                     } elsif ($type eq 'shibenv') {
19508:                         if (keys(%{$cancreate{$type}}) == 0) {
19509:                             $chgtext .= &mt('Shibboleth-autheticated user does not use environment variables to set user information').'<br />'; 
19510:                         } else {
19511:                             $chgtext .= &mt('Shibboleth-autheticated user information set from environment variables, as follows:').
19512:                                         '<ul>';
19513:                             foreach my $field (@shibfields) {
19514:                                 next if ($cancreate{$type}{$field} eq '');
19515:                                 if ($field eq 'inststatus') {
19516:                                     $chgtext .= '<li>'.&mt('Institutional status').' -- '.$cancreate{$type}{$field}.'</li>';
19517:                                 } else {
19518:                                     $chgtext .= '<li>'.$fieldtitles{$field}.' -- '.$cancreate{$type}{$field}.'</li>';
19519:                                 }
19520:                             }
19521:                             $chgtext .= '</ul>';
19522:                         }
19523:                     } elsif ($type eq 'statustocreate') {
19524:                         if ((ref($cancreate{'selfcreate'}) eq 'ARRAY') &&
19525:                             (ref($cancreate{'statustocreate'}) eq 'ARRAY')) {
19526:                             if (@{$cancreate{'selfcreate'}} > 0) {
19527:                                 if (@{$cancreate{'statustocreate'}} == 0) {
19528:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts set to 'None'.");
19529:                                     if (!grep(/^email$/,@{$cancreate{'selfcreate'}})) {
19530:                                         $chgtext .= '<br />'.
19531:                                                     '<span class="LC_warning">'.
19532:                                                     &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts.").
19533:                                                     '</span>';
19534:                                     }
19535:                                 } elsif (keys(%usertypes) > 0) {
19536:                                     if (grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
19537:                                         $chgtext .= &mt('Creation of a new account for an institutional user is restricted to the following institutional affiliation(s):');
19538:                                     } else {
19539:                                         $chgtext .= &mt('Institutional affiliations permitted to create accounts with institutional authentication were set as follows:');
19540:                                     }
19541:                                     $chgtext .= '<ul>';
19542:                                     foreach my $case (@{$cancreate{$type}}) {
19543:                                         if ($case eq 'default') {
19544:                                             $chgtext .= '<li>'.$othertitle.'</li>';
19545:                                         } else {
19546:                                             $chgtext .= '<li>'.$usertypes{$case}.'</li>';
19547:                                         }
19548:                                     }
19549:                                     $chgtext .= '</ul>';
19550:                                     if (!grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
19551:                                         $chgtext .= '<span class="LC_warning">'.
19552:                                                     &mt('However, users authenticated by institutional login/single sign on are not currently permitted to create accounts.').
19553:                                                     '</span>';
19554:                                     }
19555:                                 }
19556:                             } else {
19557:                                 if (@{$cancreate{$type}} == 0) {
19558:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts were set to 'none'.");
19559:                                 } else {
19560:                                     $chgtext .= &mt('Although institutional affiliations permitted to create accounts were changed, self creation of accounts is not currently permitted for any authentication types.');
19561:                                 }
19562:                             }
19563:                             $chgtext .= '<br />';
19564:                         }
19565:                     } elsif ($type eq 'selfcreateprocessing') {
19566:                         my %choices = &Apache::lonlocal::texthash (
19567:                                                                     automatic => 'Automatic approval',
19568:                                                                     approval  => 'Queued for approval',
19569:                                                                   );
19570:                         if (@types) {
19571:                             if (@statuses) {
19572:                                 $chgtext .= &mt('Processing of requests to create account with e-mail verification set as follows:'). 
19573:                                             '<ul>';
19574:                                 foreach my $status (@statuses) {
19575:                                     if ($status eq 'default') {
19576:                                         $chgtext .= '<li>'.$othertitle.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
19577:                                     } else {
19578:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
19579:                                     }
19580:                                 }
19581:                                 $chgtext .= '</ul>';
19582:                             }
19583:                         } else {
19584:                             $chgtext .= &mt('Processing of requests to create account with e-mail verification set to: "[_1]"',
19585:                                             $choices{$cancreate{'selfcreateprocessing'}{'default'}});
19586:                         }
19587:                     } elsif ($type eq 'emailverified') {
19588:                         my %options = &Apache::lonlocal::texthash (
19589:                                                                     all   => 'Same as e-mail',
19590:                                                                     first => 'Omit @domain',
19591:                                                                     free  => 'Free to choose',
19592:                                                                   );
19593:                         if (@types) {
19594:                             if (@statuses) {
19595:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, username is set as follows:').
19596:                                             '<ul>';
19597:                                 foreach my $status (@statuses) {
19598:                                     if ($status eq 'default') {
19599:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
19600:                                     } else {
19601:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
19602:                                     }
19603:                                 }
19604:                                 $chgtext .= '</ul>';
19605:                             }
19606:                         } else {
19607:                             $chgtext .= &mt("For self-created accounts verified by e-mail address, user's username is: '[_1]'",
19608:                                             $options{$cancreate{'emailverified'}{'default'}});
19609:                         }
19610:                     } elsif ($type eq 'emailoptions') {
19611:                         my %options = &Apache::lonlocal::texthash (
19612:                                                                     any     => 'Any e-mail',
19613:                                                                     inst    => 'Institutional only',
19614:                                                                     noninst => 'Non-institutional only',
19615:                                                                     custom  => 'Custom restrictions',
19616:                                                                   );
19617:                         if (@types) {
19618:                             if (@statuses) {
19619:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, requirements for e-mail address are as follows:').
19620:                                             '<ul>';
19621:                                 foreach my $status (@statuses) {
19622:                                     if ($type eq 'default') {
19623:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
19624:                                     } else {
19625:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
19626:                                     }
19627:                                 }
19628:                                 $chgtext .= '</ul>';
19629:                             }
19630:                         } else {
19631:                             if ($cancreate{'emailoptions'}{'default'} eq 'any') {
19632:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, any e-mail may be used');
19633:                             } else {
19634:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, e-mail restricted to: "[_1]"',
19635:                                                 $options{$cancreate{'emailoptions'}{'default'}});
19636:                             }
19637:                         }
19638:                     } elsif ($type eq 'emaildomain') {
19639:                         my $output;
19640:                         if (@statuses) {
19641:                             foreach my $type (@statuses) {
19642:                                 if (ref($cancreate{'emaildomain'}{$type}) eq 'HASH') {
19643:                                     if ($cancreate{'emailoptions'}{$type} eq 'inst') {
19644:                                         if ($type eq 'default') {
19645:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
19646:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} eq '')) {
19647:                                                 $output = '<li>'.$othertitle.' -- '.&mt('No restriction on e-mail domain').'</li>';
19648:                                             } else {
19649:                                                 $output = '<li>'.$othertitle.' -- '.&mt("User's e-mail address needs to end: [_1]",
19650:                                                                                         $cancreate{'emaildomain'}{$type}{'inst'}).'</li>';
19651:                                             }
19652:                                         } else {
19653:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
19654:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} eq '')) {
19655:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
19656:                                             } else {
19657:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address needs to end: [_1]",
19658:                                                                                               $cancreate{'emaildomain'}{$type}{'inst'}).'</li>'; 
19659:                                             }
19660:                                         }
19661:                                     } elsif ($cancreate{'emailoptions'}{$type} eq 'noninst') {
19662:                                         if ($type eq 'default') {
19663:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
19664:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
19665:                                                 $output = '<li>'.$othertitle.' -- '.&mt('No restriction on e-mail domain').'</li>';
19666:                                             } else {
19667:                                                 $output = '<li>'.$othertitle.' -- '.&mt("User's e-mail address must not end: [_1]",
19668:                                                                                         $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';
19669:                                             }
19670:                                         } else {
19671:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
19672:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
19673:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
19674:                                             } else {
19675:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address must not end: [_1]",
19676:                                                                                                 $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';   
19677:                                             }
19678:                                         }
19679:                                     }
19680:                                 }
19681:                             }
19682:                         }
19683:                         if ($output ne '') {
19684:                             $chgtext .= &mt('For self-created accounts verified by e-mail address:').
19685:                                         '<ul>'.$output.'</ul>';
19686:                         }
19687:                     } elsif ($type eq 'captcha') {
19688:                         if ($savecaptcha{$type} eq 'notused') {
19689:                             $chgtext .= &mt('No CAPTCHA validation in use for self-creation screen.');
19690:                         } else {
19691:                             my %captchas = &captcha_phrases();
19692:                             if ($captchas{$savecaptcha{$type}}) {
19693:                                 $chgtext .= &mt("Validation for self-creation screen set to $captchas{$savecaptcha{$type}}.");
19694:                             } else {
19695:                                 $chgtext .= &mt('Validation for self-creation screen set to unknown type.');
19696:                             }
19697:                         }
19698:                     } elsif ($type eq 'recaptchakeys') {
19699:                         my ($privkey,$pubkey);
19700:                         if (ref($savecaptcha{$type}) eq 'HASH') {
19701:                             $pubkey = $savecaptcha{$type}{'public'};
19702:                             $privkey = $savecaptcha{$type}{'private'};
19703:                         }
19704:                         $chgtext .= &mt('ReCAPTCHA keys changes').'<ul>';
19705:                         if (!$pubkey) {
19706:                             $chgtext .= '<li>'.&mt('Public key deleted').'</li>';
19707:                         } else {
19708:                             $chgtext .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
19709:                         }
19710:                         if (!$privkey) {
19711:                             $chgtext .= '<li>'.&mt('Private key deleted').'</li>';
19712:                         } else {
19713:                             $chgtext .= '<li>'.&mt('Private key set to [_1]',$pubkey).'</li>';
19714:                         }
19715:                         $chgtext .= '</ul>';
19716:                     } elsif ($type eq 'recaptchaversion') {
19717:                         if ($savecaptcha{'captcha'} eq 'recaptcha') {
19718:                             $chgtext .= &mt('ReCAPTCHA set to version [_1]',$savecaptcha{$type});
19719:                         }
19720:                     } elsif ($type eq 'emailusername') {
19721:                         if (ref($cancreate{'emailusername'}) eq 'HASH') {
19722:                             if (@statuses) {
19723:                                 foreach my $type (@statuses) {
19724:                                     if (ref($cancreate{'emailusername'}{$type}) eq 'HASH') {
19725:                                         if (keys(%{$cancreate{'emailusername'}{$type}}) > 0) {
19726:                                             $chgtext .= &mt('When self-creating account with e-mail verification, the following information will be provided by [_1]:',"'$usertypes{$type}'").
19727:                                                     '<ul>';
19728:                                             foreach my $field (@{$infofields}) {
19729:                                                 if ($cancreate{'emailusername'}{$type}{$field}) {
19730:                                                     $chgtext .= '<li>'.$infotitles->{$field}.'</li>';
19731:                                                 }
19732:                                             }
19733:                                             $chgtext .= '</ul>';
19734:                                         } else {
19735:                                             $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
19736:                                         }
19737:                                     } else {
19738:                                         $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
19739:                                     }
19740:                                 }
19741:                             }
19742:                         }
19743:                     } elsif ($type eq 'notify') {
19744:                         my $numapprove = 0;
19745:                         if (ref($changes{'cancreate'}) eq 'ARRAY') {
19746:                             if ((grep(/^notify$/,@{$changes{'cancreate'}})) && (ref($cancreate{'notify'}) eq 'HASH')) {
19747:                                 if ($cancreate{'notify'}{'approval'}) {
19748:                                     $chgtext .= &mt('Notification of username requests requiring approval will be sent to: ').$cancreate{'notify'}{'approval'};
19749:                                     $numapprove ++;
19750:                                 }
19751:                             }
19752:                         }
19753:                         unless ($numapprove) {
19754:                             $chgtext .= &mt('No Domain Coordinators will receive notification of username requests requiring approval.');
19755:                         }
19756:                     }
19757:                     if ($chgtext) {
19758:                         $resulttext .= '<li>'.$chgtext.'</li>';
19759:                     }
19760:                 }
19761:             }
19762:             if ((ref($changes{'email_rule'}) eq 'ARRAY') && (@{$changes{'email_rule'}} > 0)) {
19763:                 my ($emailrules,$emailruleorder) =
19764:                     &Apache::lonnet::inst_userrules($dom,'email');
19765:                 foreach my $type (@{$changes{'email_rule'}}) {
19766:                     if (ref($email_rule{$type}) eq 'ARRAY') {
19767:                         my $chgtext = '<ul>';
19768:                         foreach my $rule (@{$email_rule{$type}}) {
19769:                             if (ref($emailrules->{$rule}) eq 'HASH') {
19770:                                 $chgtext .= '<li>'.$emailrules->{$rule}{'name'}.'</li>';
19771:                             }
19772:                         }
19773:                         $chgtext .= '</ul>';
19774:                         my $typename;
19775:                         if (@types) {
19776:                             if ($type eq 'default') {
19777:                                 $typename = $othertitle;
19778:                             } else {
19779:                                 $typename = $usertypes{$type};
19780:                             } 
19781:                             $chgtext .= &mt('(Affiliation: [_1])',$typename);
19782:                         }
19783:                         if (@{$email_rule{$type}} > 0) {
19784:                             $resulttext .= '<li>'.
19785:                                            &mt('Accounts may not be created by users verified by e-mail, for e-mail addresses of the following types: ',
19786:                                                $usertypes{$type}).
19787:                                            $chgtext.
19788:                                            '</li>';
19789:                         } else {
19790:                             $resulttext .= '<li>'.
19791:                                            &mt('There are now no restrictions on e-mail addresses which may be used for verification when a user requests an account.').
19792:                                            '</li>'.
19793:                                            &mt('(Affiliation: [_1])',$typename);
19794:                         }
19795:                     }
19796:                 }
19797:             }
19798:             if (ref($changes{'inststatus'}) eq 'ARRAY') {
19799:                 if (ref($save_inststatus{'inststatusguest'}) eq 'ARRAY') {
19800:                     if (@{$save_inststatus{'inststatusguest'}} > 0) {
19801:                         my $chgtext = '<ul>';
19802:                         foreach my $type (@{$save_inststatus{'inststatusguest'}}) {
19803:                             $chgtext .= '<li>'.$usertypes{$type}.'</li>';
19804:                         }
19805:                         $chgtext .= '</ul>';
19806:                         $resulttext .= '<li>'.
19807:                                        &mt('A user will self-report one of the following affiliations when requesting an account verified by e-mail: ').
19808:                                           $chgtext.
19809:                                        '</li>';
19810:                     } else {
19811:                         $resulttext .= '<li>'.
19812:                                        &mt('No affiliations available for self-reporting when requesting an account verified by e-mail.').
19813:                                        '</li>';
19814:                     }
19815:                 }
19816:             }
19817:             if (ref($changes{'selfcreate'}) eq 'ARRAY') {
19818:                 $resulttext .= '<li>'.&mt('When self-creating institutional account:').'<ul>';
19819:                 my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
19820:                 foreach my $type (@{$changes{'selfcreate'}}) {
19821:                     my $typename = $type;
19822:                     if (keys(%usertypes) > 0) {
19823:                         if ($usertypes{$type} ne '') {
19824:                             $typename = $usertypes{$type};
19825:                         }
19826:                     }
19827:                     my @modifiable;
19828:                     $resulttext .= '<li>'.
19829:                                     &mt('Self-creation of account by users with status: [_1]',
19830:                                         '<span class="LC_cusr_emph">'.$typename.'</span>').
19831:                                     ' - '.&mt('modifiable fields (if institutional data blank): ');
19832:                     foreach my $field (@fields) {
19833:                         if ($save_usermodify{'selfcreate'}{$type}{$field}) {
19834:                             push(@modifiable,'<b>'.$fieldtitles{$field}.'</b>');
19835:                         }
19836:                     }
19837:                     if (@modifiable > 0) {
19838:                         $resulttext .= join(', ',@modifiable);
19839:                     } else {
19840:                         $resulttext .= &mt('none');
19841:                     }
19842:                     $resulttext .= '</li>';
19843:                 }
19844:                 $resulttext .= '</ul></li>';
19845:             }
19846:             $resulttext .= '</ul>';
19847:             my $cachetime = 24*60*60;
19848:             $domdefaults{'inststatusguest'} = $save_inststatus{'inststatusguest'};
19849:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
19850:             if (ref($lastactref) eq 'HASH') {
19851:                 $lastactref->{'domdefaults'} = 1;
19852:             }
19853:         } else {
19854:             $resulttext = &mt('No changes made to self-creation settings');
19855:         }
19856:     } else {
19857:         $resulttext = '<span class="LC_error">'.
19858:             &mt('An error occurred: [_1]',$putresult).'</span>';
19859:     }
19860:     if ($warningmsg ne '') {
19861:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
19862:     }
19863:     return $resulttext;
19864: }
19865: 
19866: sub process_captcha {
19867:     my ($container,$changes,$newsettings,$currsettings) = @_;
19868:     return unless ((ref($changes) eq 'HASH') && (ref($newsettings) eq 'HASH'));
19869:     $newsettings->{'captcha'} = $env{'form.'.$container.'_captcha'};
19870:     unless ($newsettings->{'captcha'} eq 'recaptcha' || $newsettings->{'captcha'} eq 'notused') {
19871:         $newsettings->{'captcha'} = 'original';
19872:     }
19873:     my %current;
19874:     if (ref($currsettings) eq 'HASH') {
19875:         %current = %{$currsettings};
19876:     }
19877:     if ($current{'captcha'} ne $newsettings->{'captcha'}) {
19878:         if ($container eq 'cancreate') {
19879:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
19880:                 push(@{$changes->{'cancreate'}},'captcha');
19881:             } elsif (!defined($changes->{'cancreate'})) {
19882:                 $changes->{'cancreate'} = ['captcha'];
19883:             }
19884:         } elsif ($container eq 'passwords') {
19885:             $changes->{'reset'} = 1;
19886:         } else {
19887:             $changes->{'captcha'} = 1;
19888:         }
19889:     }
19890:     my ($newpub,$newpriv,$currpub,$currpriv,$newversion,$currversion);
19891:     if ($newsettings->{'captcha'} eq 'recaptcha') {
19892:         $newpub = $env{'form.'.$container.'_recaptchapub'};
19893:         $newpriv = $env{'form.'.$container.'_recaptchapriv'};
19894:         $newpub =~ s/[^\w\-]//g;
19895:         $newpriv =~ s/[^\w\-]//g;
19896:         $newsettings->{'recaptchakeys'} = {
19897:                                              public  => $newpub,
19898:                                              private => $newpriv,
19899:                                           };
19900:         $newversion = $env{'form.'.$container.'_recaptchaversion'};
19901:         $newversion =~ s/\D//g;
19902:         if ($newversion ne '2') {
19903:             $newversion = 1;
19904:         }
19905:         $newsettings->{'recaptchaversion'} = $newversion;
19906:     }
19907:     if (ref($current{'recaptchakeys'}) eq 'HASH') {
19908:         $currpub = $current{'recaptchakeys'}{'public'};
19909:         $currpriv = $current{'recaptchakeys'}{'private'};
19910:         unless ($newsettings->{'captcha'} eq 'recaptcha') {
19911:             $newsettings->{'recaptchakeys'} = {
19912:                                                  public  => '',
19913:                                                  private => '',
19914:                                               }
19915:         }
19916:     }
19917:     if ($current{'captcha'} eq 'recaptcha') {
19918:         $currversion = $current{'recaptchaversion'};
19919:         if ($currversion ne '2') {
19920:             $currversion = 1;
19921:         }
19922:     }
19923:     if ($currversion ne $newversion) {
19924:         if ($container eq 'cancreate') {
19925:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
19926:                 push(@{$changes->{'cancreate'}},'recaptchaversion');
19927:             } elsif (!defined($changes->{'cancreate'})) {
19928:                 $changes->{'cancreate'} = ['recaptchaversion'];
19929:             }
19930:         } elsif ($container eq 'passwords') {
19931:             $changes->{'reset'} = 1;
19932:         } else {
19933:             $changes->{'recaptchaversion'} = 1;
19934:         }
19935:     }
19936:     if (($newpub ne $currpub) || ($newpriv ne $currpriv)) {
19937:         if ($container eq 'cancreate') {
19938:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
19939:                 push(@{$changes->{'cancreate'}},'recaptchakeys');
19940:             } elsif (!defined($changes->{'cancreate'})) {
19941:                 $changes->{'cancreate'} = ['recaptchakeys'];
19942:             }
19943:         } elsif ($container eq 'passwords') {
19944:             $changes->{'reset'} = 1;
19945:         } else {
19946:             $changes->{'recaptchakeys'} = 1;
19947:         }
19948:     }
19949:     return;
19950: }
19951: 
19952: sub modify_usermodification {
19953:     my ($dom,%domconfig) = @_;
19954:     my ($resulttext,%curr_usermodification,%changes,%modifyhash);
19955:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
19956:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
19957:             if ($key eq 'selfcreate') {
19958:                 $modifyhash{$key} = $domconfig{'usermodification'}{$key};
19959:             } else {  
19960:                 $curr_usermodification{$key} = $domconfig{'usermodification'}{$key};
19961:             }
19962:         }
19963:     }
19964:     my @contexts = ('author','course');
19965:     my %context_title = (
19966:                            author => 'In author context',
19967:                            course => 'In course context',
19968:                         );
19969:     my @fields = ('lastname','firstname','middlename','generation',
19970:                   'permanentemail','id');
19971:     my %roles = (
19972:                   author => ['ca','aa'],
19973:                   course => ['st','ep','ta','in','cr'],
19974:                 );
19975:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
19976:     foreach my $context (@contexts) {
19977:         foreach my $role (@{$roles{$context}}) {
19978:             my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$role);
19979:             foreach my $item (@fields) {
19980:                 if (grep(/^\Q$item\E$/,@modifiable)) {
19981:                     $modifyhash{$context}{$role}{$item} = 1;
19982:                 } else {
19983:                     $modifyhash{$context}{$role}{$item} = 0;
19984:                 }
19985:             }
19986:         }
19987:         if (ref($curr_usermodification{$context}) eq 'HASH') {
19988:             foreach my $role (@{$roles{$context}}) {
19989:                 if (ref($curr_usermodification{$context}{$role}) eq 'HASH') {
19990:                     foreach my $field (@fields) {
19991:                         if ($modifyhash{$context}{$role}{$field} ne 
19992:                                 $curr_usermodification{$context}{$role}{$field}) {
19993:                             push(@{$changes{$context}},$role);
19994:                             last;
19995:                         }
19996:                     }
19997:                 }
19998:             }
19999:         } else {
20000:             foreach my $context (@contexts) {
20001:                 foreach my $role (@{$roles{$context}}) {
20002:                     push(@{$changes{$context}},$role);
20003:                 }
20004:             }
20005:         }
20006:     }
20007:     my %usermodification_hash =  (
20008:                                    usermodification => \%modifyhash,
20009:                                  );
20010:     my $putresult = &Apache::lonnet::put_dom('configuration',
20011:                                              \%usermodification_hash,$dom);
20012:     if ($putresult eq 'ok') {
20013:         if (keys(%changes) > 0) {
20014:             $resulttext = &mt('Changes made: ').'<ul>';
20015:             foreach my $context (@contexts) {
20016:                 if (ref($changes{$context}) eq 'ARRAY') {
20017:                     $resulttext .= '<li>'.$context_title{$context}.':<ul>';
20018:                     if (ref($changes{$context}) eq 'ARRAY') {
20019:                         foreach my $role (@{$changes{$context}}) {
20020:                             my $rolename;
20021:                             if ($role eq 'cr') {
20022:                                 $rolename = &mt('Custom');
20023:                             } else {
20024:                                 $rolename = &Apache::lonnet::plaintext($role);
20025:                             }
20026:                             my @modifiable;
20027:                             $resulttext .= '<li><span class="LC_cusr_emph">'.&mt('Target user with [_1] role',$rolename).'</span> - '.&mt('modifiable fields: ');
20028:                             foreach my $field (@fields) {
20029:                                 if ($modifyhash{$context}{$role}{$field}) {
20030:                                     push(@modifiable,$fieldtitles{$field});
20031:                                 }
20032:                             }
20033:                             if (@modifiable > 0) {
20034:                                 $resulttext .= join(', ',@modifiable);
20035:                             } else {
20036:                                 $resulttext .= &mt('none'); 
20037:                             }
20038:                             $resulttext .= '</li>';
20039:                         }
20040:                         $resulttext .= '</ul></li>';
20041:                     }
20042:                 }
20043:             }
20044:             $resulttext .= '</ul>';
20045:         } else {
20046:             $resulttext = &mt('No changes made to user modification settings');
20047:         }
20048:     } else {
20049:         $resulttext = '<span class="LC_error">'.
20050:             &mt('An error occurred: [_1]',$putresult).'</span>';
20051:     }
20052:     return $resulttext;
20053: }
20054: 
20055: sub modify_defaults {
20056:     my ($dom,$lastactref,%domconfig) = @_;
20057:     my ($resulttext,$mailmsgtxt,%newvalues,%changes,@errors);
20058:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
20059:     my @items = ('auth_def','auth_arg_def','lang_def','timezone_def','datelocale_def',
20060:                  'portal_def');
20061:     my @authtypes = ('internal','krb4','krb5','localauth','lti');
20062:     foreach my $item (@items) {
20063:         $newvalues{$item} = $env{'form.'.$item};
20064:         if ($item eq 'auth_def') {
20065:             if ($newvalues{$item} ne '') {
20066:                 if (!grep(/^\Q$newvalues{$item}\E$/,@authtypes)) {
20067:                     push(@errors,$item);
20068:                 }
20069:             }
20070:         } elsif ($item eq 'lang_def') {
20071:             if ($newvalues{$item} ne '') {
20072:                 if ($newvalues{$item} =~ /^(\w+)/) {
20073:                     my $langcode = $1;
20074:                     if ($langcode ne 'x_chef') {
20075:                         if (code2language($langcode) eq '') {
20076:                             push(@errors,$item);
20077:                         }
20078:                     }
20079:                 } else {
20080:                     push(@errors,$item);
20081:                 }
20082:             }
20083:         } elsif ($item eq 'timezone_def') {
20084:             if ($newvalues{$item} ne '') {
20085:                 if (!DateTime::TimeZone->is_valid_name($newvalues{$item})) {
20086:                     push(@errors,$item);   
20087:                 }
20088:             }
20089:         } elsif ($item eq 'datelocale_def') {
20090:             if ($newvalues{$item} ne '') {
20091:                 my @datelocale_ids = DateTime::Locale->ids();
20092:                 if (!grep(/^\Q$newvalues{$item}\E$/,@datelocale_ids)) {
20093:                     push(@errors,$item);
20094:                 }
20095:             }
20096:         } elsif ($item eq 'portal_def') {
20097:             if ($newvalues{$item} ne '') {
20098:                 if ($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])\/?$/) {
20099:                     foreach my $field ('email','web') {
20100:                         if ($env{'form.'.$item.'_'.$field}) {
20101:                             $newvalues{$item.'_'.$field} = $env{'form.'.$item.'_'.$field};
20102:                         }
20103:                     }
20104:                 } else {
20105:                     push(@errors,$item);
20106:                 }
20107:             }
20108:         }
20109:         if (grep(/^\Q$item\E$/,@errors)) {
20110:             $newvalues{$item} = $domdefaults{$item};
20111:             if ($item eq 'portal_def') {
20112:                 if ($domdefaults{$item}) {
20113:                     foreach my $field ('email','web') {
20114:                         if (exists($domdefaults{$item.'_'.$field})) {
20115:                             $newvalues{$item.'_'.$field} = $domdefaults{$item.'_'.$field};
20116:                         }
20117:                     }
20118:                 }
20119:             }
20120:         } elsif ($domdefaults{$item} ne $newvalues{$item}) {
20121:             $changes{$item} = 1;
20122:         }
20123:         if ($item eq 'portal_def') {
20124:             unless (grep(/^\Q$item\E$/,@errors)) {
20125:                 if ($newvalues{$item} eq '') { 
20126:                     foreach my $field ('email','web') {
20127:                         if (exists($domdefaults{$item.'_'.$field})) {
20128:                             delete($domdefaults{$item.'_'.$field});
20129:                         }
20130:                     }
20131:                 } else {
20132:                     unless ($changes{$item}) {
20133:                         foreach my $field ('email','web') {
20134:                             if ($domdefaults{$item.'_'.$field} ne $newvalues{$item.'_'.$field}) {
20135:                                 $changes{$item} = 1;
20136:                                 last;
20137:                             }
20138:                         }
20139:                     }
20140:                     foreach my $field ('email','web') {
20141:                         if ($newvalues{$item.'_'.$field}) {
20142:                             $domdefaults{$item.'_'.$field} = $newvalues{$item.'_'.$field};
20143:                         } elsif (exists($domdefaults{$item.'_'.$field})) {
20144:                             delete($domdefaults{$item.'_'.$field});
20145:                         }
20146:                     }
20147:                 }
20148:             }
20149:         }
20150:         $domdefaults{$item} = $newvalues{$item};
20151:     }
20152:     my %staticdefaults = (
20153:                            'intauth_cost'   => 10,
20154:                            'intauth_check'  => 0,
20155:                            'intauth_switch' => 0,
20156:                          );
20157:     foreach my $item ('intauth_cost','intauth_check','intauth_switch') {
20158:         if (exists($domdefaults{$item})) {
20159:             $newvalues{$item} = $domdefaults{$item};
20160:         } else {
20161:             $newvalues{$item} = $staticdefaults{$item};
20162:         }
20163:     }
20164:     my ($unamemaprules,$ruleorder);
20165:     my @possunamemaprules = &Apache::loncommon::get_env_multiple('form.unamemap_rule');
20166:     if (@possunamemaprules) {
20167:         ($unamemaprules,$ruleorder) =
20168:             &Apache::lonnet::inst_userrules($dom,'unamemap');
20169:         if ((ref($unamemaprules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
20170:             if (@{$ruleorder} > 0) {
20171:                 my %possrules;
20172:                 map { $possrules{$_} = 1; } @possunamemaprules;
20173:                 foreach my $rule (@{$ruleorder}) {
20174:                     if ($possrules{$rule}) {
20175:                         push(@{$newvalues{'unamemap_rule'}},$rule);
20176:                     }
20177:                 }
20178:             }
20179:         }
20180:     }
20181:     if (ref($domdefaults{'unamemap_rule'}) eq 'ARRAY') {
20182:         if (ref($newvalues{'unamemap_rule'}) eq 'ARRAY') {
20183:             my @rulediffs = &Apache::loncommon::compare_arrays($domdefaults{'unamemap_rule'},
20184:                                                                $newvalues{'unamemap_rule'});
20185:             if (@rulediffs) {
20186:                 $changes{'unamemap_rule'} = 1;
20187:                 $domdefaults{'unamemap_rule'} = $newvalues{'unamemap_rule'};
20188:             }
20189:         } elsif (@{$domdefaults{'unamemap_rule'}} > 0) {
20190:             $changes{'unamemap_rule'} = 1;
20191:             delete($domdefaults{'unamemap_rule'});
20192:         }
20193:     } elsif (ref($newvalues{'unamemap_rule'}) eq 'ARRAY') {
20194:         if (@{$newvalues{'unamemap_rule'}} > 0) {
20195:             $changes{'unamemap_rule'} = 1;
20196:             $domdefaults{'unamemap_rule'} = $newvalues{'unamemap_rule'};
20197:         }
20198:     }
20199:     my %defaults_hash = (
20200:                          defaults => \%newvalues,
20201:                         );
20202:     my $title = &defaults_titles();
20203: 
20204:     my $currinststatus;
20205:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
20206:         $currinststatus = $domconfig{'inststatus'};
20207:     } else {
20208:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
20209:         $currinststatus = {
20210:                              inststatustypes => $usertypes,
20211:                              inststatusorder => $types,
20212:                              inststatusguest => [],
20213:                           };
20214:     }
20215:     my @todelete = &Apache::loncommon::get_env_multiple('form.inststatus_delete');
20216:     my @allpos;
20217:     my %alltypes;
20218:     my @inststatusguest;
20219:     if (ref($currinststatus->{'inststatusguest'}) eq 'ARRAY') {
20220:         foreach my $type (@{$currinststatus->{'inststatusguest'}}) {
20221:             unless (grep(/^\Q$type\E$/,@todelete)) {
20222:                 push(@inststatusguest,$type);
20223:             }
20224:         }
20225:     }
20226:     my ($currtitles,$currorder);
20227:     if (ref($currinststatus) eq 'HASH') {
20228:         if (ref($currinststatus->{'inststatusorder'}) eq 'ARRAY') {
20229:             foreach my $type (@{$currinststatus->{'inststatusorder'}}) {
20230:                 if (ref($currinststatus->{inststatustypes}) eq 'HASH') {
20231:                     if ($currinststatus->{inststatustypes}->{$type} ne '') {
20232:                         $currtitles .= $currinststatus->{inststatustypes}->{$type}.',';
20233:                     }
20234:                 }
20235:                 unless (grep(/^\Q$type\E$/,@todelete)) { 
20236:                     my $position = $env{'form.inststatus_pos_'.$type};
20237:                     $position =~ s/\D+//g;
20238:                     $allpos[$position] = $type;
20239:                     $alltypes{$type} = $env{'form.inststatus_title_'.$type};
20240:                     $alltypes{$type} =~ s/`//g;
20241:                 }
20242:             }
20243:             $currorder = join(',',@{$currinststatus->{'inststatusorder'}});
20244:             $currtitles =~ s/,$//;
20245:         }
20246:     }
20247:     if ($env{'form.addinststatus'}) {
20248:         my $newtype = $env{'form.addinststatus'};
20249:         $newtype =~ s/\W//g;
20250:         unless (exists($alltypes{$newtype})) {
20251:             $alltypes{$newtype} = $env{'form.addinststatus_title'};
20252:             $alltypes{$newtype} =~ s/`//g; 
20253:             my $position = $env{'form.addinststatus_pos'};
20254:             $position =~ s/\D+//g;
20255:             if ($position ne '') {
20256:                 $allpos[$position] = $newtype;
20257:             }
20258:         }
20259:     }
20260:     my @orderedstatus;
20261:     foreach my $type (@allpos) {
20262:         unless (($type eq '') || (grep(/^\Q$type\E$/,@orderedstatus))) {
20263:             push(@orderedstatus,$type);
20264:         }
20265:     }
20266:     foreach my $type (keys(%alltypes)) {
20267:         unless (grep(/^\Q$type\E$/,@orderedstatus)) {
20268:             delete($alltypes{$type});
20269:         }
20270:     }
20271:     $defaults_hash{'inststatus'} = {
20272:                                      inststatustypes => \%alltypes,
20273:                                      inststatusorder => \@orderedstatus,
20274:                                      inststatusguest => \@inststatusguest,
20275:                                    };
20276:     if (ref($defaults_hash{'inststatus'}) eq 'HASH') {
20277:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
20278:             $domdefaults{$item} = $defaults_hash{'inststatus'}{$item};
20279:         }
20280:     }
20281:     if ($currorder ne join(',',@orderedstatus)) {
20282:         $changes{'inststatus'}{'inststatusorder'} = 1;
20283:     }
20284:     my $newtitles;
20285:     foreach my $item (@orderedstatus) {
20286:         $newtitles .= $alltypes{$item}.',';
20287:     }
20288:     $newtitles =~ s/,$//;
20289:     if ($currtitles ne $newtitles) {
20290:         $changes{'inststatus'}{'inststatustypes'} = 1;
20291:     }
20292:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaults_hash,
20293:                                              $dom);
20294:     if ($putresult eq 'ok') {
20295:         if (keys(%changes) > 0) {
20296:             $resulttext = &mt('Changes made:').'<ul>';
20297:             my $version = &Apache::lonnet::get_server_loncaparev($dom);
20298:             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";
20299:             foreach my $item (sort(keys(%changes))) {
20300:                 if ($item eq 'inststatus') {
20301:                     if (ref($changes{'inststatus'}) eq 'HASH') {
20302:                         if (@orderedstatus) {
20303:                             $resulttext .= '<li>'.&mt('Institutional user status types set to:').' ';
20304:                             foreach my $type (@orderedstatus) { 
20305:                                 $resulttext .= $alltypes{$type}.', ';
20306:                             }
20307:                             $resulttext =~ s/, $//;
20308:                             $resulttext .= '</li>';
20309:                         } else {
20310:                             $resulttext .= '<li>'.&mt('Institutional user status types deleted').'</li>'; 
20311:                         }
20312:                     }
20313:                 } elsif ($item eq 'unamemap_rule') {
20314:                     if (ref($newvalues{'unamemap_rule'}) eq 'ARRAY') {
20315:                         my @rulenames;
20316:                         if (ref($unamemaprules) eq 'HASH') {
20317:                             foreach my $rule (@{$newvalues{'unamemap_rule'}}) {
20318:                                 if (ref($unamemaprules->{$rule}) eq 'HASH') {
20319:                                     push(@rulenames,$unamemaprules->{$rule}->{'name'});
20320:                                 }
20321:                             }
20322:                         }
20323:                         if (@rulenames) {
20324:                             $resulttext .= '<li>'.&mt('Mapping for missing usernames includes: [_1]',
20325:                                                      '<ul><li>'.join('</li><li>',@rulenames).'</li></ul>').
20326:                                            '</li>';
20327:                         } else {
20328:                             $resulttext .= '<li>'.&mt('No mapping for missing usernames via standard log-in').'</li>';
20329:                         }
20330:                     } else {
20331:                         $resulttext .= '<li>'.&mt('Mapping for missing usernames via standard log-in deleted').'</li>';
20332:                     }
20333:                 } else {
20334:                     my $value = $env{'form.'.$item};
20335:                     if ($value eq '') {
20336:                         $value = &mt('none');
20337:                     } elsif ($item eq 'auth_def') {
20338:                         my %authnames = &authtype_names();
20339:                         my %shortauth = (
20340:                                           internal   => 'int',
20341:                                           krb4       => 'krb4',
20342:                                           krb5       => 'krb5',
20343:                                           localauth  => 'loc',
20344:                                           lti        => 'lti',
20345:                         );
20346:                         $value = $authnames{$shortauth{$value}};
20347:                     }
20348:                     $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$title->{$item},$value).'</li>';
20349:                     $mailmsgtext .= "$title->{$item} set to $value\n";
20350:                     if ($item eq 'portal_def') {
20351:                         if ($env{'form.'.$item} ne '') {
20352:                             foreach my $field ('email','web') {
20353:                                 $value = $env{'form.'.$item.'_'.$field};
20354:                                 if ($value) {
20355:                                     $value = &mt('Yes');
20356:                                 } else {
20357:                                     $value = &mt('No');
20358:                                 }
20359:                                 $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$title->{$field},$value).'</li>';
20360:                             }
20361:                         }
20362:                     }
20363:                 }
20364:             }
20365:             $resulttext .= '</ul>';
20366:             $mailmsgtext .= "\n";
20367:             my $cachetime = 24*60*60;
20368:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
20369:             if (ref($lastactref) eq 'HASH') {
20370:                 $lastactref->{'domdefaults'} = 1;
20371:             }
20372:             if ($changes{'auth_def'} || $changes{'auth_arg_def'} || $changes{'lang_def'} || $changes{'datelocale_def'}) {
20373:                 my $notify = 1;
20374:                 if (ref($domconfig{'contacts'}) eq 'HASH') {
20375:                     if ($domconfig{'contacts'}{'reportupdates'} == 0) {
20376:                         $notify = 0;
20377:                     }
20378:                 }
20379:                 if ($notify) {
20380:                     &Apache::lonmsg::sendemail('installrecord@loncapa.org',
20381:                                                "LON-CAPA Domain Settings Change - $dom",
20382:                                                $mailmsgtext);
20383:                 }
20384:             }
20385:         } else {
20386:             $resulttext = &mt('No changes made to default authentication/language/timezone settings');
20387:         }
20388:     } else {
20389:         $resulttext = '<span class="LC_error">'.
20390:             &mt('An error occurred: [_1]',$putresult).'</span>';
20391:     }
20392:     if (@errors > 0) {
20393:         $resulttext .= '<br />'.&mt('The following were left unchanged because the values entered were invalid:');
20394:         foreach my $item (@errors) {
20395:             $resulttext .= ' "'.$title->{$item}.'",';
20396:         }
20397:         $resulttext =~ s/,$//;
20398:     }
20399:     return $resulttext;
20400: }
20401: 
20402: sub modify_scantron {
20403:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
20404:     my ($resulttext,%confhash,%changes,$errors);
20405:     my $custom = 'custom.tab';
20406:     my $default = 'default.tab';
20407:     my $servadm = $r->dir_config('lonAdmEMail');
20408:     my ($configuserok,$author_ok,$switchserver) =
20409:         &config_check($dom,$confname,$servadm);
20410:     if ($env{'form.scantronformat.filename'} ne '') {
20411:         my $error;
20412:         if ($configuserok eq 'ok') {
20413:             if ($switchserver) {
20414:                 $error = &mt("Upload of bubblesheet format file is not permitted to this server: [_1]",$switchserver);
20415:             } else {
20416:                 if ($author_ok eq 'ok') {
20417:                     my ($result,$scantronurl) =
20418:                         &publishlogo($r,'upload','scantronformat',$dom,
20419:                                      $confname,'scantron','','',$custom);
20420:                     if ($result eq 'ok') {
20421:                         $confhash{'scantron'}{'scantronformat'} = $scantronurl;
20422:                         $changes{'scantronformat'} = 1;
20423:                     } else {
20424:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$custom,$result);
20425:                     }
20426:                 } else {
20427:                     $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);
20428:                 }
20429:             }
20430:         } else {
20431:             $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);
20432:         }
20433:         if ($error) {
20434:             &Apache::lonnet::logthis($error);
20435:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
20436:         }
20437:     }
20438:     if (ref($domconfig{'scantron'}) eq 'HASH') {
20439:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
20440:             if ($env{'form.scantronformat_del'}) {
20441:                 $confhash{'scantron'}{'scantronformat'} = '';
20442:                 $changes{'scantronformat'} = 1;
20443:             } else {
20444:                 $confhash{'scantron'}{'scantronformat'} = $domconfig{'scantron'}{'scantronformat'};
20445:             }
20446:         }
20447:     }
20448:     my @options = ('hdr','pad','rem');
20449:     my @fields = &scantroncsv_fields();
20450:     my %titles = &scantronconfig_titles();
20451:     my @formats = &Apache::loncommon::get_env_multiple('form.scantronconfig');
20452:     my ($newdat,$currdat,%newcol,%currcol);
20453:     if (grep(/^dat$/,@formats)) {
20454:         $confhash{'scantron'}{config}{dat} = 1;
20455:         $newdat = 1;
20456:     } else {
20457:         $newdat = 0;
20458:     }
20459:     if (grep(/^csv$/,@formats)) {
20460:         my %bynum;
20461:         foreach my $field (@fields) {
20462:             if ($env{'form.scantronconfig_csv_'.$field} =~ /^(\d+)$/) {
20463:                 my $posscol = $1;
20464:                 if (($posscol < 20) && (!$bynum{$posscol})) {
20465:                     $confhash{'scantron'}{config}{csv}{fields}{$field} = $posscol;
20466:                     $bynum{$posscol} = $field;
20467:                     $newcol{$field} = $posscol;
20468:                 }
20469:             }
20470:         }
20471:         if (keys(%newcol)) {
20472:             foreach my $option (@options) {
20473:                 if ($env{'form.scantroncsv_'.$option}) {
20474:                     $confhash{'scantron'}{config}{csv}{options}{$option} = 1;
20475:                 }
20476:             }
20477:         }
20478:     }
20479:     $currdat = 1;
20480:     if (ref($domconfig{'scantron'}) eq 'HASH') {
20481:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
20482:             unless (exists($domconfig{'scantron'}{'config'}{'dat'})) {
20483:                 $currdat = 0;
20484:             }
20485:             if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
20486:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
20487:                     %currcol = %{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}};
20488:                 }
20489:             }
20490:         }
20491:     }
20492:     if ($currdat != $newdat) {
20493:         $changes{'config'} = 1;
20494:     } else {
20495:         foreach my $field (@fields) {
20496:             if ($currcol{$field} ne '') {
20497:                 if ($currcol{$field} ne $newcol{$field}) {
20498:                     $changes{'config'} = 1;
20499:                     last;
20500:                 }
20501:             } elsif ($newcol{$field} ne '') {
20502:                 $changes{'config'} = 1;
20503:                 last;
20504:             }
20505:         }
20506:     }
20507:     if (keys(%confhash) > 0) {
20508:         my $putresult = &Apache::lonnet::put_dom('configuration',\%confhash,
20509:                                                  $dom);
20510:         if ($putresult eq 'ok') {
20511:             if (keys(%changes) > 0) {
20512:                 if (ref($confhash{'scantron'}) eq 'HASH') {
20513:                     $resulttext = &mt('Changes made:').'<ul>';
20514:                     if ($changes{'scantronformat'}) {
20515:                         if ($confhash{'scantron'}{'scantronformat'} eq '') {
20516:                             $resulttext .= '<li>'.&mt('[_1] bubblesheet format file removed; [_2] file will be used for courses in this domain.',$custom,$default).'</li>';
20517:                         } else {
20518:                             $resulttext .= '<li>'.&mt('Custom bubblesheet format file ([_1]) uploaded for use with courses in this domain.',$custom).'</li>';
20519:                         }
20520:                     }
20521:                     if ($changes{'config'}) {
20522:                         if (ref($confhash{'scantron'}{'config'}) eq 'HASH') {
20523:                             if ($confhash{'scantron'}{'config'}{'dat'}) {
20524:                                 $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .dat format').'</li>';
20525:                             }
20526:                             if (ref($confhash{'scantron'}{'config'}{'csv'}) eq 'HASH') {
20527:                                 if (ref($confhash{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
20528:                                     if (keys(%{$confhash{'scantron'}{'config'}{'csv'}{'fields'}})) {
20529:                                         $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .csv format, with following fields/column numbers supported:').'<ul>';
20530:                                         foreach my $field (@fields) {
20531:                                             if ($confhash{'scantron'}{'config'}{'csv'}{'fields'}{$field} ne '') {
20532:                                                 my $showcol = $confhash{'scantron'}{'config'}{'csv'}{'fields'}{$field} + 1;
20533:                                                 $resulttext .= '<li>'.$titles{$field}.': '.$showcol.'</li>';
20534:                                             }
20535:                                         }
20536:                                         $resulttext .= '</ul></li>';
20537:                                         if (ref($confhash{'scantron'}{'config'}{'csv'}{'options'}) eq 'HASH') {
20538:                                             if (keys(%{$confhash{'scantron'}{'config'}{'csv'}{'options'}})) {
20539:                                                 $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .csv format, with following options:').'<ul>';
20540:                                                 foreach my $option (@options) {
20541:                                                     if ($confhash{'scantron'}{'config'}{'csv'}{'options'}{$option} ne '') {
20542:                                                         $resulttext .= '<li>'.$titles{$option}.'</li>';
20543:                                                     }
20544:                                                 }
20545:                                                 $resulttext .= '</ul></li>';
20546:                                             }
20547:                                         }
20548:                                     }
20549:                                 }
20550:                             }
20551:                         } else {
20552:                             $resulttext .= '<li>'.&mt('No bubblesheet data upload formats set -- will default to assuming .dat format').'</li>';
20553:                         }
20554:                     }
20555:                     $resulttext .= '</ul>';
20556:                 } else {
20557:                     $resulttext = &mt('Changes made to bubblesheet format file.');
20558:                 }
20559:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
20560:                 if (ref($lastactref) eq 'HASH') {
20561:                     $lastactref->{'domainconfig'} = 1;
20562:                 }
20563:             } else {
20564:                 $resulttext = &mt('No changes made to bubblesheet format settings');
20565:             }
20566:         } else {
20567:             $resulttext = '<span class="LC_error">'.
20568:                 &mt('An error occurred: [_1]',$putresult).'</span>';
20569:         }
20570:     } else {
20571:         $resulttext = &mt('No changes made to bubblesheet format file'); 
20572:     }
20573:     if ($errors) {
20574:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
20575:                        $errors.'</ul></p>';
20576:     }
20577:     return $resulttext;
20578: }
20579: 
20580: sub modify_coursecategories {
20581:     my ($dom,$lastactref,%domconfig) = @_;
20582:     my ($resulttext,%deletions,%reorderings,%needreordering,%adds,%changes,$errors,
20583:         $cathash);
20584:     my @deletecategory = &Apache::loncommon::get_env_multiple('form.deletecategory');
20585:     my @catitems = ('unauth','auth');
20586:     my @cattypes = ('std','domonly','codesrch','none');
20587:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
20588:         $cathash = $domconfig{'coursecategories'}{'cats'};
20589:         if ($domconfig{'coursecategories'}{'togglecats'} ne $env{'form.togglecats'}) {
20590:             $changes{'togglecats'} = 1;
20591:             $domconfig{'coursecategories'}{'togglecats'} = $env{'form.togglecats'};
20592:         }
20593:         if ($domconfig{'coursecategories'}{'categorize'} ne $env{'form.categorize'}) {
20594:             $changes{'categorize'} = 1;
20595:             $domconfig{'coursecategories'}{'categorize'} = $env{'form.categorize'};
20596:         }
20597:         if ($domconfig{'coursecategories'}{'togglecatscomm'} ne $env{'form.togglecatscomm'}) {
20598:             $changes{'togglecatscomm'} = 1;
20599:             $domconfig{'coursecategories'}{'togglecatscomm'} = $env{'form.togglecatscomm'};
20600:         }
20601:         if ($domconfig{'coursecategories'}{'categorizecomm'} ne $env{'form.categorizecomm'}) {
20602:             $changes{'categorizecomm'} = 1;
20603:             $domconfig{'coursecategories'}{'categorizecomm'} = $env{'form.categorizecomm'};
20604: 
20605:         }
20606:         if ($domconfig{'coursecategories'}{'togglecatsplace'} ne $env{'form.togglecatsplace'}) {
20607:             $changes{'togglecatsplace'} = 1;
20608:             $domconfig{'coursecategories'}{'togglecatsplace'} = $env{'form.togglecatsplace'};
20609:         }
20610:         if ($domconfig{'coursecategories'}{'categorizeplace'} ne $env{'form.categorizeplace'}) {
20611:             $changes{'categorizeplace'} = 1;
20612:             $domconfig{'coursecategories'}{'categorizeplace'} = $env{'form.categorizeplace'};
20613:         }
20614:         foreach my $item (@catitems) {
20615:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
20616:                 if ($domconfig{'coursecategories'}{$item} ne $env{'form.coursecat_'.$item}) {
20617:                     $changes{$item} = 1;
20618:                     $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
20619:                 }
20620:             }
20621:         }
20622:     } else {
20623:         $changes{'togglecats'} = 1;
20624:         $changes{'categorize'} = 1;
20625:         $changes{'togglecatscomm'} = 1;
20626:         $changes{'categorizecomm'} = 1;
20627:         $changes{'togglecatsplace'} = 1;
20628:         $changes{'categorizeplace'} = 1;
20629:         $domconfig{'coursecategories'} = {
20630:                                              togglecats => $env{'form.togglecats'},
20631:                                              categorize => $env{'form.categorize'},
20632:                                              togglecatscomm => $env{'form.togglecatscomm'},
20633:                                              categorizecomm => $env{'form.categorizecomm'},
20634:                                              togglecatsplace => $env{'form.togglecatsplace'},
20635:                                              categorizeplace => $env{'form.categorizeplace'},
20636:                                          };
20637:         foreach my $item (@catitems) {
20638:             if ($env{'form.coursecat_'.$item} ne 'std') {
20639:                 $changes{$item} = 1;
20640:             }
20641:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
20642:                 $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
20643:             }
20644:         }
20645:     }
20646:     if (ref($cathash) eq 'HASH') {
20647:         if (($domconfig{'coursecategories'}{'cats'}{'instcode::0'} ne '')  && ($env{'form.instcode'} == 0)) {
20648:             push (@deletecategory,'instcode::0');
20649:         }
20650:         if (($domconfig{'coursecategories'}{'cats'}{'communities::0'} ne '')  && ($env{'form.communities'} == 0)) {
20651:             push(@deletecategory,'communities::0');
20652:         }
20653:         if (($domconfig{'coursecategories'}{'cats'}{'placement::0'} ne '')  && ($env{'form.placement'} == 0)) {
20654:             push(@deletecategory,'placement::0');
20655:         }
20656:     }
20657:     my (@predelcats,@predeltrails,%predelallitems,%sort_by_deltrail);
20658:     if (ref($cathash) eq 'HASH') {
20659:         if (@deletecategory > 0) {
20660:             #FIXME Need to remove category from all courses using a deleted category 
20661:             &Apache::loncommon::extract_categories($cathash,\@predelcats,\@predeltrails,\%predelallitems);
20662:             foreach my $item (@deletecategory) {
20663:                 if ($domconfig{'coursecategories'}{'cats'}{$item} ne '') {
20664:                     delete($domconfig{'coursecategories'}{'cats'}{$item});
20665:                     $deletions{$item} = 1;
20666:                     &recurse_cat_deletes($item,$cathash,\%deletions);
20667:                 }
20668:             }
20669:         }
20670:         foreach my $item (keys(%{$cathash})) {
20671:             my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
20672:             if ($cathash->{$item} ne $env{'form.'.$item}) {
20673:                 $reorderings{$item} = 1;
20674:                 $domconfig{'coursecategories'}{'cats'}{$item} = $env{'form.'.$item};
20675:             }
20676:             if ($env{'form.addcategory_name_'.$item} ne '') {
20677:                 my $newcat = $env{'form.addcategory_name_'.$item};
20678:                 my $newdepth = $depth+1;
20679:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
20680:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos_'.$item};
20681:                 $adds{$newitem} = 1; 
20682:             }
20683:             if ($env{'form.subcat_'.$item} ne '') {
20684:                 my $newcat = $env{'form.subcat_'.$item};
20685:                 my $newdepth = $depth+1;
20686:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
20687:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = 0;
20688:                 $adds{$newitem} = 1;
20689:             }
20690:         }
20691:     }
20692:     if ($env{'form.instcode'} eq '1') {
20693:         if (ref($cathash) eq 'HASH') {
20694:             my $newitem = 'instcode::0';
20695:             if ($cathash->{$newitem} eq '') {  
20696:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
20697:                 $adds{$newitem} = 1;
20698:             }
20699:         } else {
20700:             my $newitem = 'instcode::0';
20701:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
20702:             $adds{$newitem} = 1;
20703:         }
20704:     }
20705:     if ($env{'form.communities'} eq '1') {
20706:         if (ref($cathash) eq 'HASH') {
20707:             my $newitem = 'communities::0';
20708:             if ($cathash->{$newitem} eq '') {
20709:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
20710:                 $adds{$newitem} = 1;
20711:             }
20712:         } else {
20713:             my $newitem = 'communities::0';
20714:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
20715:             $adds{$newitem} = 1;
20716:         }
20717:     }
20718:     if ($env{'form.placement'} eq '1') {
20719:         if (ref($cathash) eq 'HASH') {
20720:             my $newitem = 'placement::0';
20721:             if ($cathash->{$newitem} eq '') {
20722:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.placement_pos'};
20723:                 $adds{$newitem} = 1;
20724:             }
20725:         } else {
20726:             my $newitem = 'placement::0';
20727:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.placement_pos'};
20728:             $adds{$newitem} = 1;
20729:         }
20730:     }
20731:     if ($env{'form.addcategory_name'} ne '') {
20732:         if (($env{'form.addcategory_name'} ne 'instcode') &&
20733:             ($env{'form.addcategory_name'} ne 'communities') &&
20734:             ($env{'form.addcategory_name'} ne 'placement')) {
20735:             my $newitem = &escape($env{'form.addcategory_name'}).'::0';
20736:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos'};
20737:             $adds{$newitem} = 1;
20738:         }
20739:     }
20740:     my $putresult;
20741:     if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
20742:         if (keys(%deletions) > 0) {
20743:             foreach my $key (keys(%deletions)) {
20744:                 if ($predelallitems{$key} ne '') {
20745:                     $sort_by_deltrail{$predelallitems{$key}} = $predeltrails[$predelallitems{$key}];
20746:                 }
20747:             }
20748:         }
20749:         my (@chkcats,@chktrails,%chkallitems);
20750:         &Apache::loncommon::extract_categories($domconfig{'coursecategories'}{'cats'},\@chkcats,\@chktrails,\%chkallitems);
20751:         if (ref($chkcats[0]) eq 'ARRAY') {
20752:             my $depth = 0;
20753:             my $chg = 0;
20754:             for (my $i=0; $i<@{$chkcats[0]}; $i++) {
20755:                 my $name = $chkcats[0][$i];
20756:                 my $item;
20757:                 if ($name eq '') {
20758:                     $chg ++;
20759:                 } else {
20760:                     $item = &escape($name).'::0';
20761:                     if ($chg) {
20762:                         $domconfig{'coursecategories'}{'cats'}{$item} -= $chg;
20763:                     }
20764:                     $depth ++; 
20765:                     &recurse_check(\@chkcats,$domconfig{'coursecategories'}{'cats'},$depth,$name);
20766:                     $depth --;
20767:                 }
20768:             }
20769:         }
20770:     }
20771:     if ((keys(%changes) > 0) || (keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
20772:         $putresult = &Apache::lonnet::put_dom('configuration',\%domconfig,$dom);
20773:         if ($putresult eq 'ok') {
20774:             my %title = (
20775:                          togglecats     => 'Show/Hide a course in catalog',
20776:                          categorize     => 'Assign a category to a course',
20777:                          togglecatscomm => 'Show/Hide a community in catalog',
20778:                          categorizecomm => 'Assign a category to a community',
20779:                         );
20780:             my %level = (
20781:                          dom  => 'set in Domain ("Modify Course/Community")',
20782:                          crs  => 'set in Course ("Course Configuration")',
20783:                          comm => 'set in Community ("Community Configuration")',
20784:                          none     => 'No catalog',
20785:                          std      => 'Standard catalog',
20786:                          domonly  => 'Domain-only catalog',
20787:                          codesrch => 'Code search form',
20788:                         );
20789:             $resulttext = &mt('Changes made:').'<ul>';
20790:             if ($changes{'togglecats'}) {
20791:                 $resulttext .= '<li>'.&mt("$title{'togglecats'} $level{$env{'form.togglecats'}}").'</li>'; 
20792:             }
20793:             if ($changes{'categorize'}) {
20794:                 $resulttext .= '<li>'.&mt("$title{'categorize'} $level{$env{'form.categorize'}}").'</li>';
20795:             }
20796:             if ($changes{'togglecatscomm'}) {
20797:                 $resulttext .= '<li>'.&mt("$title{'togglecatscomm'} $level{$env{'form.togglecatscomm'}}").'</li>';
20798:             }
20799:             if ($changes{'categorizecomm'}) {
20800:                 $resulttext .= '<li>'.&mt("$title{'categorizecomm'} $level{$env{'form.categorizecomm'}}").'</li>';
20801:             }
20802:             if ($changes{'unauth'}) {
20803:                 $resulttext .= '<li>'.&mt('Catalog type for unauthenticated users set to "'.$level{$env{'form.coursecat_unauth'}}.'"').'</li>';
20804:             }
20805:             if ($changes{'auth'}) {
20806:                 $resulttext .= '<li>'.&mt('Catalog type for authenticated users set to "'.$level{$env{'form.coursecat_auth'}}.'"').'</li>';
20807:             }
20808:             if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
20809:                 my $cathash;
20810:                 if (ref($domconfig{'coursecategories'}) eq 'HASH') {
20811:                     $cathash = $domconfig{'coursecategories'}{'cats'};
20812:                 } else {
20813:                     $cathash = {};
20814:                 } 
20815:                 my (@cats,@trails,%allitems);
20816:                     &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,\%allitems);
20817:                 if (keys(%deletions) > 0) {
20818:                     $resulttext .= '<li>'.&mt('Deleted categories:').'<ul>';
20819:                     foreach my $predeltrail (sort {$a <=> $b } (keys(%sort_by_deltrail))) { 
20820:                         $resulttext .= '<li>'.$predeltrails[$predeltrail].'</li>';
20821:                     }
20822:                     $resulttext .= '</ul></li>';
20823:                 }
20824:                 if (keys(%reorderings) > 0) {
20825:                     my %sort_by_trail;
20826:                     $resulttext .= '<li>'.&mt('Reordered categories:').'<ul>';
20827:                     foreach my $key (keys(%reorderings)) {
20828:                         if ($allitems{$key} ne '') {
20829:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
20830:                         }
20831:                     }
20832:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
20833:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
20834:                     }
20835:                     $resulttext .= '</ul></li>';
20836:                 }
20837:                 if (keys(%adds) > 0) {
20838:                     my %sort_by_trail;
20839:                     $resulttext .= '<li>'.&mt('Added categories:').'<ul>';
20840:                     foreach my $key (keys(%adds)) {
20841:                         if ($allitems{$key} ne '') {
20842:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
20843:                         }
20844:                     }
20845:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
20846:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
20847:                     }
20848:                     $resulttext .= '</ul></li>';
20849:                 }
20850:                 &Apache::lonnet::do_cache_new('cats',$dom,$cathash,3600);
20851:                 if (ref($lastactref) eq 'HASH') {
20852:                     $lastactref->{'cats'} = 1;
20853:                 }
20854:             }
20855:             $resulttext .= '</ul>';
20856:             if ($changes{'unauth'} || $changes{'auth'}) {
20857:                 my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
20858:                 if ($changes{'auth'}) {
20859:                     $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
20860:                 }
20861:                 if ($changes{'unauth'}) {
20862:                     $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
20863:                 }
20864:                 my $cachetime = 24*60*60;
20865:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
20866:                 if (ref($lastactref) eq 'HASH') {
20867:                     $lastactref->{'domdefaults'} = 1;
20868:                 }
20869:             }
20870:         } else {
20871:             $resulttext = '<span class="LC_error">'.
20872:                           &mt('An error occurred: [_1]',$putresult).'</span>';
20873:         }
20874:     } else {
20875:         $resulttext = &mt('No changes made to course and community categories');
20876:     }
20877:     return $resulttext;
20878: }
20879: 
20880: sub modify_serverstatuses {
20881:     my ($dom,%domconfig) = @_;
20882:     my ($resulttext,%changes,%currserverstatus,%newserverstatus);
20883:     if (ref($domconfig{'serverstatuses'}) eq 'HASH') {
20884:         %currserverstatus = %{$domconfig{'serverstatuses'}};
20885:     }
20886:     my @pages = &serverstatus_pages();
20887:     foreach my $type (@pages) {
20888:         $newserverstatus{$type}{'namedusers'} = '';
20889:         $newserverstatus{$type}{'machines'} = '';
20890:         if (defined($env{'form.'.$type.'_namedusers'})) {
20891:             my @users = split(/,/,$env{'form.'.$type.'_namedusers'});
20892:             my @okusers;
20893:             foreach my $user (@users) {
20894:                 my ($uname,$udom) = split(/:/,$user);
20895:                 if (($udom =~ /^$match_domain$/) &&   
20896:                     (&Apache::lonnet::domain($udom)) &&
20897:                     ($uname =~ /^$match_username$/)) {
20898:                     if (!grep(/^\Q$user\E/,@okusers)) {
20899:                         push(@okusers,$user);
20900:                     }
20901:                 }
20902:             }
20903:             if (@okusers > 0) {
20904:                  @okusers = sort(@okusers);
20905:                  $newserverstatus{$type}{'namedusers'} = join(',',@okusers);
20906:             }
20907:         }
20908:         if (defined($env{'form.'.$type.'_machines'})) {
20909:             my @machines = split(/,/,$env{'form.'.$type.'_machines'});
20910:             my @okmachines;
20911:             foreach my $ip (@machines) {
20912:                 my @parts = split(/\./,$ip);
20913:                 next if (@parts < 4);
20914:                 my $badip = 0;
20915:                 for (my $i=0; $i<4; $i++) {
20916:                     if (!(($parts[$i] >= 0) && ($parts[$i] <= 255))) {
20917:                         $badip = 1;
20918:                         last;
20919:                     }
20920:                 }
20921:                 if (!$badip) {
20922:                     push(@okmachines,$ip);     
20923:                 }
20924:             }
20925:             @okmachines = sort(@okmachines);
20926:             $newserverstatus{$type}{'machines'} = join(',',@okmachines);
20927:         }
20928:     }
20929:     my %serverstatushash =  (
20930:                                 serverstatuses => \%newserverstatus,
20931:                             );
20932:     foreach my $type (@pages) {
20933:         foreach my $setting ('namedusers','machines') {
20934:             my (@current,@new);
20935:             if (ref($currserverstatus{$type}) eq 'HASH') {
20936:                 if ($currserverstatus{$type}{$setting} ne '') { 
20937:                     @current = split(/,/,$currserverstatus{$type}{$setting});
20938:                 }
20939:             }
20940:             if ($newserverstatus{$type}{$setting} ne '') {
20941:                 @new = split(/,/,$newserverstatus{$type}{$setting});
20942:             }
20943:             if (@current > 0) {
20944:                 if (@new > 0) {
20945:                     foreach my $item (@current) {
20946:                         if (!grep(/^\Q$item\E$/,@new)) {
20947:                             $changes{$type}{$setting} = 1;
20948:                             last;
20949:                         }
20950:                     }
20951:                     foreach my $item (@new) {
20952:                         if (!grep(/^\Q$item\E$/,@current)) {
20953:                             $changes{$type}{$setting} = 1;
20954:                             last;
20955:                         }
20956:                     }
20957:                 } else {
20958:                     $changes{$type}{$setting} = 1;
20959:                 }
20960:             } elsif (@new > 0) {
20961:                 $changes{$type}{$setting} = 1;
20962:             }
20963:         }
20964:     }
20965:     if (keys(%changes) > 0) {
20966:         my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
20967:         my $putresult = &Apache::lonnet::put_dom('configuration',
20968:                                                  \%serverstatushash,$dom);
20969:         if ($putresult eq 'ok') {
20970:             $resulttext .= &mt('Changes made:').'<ul>';
20971:             foreach my $type (@pages) {
20972:                 if (ref($changes{$type}) eq 'HASH') {
20973:                     $resulttext .= '<li>'.$titles->{$type}.'<ul>';
20974:                     if ($changes{$type}{'namedusers'}) {
20975:                         if ($newserverstatus{$type}{'namedusers'} eq '') {
20976:                             $resulttext .= '<li>'.&mt("Access terminated for all specific (named) users").'</li>'."\n";
20977:                         } else {
20978:                             $resulttext .= '<li>'.&mt("Access available for the following specified users: ").$newserverstatus{$type}{'namedusers'}.'</li>'."\n";
20979:                         }
20980:                     }
20981:                     if ($changes{$type}{'machines'}) {
20982:                         if ($newserverstatus{$type}{'machines'} eq '') {
20983:                             $resulttext .= '<li>'.&mt("Access terminated for all specific IP addresses").'</li>'."\n";
20984:                         } else {
20985:                             $resulttext .= '<li>'.&mt("Access available for the following specified IP addresses: ").$newserverstatus{$type}{'machines'}.'</li>'."\n";
20986:                         }
20987: 
20988:                     }
20989:                     $resulttext .= '</ul></li>';
20990:                 }
20991:             }
20992:             $resulttext .= '</ul>';
20993:         } else {
20994:             $resulttext = '<span class="LC_error">'.
20995:                           &mt('An error occurred saving access settings for server status pages: [_1].',$putresult).'</span>';
20996: 
20997:         }
20998:     } else {
20999:         $resulttext = &mt('No changes made to access to server status pages');
21000:     }
21001:     return $resulttext;
21002: }
21003: 
21004: sub modify_helpsettings {
21005:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
21006:     my ($resulttext,$errors,%changes,%helphash);
21007:     my %defaultchecked = ('submitbugs' => 'on');
21008:     my @offon = ('off','on');
21009:     my @toggles = ('submitbugs');
21010:     my %current = ('submitbugs' => '',
21011:                    'adhoc'      => {},
21012:                   );
21013:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
21014:         %current = %{$domconfig{'helpsettings'}};
21015:     }
21016:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
21017:     foreach my $item (@toggles) {
21018:         if ($defaultchecked{$item} eq 'on') { 
21019:             if ($current{$item} eq '') {
21020:                 if ($env{'form.'.$item} eq '0') {
21021:                     $changes{$item} = 1;
21022:                 }
21023:             } elsif ($current{$item} ne $env{'form.'.$item}) {
21024:                 $changes{$item} = 1;
21025:             }
21026:         } elsif ($defaultchecked{$item} eq 'off') {
21027:             if ($current{$item} eq '') {
21028:                 if ($env{'form.'.$item} eq '1') {
21029:                     $changes{$item} = 1;
21030:                 }
21031:             } elsif ($current{$item} ne $env{'form.'.$item}) {
21032:                 $changes{$item} = 1;
21033:             }
21034:         }
21035:         if (($env{'form.'.$item} eq '0') || ($env{'form.'.$item} eq '1')) {
21036:             $helphash{'helpsettings'}{$item} = $env{'form.'.$item};
21037:         }
21038:     }
21039:     my $maxnum = $env{'form.helproles_maxnum'};
21040:     my $confname = $dom.'-domainconfig';
21041:     my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
21042:     my (@allpos,%newsettings,%changedprivs,$newrole);
21043:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
21044:     my @accesstypes = ('all','dh','da','none','status','inc','exc');
21045:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh','da']);
21046:     my %lt = &Apache::lonlocal::texthash(
21047:                     s      => 'system',
21048:                     d      => 'domain',
21049:                     order  => 'Display order',
21050:                     access => 'Role usage',
21051:                     all    => 'All with domain helpdesk or helpdesk assistant role',
21052:                     dh     => 'All with domain helpdesk role',
21053:                     da     => 'All with domain helpdesk assistant role',
21054:                     none   => 'None',
21055:                     status => 'Determined based on institutional status',
21056:                     inc    => 'Include all, but exclude specific personnel',
21057:                     exc    => 'Exclude all, but include specific personnel',
21058:     );
21059:     for (my $num=0; $num<=$maxnum; $num++) {
21060:         my ($prefix,$identifier,$rolename,%curr);
21061:         if ($num == $maxnum) {
21062:             next unless ($env{'form.newcusthelp'} == $maxnum);
21063:             $identifier = 'custhelp'.$num;
21064:             $prefix = 'helproles_'.$num;
21065:             $rolename = $env{'form.custhelpname'.$num};
21066:             $rolename=~s/[^A-Za-z0-9]//gs;
21067:             next if ($rolename eq '');
21068:             next if (exists($existing{'rolesdef_'.$rolename}));
21069:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
21070:             my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
21071:                                                      $newprivs{'c'},$confname,$dom);
21072:             if ($result ne 'ok') {
21073:                 $errors .= '<li><span class="LC_error">'.
21074:                            &mt('An error occurred storing the new custom role: [_1]',
21075:                            $result).'</span></li>';
21076:                 next;
21077:             } else {
21078:                 $changedprivs{$rolename} = \%newprivs;
21079:                 $newrole = $rolename;
21080:             }
21081:         } else {
21082:             $prefix = 'helproles_'.$num;
21083:             $rolename = $env{'form.'.$prefix};
21084:             next if ($rolename eq '');
21085:             next unless (exists($existing{'rolesdef_'.$rolename}));
21086:             $identifier = 'custhelp'.$num;
21087:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
21088:             my %currprivs;
21089:             ($currprivs{'s'},$currprivs{'d'},$currprivs{'c'}) =
21090:                 split(/\_/,$existing{'rolesdef_'.$rolename});
21091:             foreach my $level ('c','d','s') {
21092:                 if ($newprivs{$level} ne $currprivs{$level}) {
21093:                     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
21094:                                                              $newprivs{'c'},$confname,$dom);
21095:                     if ($result ne 'ok') {
21096:                         $errors .= '<li><span class="LC_error">'.
21097:                                    &mt('An error occurred storing privileges for existing role [_1]: [_2]',
21098:                                        $rolename,$result).'</span></li>';
21099:                     } else {
21100:                         $changedprivs{$rolename} = \%newprivs;
21101:                     }
21102:                     last;
21103:                 }
21104:             }
21105:             if (ref($current{'adhoc'}) eq 'HASH') {
21106:                 if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
21107:                     %curr = %{$current{'adhoc'}{$rolename}};
21108:                 }
21109:             }
21110:         }
21111:         my $newpos = $env{'form.'.$prefix.'_pos'};
21112:         $newpos =~ s/\D+//g;
21113:         $allpos[$newpos] = $rolename;
21114:         my $newdesc = $env{'form.'.$prefix.'_desc'};
21115:         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'desc'} = $newdesc;
21116:         if ($curr{'desc'}) {
21117:             if ($curr{'desc'} ne $newdesc) {
21118:                 $changes{'customrole'}{$rolename}{'desc'} = 1;
21119:                 $newsettings{$rolename}{'desc'} = $newdesc;
21120:             }
21121:         } elsif ($newdesc ne '') {
21122:             $changes{'customrole'}{$rolename}{'desc'} = 1;
21123:             $newsettings{$rolename}{'desc'} = $newdesc;
21124:         }
21125:         my $access = $env{'form.'.$prefix.'_access'};
21126:         if (grep(/^\Q$access\E$/,@accesstypes)) {
21127:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = $access;
21128:             if ($access eq 'status') {
21129:                 my @statuses = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_status');
21130:                 if (scalar(@statuses) == 0) {
21131:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'none';
21132:                 } else {
21133:                     my (@shownstatus,$numtypes);
21134:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
21135:                     if (ref($types) eq 'ARRAY') {
21136:                         $numtypes = scalar(@{$types});
21137:                         foreach my $type (sort(@statuses)) {
21138:                             if ($type eq 'default') {
21139:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
21140:                             } elsif (grep(/^\Q$type\E$/,@{$types})) {
21141:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
21142:                                 push(@shownstatus,$usertypes->{$type});
21143:                             }
21144:                         }
21145:                     }
21146:                     if (grep(/^default$/,@statuses)) {
21147:                         push(@shownstatus,$othertitle);
21148:                     }
21149:                     if (scalar(@shownstatus) == 1+$numtypes) {
21150:                         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'all';
21151:                         delete($helphash{'helpsettings'}{'adhoc'}{$rolename}{'status'});
21152:                     } else {
21153:                         $newsettings{$rolename}{'status'} = join(' '.&mt('or').' ',@shownstatus);
21154:                         if (ref($curr{'status'}) eq 'ARRAY') {
21155:                             my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
21156:                             if (@diffs) {
21157:                                 $changes{'customrole'}{$rolename}{$access} = 1;
21158:                             }
21159:                         } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
21160:                             $changes{'customrole'}{$rolename}{$access} = 1;
21161:                         }
21162:                     }
21163:                 }
21164:             } elsif (($access eq 'inc') || ($access eq 'exc')) {
21165:                 my @personnel = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_staff_'.$access);
21166:                 my @newspecstaff;
21167:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
21168:                 foreach my $person (sort(@personnel)) {
21169:                     if ($domhelpdesk{$person}) {
21170:                         push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$person);
21171:                     }
21172:                 }
21173:                 if (ref($curr{$access}) eq 'ARRAY') {
21174:                     my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
21175:                     if (@diffs) {
21176:                         $changes{'customrole'}{$rolename}{$access} = 1;
21177:                     }
21178:                 } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
21179:                     $changes{'customrole'}{$rolename}{$access} = 1;
21180:                 }
21181:                 foreach my $person (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
21182:                     my ($uname,$udom) = split(/:/,$person);
21183:                         push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
21184:                 }
21185:                 $newsettings{$rolename}{$access} = join(', ',sort(@newspecstaff));
21186:             }
21187:         } else {
21188:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}= 'all';
21189:         }
21190:         unless ($curr{'access'} eq $access) {
21191:             $changes{'customrole'}{$rolename}{'access'} = 1;
21192:             $newsettings{$rolename}{'access'} = $lt{$helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}};
21193:         }
21194:     }
21195:     if (@allpos > 0) {
21196:         my $idx = 0;
21197:         foreach my $rolename (@allpos) {
21198:             if ($rolename ne '') {
21199:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{'order'} = $idx;
21200:                 if (ref($current{'adhoc'}) eq 'HASH') {
21201:                     if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
21202:                         if ($current{'adhoc'}{$rolename}{'order'} ne $idx) {
21203:                             $changes{'customrole'}{$rolename}{'order'} = 1;
21204:                             $newsettings{$rolename}{'order'} = $idx+1;
21205:                         }
21206:                     }
21207:                 }
21208:                 $idx ++;
21209:             }
21210:         }
21211:     }
21212:     my $putresult;
21213:     if (keys(%changes) > 0) {
21214:         $putresult = &Apache::lonnet::put_dom('configuration',\%helphash,$dom);
21215:         if ($putresult eq 'ok') {
21216:             if (ref($helphash{'helpsettings'}) eq 'HASH') {
21217:                 $domdefaults{'submitbugs'} = $helphash{'helpsettings'}{'submitbugs'};
21218:                 if (ref($helphash{'helpsettings'}{'adhoc'}) eq 'HASH') {
21219:                     $domdefaults{'adhocroles'} = $helphash{'helpsettings'}{'adhoc'};
21220:                 }
21221:             }
21222:             my $cachetime = 24*60*60;
21223:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
21224:             if (ref($lastactref) eq 'HASH') {
21225:                 $lastactref->{'domdefaults'} = 1;
21226:             }
21227:         } else {
21228:             $errors .= '<li><span class="LC_error">'.
21229:                        &mt('An error occurred storing the settings: [_1]',
21230:                            $putresult).'</span></li>';
21231:         }
21232:     }
21233:     if ((keys(%changes) && ($putresult eq 'ok')) || (keys(%changedprivs))) {
21234:         $resulttext = &mt('Changes made:').'<ul>';
21235:         my (%shownprivs,@levelorder);
21236:         @levelorder = ('c','d','s');
21237:         if ((keys(%changes)) && ($putresult eq 'ok')) {
21238:             foreach my $item (sort(keys(%changes))) {
21239:                 if ($item eq 'submitbugs') {
21240:                     $resulttext .= '<li>'.&mt('Display link to: [_1] set to "'.$offon[$env{'form.'.$item}].'".',
21241:                                               &Apache::loncommon::modal_link('http://bugs.loncapa.org',
21242:                                               &mt('LON-CAPA bug tracker'),600,500)).'</li>';
21243:                 } elsif ($item eq 'customrole') {
21244:                     if (ref($changes{'customrole'}) eq 'HASH') {
21245:                         my @keyorder = ('order','desc','access','status','exc','inc');
21246:                         my %keytext = &Apache::lonlocal::texthash(
21247:                                                                    order  => 'Order',
21248:                                                                    desc   => 'Role description',
21249:                                                                    access => 'Role usage',
21250:                                                                    status => 'Allowed institutional types',
21251:                                                                    exc    => 'Allowed personnel',
21252:                                                                    inc    => 'Disallowed personnel',
21253:                         );
21254:                         foreach my $role (sort(keys(%{$changes{'customrole'}}))) {
21255:                             if (ref($changes{'customrole'}{$role}) eq 'HASH') {
21256:                                 if ($role eq $newrole) {
21257:                                     $resulttext .= '<li>'.&mt('New custom role added: [_1]',
21258:                                                               $role).'<ul>';
21259:                                 } else {
21260:                                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
21261:                                                               $role).'<ul>';
21262:                                 }
21263:                                 foreach my $key (@keyorder) {
21264:                                     if ($changes{'customrole'}{$role}{$key}) {
21265:                                         $resulttext .= '<li>'.&mt("[_1] set to: [_2]",
21266:                                                                   $keytext{$key},$newsettings{$role}{$key}).
21267:                                                        '</li>';
21268:                                     }
21269:                                 }
21270:                                 if (ref($changedprivs{$role}) eq 'HASH') {
21271:                                     $shownprivs{$role} = 1;
21272:                                     $resulttext .= '<li>'.&mt('Privileges set to :').'<ul>';
21273:                                     foreach my $level (@levelorder) {
21274:                                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
21275:                                             next if ($item eq '');
21276:                                             my ($priv) = split(/\&/,$item,2);
21277:                                             if (&Apache::lonnet::plaintext($priv)) {
21278:                                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
21279:                                                 unless ($level eq 'c') {
21280:                                                     $resulttext .= ' ('.$lt{$level}.')';
21281:                                                 }
21282:                                                 $resulttext .= '</li>';
21283:                                             }
21284:                                         }
21285:                                     }
21286:                                     $resulttext .= '</ul>';
21287:                                 }
21288:                                 $resulttext .= '</ul></li>';
21289:                             }
21290:                         }
21291:                     }
21292:                 }
21293:             }
21294:         }
21295:         if (keys(%changedprivs)) {
21296:             foreach my $role (sort(keys(%changedprivs))) {
21297:                 unless ($shownprivs{$role}) {
21298:                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
21299:                                               $role).'<ul>'.
21300:                                    '<li>'.&mt('Privileges set to :').'<ul>';
21301:                     foreach my $level (@levelorder) {
21302:                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
21303:                             next if ($item eq '');
21304:                             my ($priv) = split(/\&/,$item,2);
21305:                             if (&Apache::lonnet::plaintext($priv)) {
21306:                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
21307:                                 unless ($level eq 'c') {
21308:                                     $resulttext .= ' ('.$lt{$level}.')';
21309:                                 }
21310:                                 $resulttext .= '</li>';
21311:                             }
21312:                         }
21313:                     }
21314:                     $resulttext .= '</ul></li></ul></li>';
21315:                 }
21316:             }
21317:         }
21318:         $resulttext .= '</ul>';
21319:     } else {
21320:         $resulttext = &mt('No changes made to help settings');
21321:     }
21322:     if ($errors) {
21323:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
21324:                                     $errors.'</ul>';
21325:     }
21326:     return $resulttext;
21327: }
21328: 
21329: sub modify_coursedefaults {
21330:     my ($dom,$lastactref,%domconfig) = @_;
21331:     my ($resulttext,$errors,%changes,%defaultshash);
21332:     my %defaultchecked = (
21333:                            'canuse_pdfforms' => 'off',
21334:                            'uselcmath'       => 'on',
21335:                            'usejsme'         => 'on',
21336:                            'inline_chem'     => 'on',
21337:                            'ltiauth'         => 'off',
21338:                          );
21339:     my @toggles = ('canuse_pdfforms','uselcmath','usejsme','inline_chem','ltiauth');
21340:     my @numbers = ('anonsurvey_threshold','uploadquota_official','uploadquota_unofficial',
21341:                    'uploadquota_community','uploadquota_textbook','uploadquota_placement',
21342:                    'mysqltables_official','mysqltables_unofficial','mysqltables_community',
21343:                    'mysqltables_textbook','mysqltables_placement');
21344:     my @types = ('official','unofficial','community','textbook','placement');
21345:     my %staticdefaults = (
21346:                            anonsurvey_threshold => 10,
21347:                            uploadquota          => 500,
21348:                            postsubmit           => 60,
21349:                            mysqltables          => 172800,
21350:                          );
21351:     my %texoptions = (
21352:                         MathJax  => 'MathJax',
21353:                         mimetex  => &mt('Convert to Images'),
21354:                         tth      => &mt('TeX to HTML'),
21355:                      );
21356:     $defaultshash{'coursedefaults'} = {};
21357: 
21358:     if (ref($domconfig{'coursedefaults'}) ne 'HASH') {
21359:         if ($domconfig{'coursedefaults'} eq '') {
21360:             $domconfig{'coursedefaults'} = {};
21361:         }
21362:     }
21363: 
21364:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
21365:         foreach my $item (@toggles) {
21366:             if ($defaultchecked{$item} eq 'on') {
21367:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
21368:                     ($env{'form.'.$item} eq '0')) {
21369:                     $changes{$item} = 1;
21370:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
21371:                     $changes{$item} = 1;
21372:                 }
21373:             } elsif ($defaultchecked{$item} eq 'off') {
21374:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
21375:                     ($env{'form.'.$item} eq '1')) {
21376:                     $changes{$item} = 1;
21377:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
21378:                     $changes{$item} = 1;
21379:                 }
21380:             }
21381:             $defaultshash{'coursedefaults'}{$item} = $env{'form.'.$item};
21382:         }
21383:         foreach my $item (@numbers) {
21384:             my ($currdef,$newdef);
21385:             $newdef = $env{'form.'.$item};
21386:             if ($item eq 'anonsurvey_threshold') {
21387:                 $currdef = $domconfig{'coursedefaults'}{$item};
21388:                 $newdef =~ s/\D//g;
21389:                 if ($newdef eq '' || $newdef < 1) {
21390:                     $newdef = 1;
21391:                 }
21392:                 $defaultshash{'coursedefaults'}{$item} = $newdef;
21393:             } else {
21394:                 my ($setting,$type) = ($item =~ /^(uploadquota|mysqltables)_(\w+)$/);
21395:                 if (ref($domconfig{'coursedefaults'}{$setting}) eq 'HASH') {
21396:                     $currdef = $domconfig{'coursedefaults'}{$setting}{$type};
21397:                 }
21398:                 $newdef =~ s/[^\w.\-]//g;
21399:                 $defaultshash{'coursedefaults'}{$setting}{$type} = $newdef;
21400:             }
21401:             if ($currdef ne $newdef) {
21402:                 if ($item eq 'anonsurvey_threshold') {
21403:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$item})) {
21404:                         $changes{$item} = 1;
21405:                     }
21406:                 } elsif ($item =~ /^(uploadquota|mysqltables)_/) {
21407:                     my $setting = $1;
21408:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$setting})) {
21409:                         $changes{$setting} = 1;
21410:                     }
21411:                 }
21412:             }
21413:         }
21414:         my $texengine;
21415:         if ($env{'form.texengine'} =~ /^(MathJax|mimetex|tth)$/) {
21416:             $texengine = $env{'form.texengine'};
21417:             my $currdef = $domconfig{'coursedefaults'}{'texengine'};
21418:             if ($currdef eq '') {
21419:                 unless ($texengine eq $Apache::lonnet::deftex) {
21420:                     $changes{'texengine'} = 1;
21421:                 }
21422:             } elsif ($currdef ne $texengine) {
21423:                 $changes{'texengine'} = 1;
21424:             }
21425:         }
21426:         if ($texengine ne '') {
21427:             $defaultshash{'coursedefaults'}{'texengine'} = $texengine;
21428:         }
21429:         my $currclone = $domconfig{'coursedefaults'}{'canclone'};
21430:         my @currclonecode;
21431:         if (ref($currclone) eq 'HASH') {
21432:             if (ref($currclone->{'instcode'}) eq 'ARRAY') {
21433:                 @currclonecode = @{$currclone->{'instcode'}};
21434:             }
21435:         }
21436:         my $newclone;
21437:         if ($env{'form.canclone'} =~ /^(none|domain|instcode)$/) {
21438:             $newclone = $env{'form.canclone'};
21439:         }
21440:         if ($newclone eq 'instcode') {
21441:             my @newcodes = &Apache::loncommon::get_env_multiple('form.clonecode');
21442:             my (%codedefaults,@code_order,@clonecode);
21443:             &Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
21444:                                                     \@code_order);
21445:             foreach my $item (@code_order) {
21446:                 if (grep(/^\Q$item\E$/,@newcodes)) {
21447:                     push(@clonecode,$item);
21448:                 }
21449:             }
21450:             if (@clonecode) {
21451:                 $defaultshash{'coursedefaults'}{'canclone'} = { $newclone => \@clonecode };
21452:                 my @diffs = &Apache::loncommon::compare_arrays(\@currclonecode,\@clonecode);
21453:                 if (@diffs) {
21454:                     $changes{'canclone'} = 1;
21455:                 }
21456:             } else {
21457:                 $newclone eq '';
21458:             }
21459:         } elsif ($newclone ne '') {
21460:             $defaultshash{'coursedefaults'}{'canclone'} = $newclone;
21461:         }
21462:         if ($newclone ne $currclone) {
21463:             $changes{'canclone'} = 1;
21464:         }
21465:         my %credits;
21466:         foreach my $type (@types) {
21467:             unless ($type eq 'community') {
21468:                 $credits{$type} = $env{'form.'.$type.'_credits'};
21469:                 $credits{$type} =~ s/[^\d.]+//g;
21470:             }
21471:         }
21472:         if ((ref($domconfig{'coursedefaults'}{'coursecredits'}) ne 'HASH') &&
21473:             ($env{'form.coursecredits'} eq '1')) {
21474:             $changes{'coursecredits'} = 1;
21475:             foreach my $type (keys(%credits)) {
21476:                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
21477:             }
21478:         } else {
21479:             if ($env{'form.coursecredits'} eq '1') {
21480:                 foreach my $type (@types) {
21481:                     unless ($type eq 'community') {
21482:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type} ne $credits{$type}) {
21483:                             $changes{'coursecredits'} = 1;
21484:                         }
21485:                         $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
21486:                     }
21487:                 }
21488:             } elsif (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
21489:                 foreach my $type (@types) {
21490:                     unless ($type eq 'community') {
21491:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type}) {
21492:                             $changes{'coursecredits'} = 1;
21493:                             last;
21494:                         }
21495:                     }
21496:                 }
21497:             }
21498:         }
21499:         if ($env{'form.postsubmit'} eq '1') {
21500:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'on';
21501:             my %currtimeout;
21502:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
21503:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'off') {
21504:                     $changes{'postsubmit'} = 1;
21505:                 }
21506:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
21507:                     %currtimeout = %{$domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}};
21508:                 }
21509:             } else {
21510:                 $changes{'postsubmit'} = 1;
21511:             }
21512:             foreach my $type (@types) {
21513:                 my $timeout = $env{'form.'.$type.'_timeout'};
21514:                 $timeout =~ s/\D//g;
21515:                 if ($timeout == $staticdefaults{'postsubmit'}) {
21516:                     $timeout = '';
21517:                 } elsif (($timeout eq '') || ($timeout =~ /^0+$/)) {
21518:                     $timeout = '0';
21519:                 }
21520:                 unless ($timeout eq '') {
21521:                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type} = $timeout;
21522:                 }
21523:                 if (exists($currtimeout{$type})) {
21524:                     if ($timeout ne $currtimeout{$type}) {
21525:                         $changes{'postsubmit'} = 1;
21526:                     }
21527:                 } elsif ($timeout ne '') {
21528:                     $changes{'postsubmit'} = 1;
21529:                 }
21530:             }
21531:         } else {
21532:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'off';
21533:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
21534:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'on') {
21535:                     $changes{'postsubmit'} = 1;
21536:                 }
21537:             } else {
21538:                 $changes{'postsubmit'} = 1;
21539:             }
21540:         }
21541:     }
21542:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
21543:                                              $dom);
21544:     if ($putresult eq 'ok') {
21545:         if (keys(%changes) > 0) {
21546:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
21547:             if (($changes{'canuse_pdfforms'}) || ($changes{'uploadquota'}) || ($changes{'postsubmit'}) ||
21548:                 ($changes{'coursecredits'}) || ($changes{'uselcmath'}) || ($changes{'usejsme'}) ||
21549:                 ($changes{'canclone'}) || ($changes{'mysqltables'}) || ($changes{'texengine'}) ||
21550:                 ($changes{'inline_chem'}) || ($changes{'ltiauth'})) {
21551:                 foreach my $item ('canuse_pdfforms','uselcmath','usejsme','inline_chem','texengine','ltiauth') {
21552:                     if ($changes{$item}) {
21553:                         $domdefaults{$item}=$defaultshash{'coursedefaults'}{$item};
21554:                     }
21555:                 }
21556:                 if ($changes{'coursecredits'}) {
21557:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
21558:                         foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'coursecredits'}})) {
21559:                             $domdefaults{$type.'credits'} =
21560:                                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type};
21561:                         }
21562:                     }
21563:                 }
21564:                 if ($changes{'postsubmit'}) {
21565:                     if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
21566:                         $domdefaults{'postsubmit'} = $defaultshash{'coursedefaults'}{'postsubmit'}{'client'};
21567:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
21568:                             foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}})) {
21569:                                 $domdefaults{$type.'postsubtimeout'} =
21570:                                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
21571:                             }
21572:                         }
21573:                     }
21574:                 }
21575:                 if ($changes{'uploadquota'}) {
21576:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
21577:                         foreach my $type (@types) {
21578:                             $domdefaults{$type.'quota'}=$defaultshash{'coursedefaults'}{'uploadquota'}{$type};
21579:                         }
21580:                     }
21581:                 }
21582:                 if ($changes{'canclone'}) {
21583:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
21584:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
21585:                             my @clonecodes = @{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}};
21586:                             if (@clonecodes) {
21587:                                 $domdefaults{'canclone'} = join('+',@clonecodes);
21588:                             }
21589:                         }
21590:                     } else {
21591:                         $domdefaults{'canclone'}=$defaultshash{'coursedefaults'}{'canclone'};
21592:                     }
21593:                 }
21594:                 my $cachetime = 24*60*60;
21595:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
21596:                 if (ref($lastactref) eq 'HASH') {
21597:                     $lastactref->{'domdefaults'} = 1;
21598:                 }
21599:             }
21600:             $resulttext = &mt('Changes made:').'<ul>';
21601:             foreach my $item (sort(keys(%changes))) {
21602:                 if ($item eq 'canuse_pdfforms') {
21603:                     if ($env{'form.'.$item} eq '1') {
21604:                         $resulttext .= '<li>'.&mt("Course/Community users can create/upload PDF forms set to 'on'").'</li>';
21605:                     } else {
21606:                         $resulttext .= '<li>'.&mt('Course/Community users can create/upload PDF forms set to "off"').'</li>';
21607:                     }
21608:                 } elsif ($item eq 'uselcmath') {
21609:                     if ($env{'form.'.$item} eq '1') {
21610:                         $resulttext .= '<li>'.&mt('Math preview uses LON-CAPA previewer (javascript), if supported by browser.').'</li>';
21611:                     } else {
21612:                         $resulttext .= '<li>'.&mt('Math preview uses DragMath (Java), if supported by client OS.').'</li>';
21613:                     }
21614:                 } elsif ($item eq 'usejsme') {
21615:                     if ($env{'form.'.$item} eq '1') {
21616:                         $resulttext .= '<li>'.&mt('Molecule editor uses JSME (HTML5), if supported by browser.').'</li>';
21617:                     } else {
21618:                         $resulttext .= '<li>'.&mt('Molecule editor uses JME (Java), if supported by client OS.').'</li>';
21619:                     }
21620:                 } elsif ($item eq 'inline_chem') {
21621:                     if ($env{'form.'.$item} eq '1') {
21622:                         $resulttext .= '<li>'.&mt('Chemical Reaction Response uses inline previewer').'</li>';
21623:                     } else {
21624:                         $resulttext .= '<li>'.&mt('Chemical Reaction Response uses pop-up previewer').'</li>';
21625:                     }
21626:                 } elsif ($item eq 'texengine') {
21627:                     if ($defaultshash{'coursedefaults'}{'texengine'} ne '') {
21628:                         $resulttext .= '<li>'.&mt('Default method to display mathematics set to: "[_1]"',
21629:                                                   $texoptions{$defaultshash{'coursedefaults'}{'texengine'}}).'</li>';
21630:                     }
21631:                 } elsif ($item eq 'anonsurvey_threshold') {
21632:                     $resulttext .= '<li>'.&mt('Responder count required for display of anonymous survey submissions set to [_1].',$defaultshash{'coursedefaults'}{'anonsurvey_threshold'}).'</li>';
21633:                 } elsif ($item eq 'uploadquota') {
21634:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
21635:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded to a course/community via Course Editor set as follows:').'<ul>'.
21636:                                        '<li>'.&mt('Official courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'official'}.'</b>').'</li>'.
21637:                                        '<li>'.&mt('Unofficial courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'unofficial'}.'</b>').'</li>'.
21638:                                        '<li>'.&mt('Textbook courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'textbook'}.'</b>').'</li>'.
21639:                                        '<li>'.&mt('Placement tests: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'placement'}.'</b>').'</li>'. 
21640:                                        '<li>'.&mt('Communities: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'community'}.'</b>').'</li>'.
21641:                                        '</ul>'.
21642:                                        '</li>';
21643:                     } else {
21644:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded via Course Editor remains default: [_1] MB',$staticdefaults{'uploadquota'}).'</li>';
21645:                     }
21646:                 } elsif ($item eq 'mysqltables') {
21647:                     if (ref($defaultshash{'coursedefaults'}{'mysqltables'}) eq 'HASH') {
21648:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver').'<ul>'.
21649:                                        '<li>'.&mt('Official courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'official'}.'</b>').'</li>'.
21650:                                        '<li>'.&mt('Unofficial courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'unofficial'}.'</b>').'</li>'.
21651:                                        '<li>'.&mt('Textbook courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'textbook'}.'</b>').'</li>'.
21652:                                        '<li>'.&mt('Placement tests: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'placement'}.'</b>').'</li>'.
21653:                                        '<li>'.&mt('Communities: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'community'}.'</b>').'</li>'.
21654:                                        '</ul>'.
21655:                                        '</li>';
21656:                     } else {
21657:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver remains default: [_1] s',$staticdefaults{'uploadquota'}).'</li>';
21658:                     }
21659:                 } elsif ($item eq 'postsubmit') {
21660:                     if ($domdefaults{'postsubmit'} eq 'off') {
21661:                         $resulttext .= '<li>'.&mt('Submit button(s) remain enabled on page after student makes submission.');
21662:                     } else {
21663:                         $resulttext .= '<li>'.&mt('Submit button(s) disabled on page after student makes submission').'; ';
21664:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
21665:                             $resulttext .= &mt('durations:').'<ul>';
21666:                             foreach my $type (@types) {
21667:                                 $resulttext .= '<li>';
21668:                                 my $timeout;
21669:                                 if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
21670:                                     $timeout = $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
21671:                                 }
21672:                                 my $display;
21673:                                 if ($timeout eq '0') {
21674:                                     $display = &mt('unlimited');
21675:                                 } elsif ($timeout eq '') {
21676:                                     $display = &mt('[quant,_1,second] (default)',$staticdefaults{'postsubmit'});
21677:                                 } else {
21678:                                     $display = &mt('[quant,_1,second]',$timeout);
21679:                                 }
21680:                                 if ($type eq 'community') {
21681:                                     $resulttext .= &mt('Communities');
21682:                                 } elsif ($type eq 'official') {
21683:                                     $resulttext .= &mt('Official courses');
21684:                                 } elsif ($type eq 'unofficial') {
21685:                                     $resulttext .= &mt('Unofficial courses');
21686:                                 } elsif ($type eq 'textbook') {
21687:                                     $resulttext .= &mt('Textbook courses');
21688:                                 } elsif ($type eq 'placement') {
21689:                                     $resulttext .= &mt('Placement tests');
21690:                                 }
21691:                                 $resulttext .= ' -- '.$display.'</li>';
21692:                             }
21693:                             $resulttext .= '</ul>';
21694:                         }
21695:                         $resulttext .= '</li>';
21696:                     }
21697:                 } elsif ($item eq 'coursecredits') {
21698:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
21699:                         if (($domdefaults{'officialcredits'} eq '') &&
21700:                             ($domdefaults{'unofficialcredits'} eq '') &&
21701:                             ($domdefaults{'textbookcredits'} eq '')) {
21702:                             $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
21703:                         } else {
21704:                             $resulttext .= '<li>'.&mt('Student credits can be set per course by a Domain Coordinator, with the following defaults applying:').'<ul>'.
21705:                                            '<li>'.&mt('Official courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'official'}).'</li>'.
21706:                                            '<li>'.&mt('Unofficial courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'unofficial'}).'</li>'.
21707:                                            '<li>'.&mt('Textbook courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'textbook'}).'</li>'.
21708:                                            '</ul>'.
21709:                                            '</li>';
21710:                         }
21711:                     } else {
21712:                         $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
21713:                     }
21714:                 } elsif ($item eq 'canclone') {
21715:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
21716:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
21717:                             my $clonecodes = join(' '.&mt('and').' ',@{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}});
21718:                             $resulttext .= '<li>'.&mt('By default, official courses can be cloned from existing courses with the same: [_1]','<b>'.$clonecodes.'</b>').'</li>';
21719:                         }
21720:                     } elsif ($defaultshash{'coursedefaults'}{'canclone'} eq 'domain') {
21721:                         $resulttext .= '<li>'.&mt('By default, a course requester can clone any course from his/her domain.').'</li>';
21722:                     } else {
21723:                         $resulttext .= '<li>'.&mt('By default, only course owner and coordinators may clone a course.').'</li>';
21724:                     }
21725:                 } elsif ($item eq 'ltiauth') {
21726:                     if ($env{'form.'.$item} eq '1') {
21727:                         $resulttext .= '<li>'.&mt('LTI launch of deep-linked URL need not require re-authentication').'</li>';
21728:                     } else {
21729:                         $resulttext .= '<li>'.&mt('LTI launch of deep-linked URL will require re-authentication').'</li>';
21730:                     }
21731:                 }
21732:             }
21733:             $resulttext .= '</ul>';
21734:         } else {
21735:             $resulttext = &mt('No changes made to course defaults');
21736:         }
21737:     } else {
21738:         $resulttext = '<span class="LC_error">'.
21739:             &mt('An error occurred: [_1]',$putresult).'</span>';
21740:     }
21741:     return $resulttext;
21742: }
21743: 
21744: sub modify_selfenrollment {
21745:     my ($dom,$lastactref,%domconfig) = @_;
21746:     my ($resulttext,$errors,%changes,%selfenrollhash,%ordered);
21747:     my @types = ('official','unofficial','community','textbook','placement');
21748:     my %titles = &tool_titles();
21749:     my %descs = &Apache::lonuserutils::selfenroll_default_descs();
21750:     ($ordered{'admin'},my $titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
21751:     $ordered{'default'} = ['types','registered','approval','limit'];
21752: 
21753:     my (%roles,%shown,%toplevel);
21754:     $roles{'0'} = &Apache::lonnet::plaintext('dc');
21755: 
21756:     if (ref($domconfig{'selfenrollment'}) ne 'HASH') {
21757:         if ($domconfig{'selfenrollment'} eq '') {
21758:             $domconfig{'selfenrollment'} = {};
21759:         }
21760:     }
21761:     %toplevel = (
21762:                   admin      => 'Configuration Rights',
21763:                   default    => 'Default settings',
21764:                   validation => 'Validation of self-enrollment requests',
21765:                 );
21766:     my ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
21767: 
21768:     if (ref($ordered{'admin'}) eq 'ARRAY') {
21769:         foreach my $item (@{$ordered{'admin'}}) {
21770:             foreach my $type (@types) {
21771:                 if ($env{'form.selfenrolladmin_'.$item.'_'.$type}) {
21772:                     $selfenrollhash{'admin'}{$type}{$item} = 1;
21773:                 } else {
21774:                     $selfenrollhash{'admin'}{$type}{$item} = 0;
21775:                 }
21776:                 if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
21777:                     if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
21778:                         if ($selfenrollhash{'admin'}{$type}{$item} ne
21779:                             $domconfig{'selfenrollment'}{'admin'}{$type}{$item})  {
21780:                             push(@{$changes{'admin'}{$type}},$item);
21781:                         }
21782:                     } else {
21783:                         if (!$selfenrollhash{'admin'}{$type}{$item}) {
21784:                             push(@{$changes{'admin'}{$type}},$item);
21785:                         }
21786:                     }
21787:                 } elsif (!$selfenrollhash{'admin'}{$type}{$item}) {
21788:                     push(@{$changes{'admin'}{$type}},$item);
21789:                 }
21790:             }
21791:         }
21792:     }
21793: 
21794:     foreach my $item (@{$ordered{'default'}}) {
21795:         foreach my $type (@types) {
21796:             my $value = $env{'form.selfenrolldefault_'.$item.'_'.$type};
21797:             if ($item eq 'types') {
21798:                 unless (($value eq 'all') || ($value eq 'dom')) {
21799:                     $value = '';
21800:                 }
21801:             } elsif ($item eq 'registered') {
21802:                 unless ($value eq '1') {
21803:                     $value = 0;
21804:                 }
21805:             } elsif ($item eq 'approval') {
21806:                 unless ($value =~ /^[012]$/) {
21807:                     $value = 0;
21808:                 }
21809:             } else {
21810:                 unless (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
21811:                     $value = 'none';
21812:                 }
21813:             }
21814:             $selfenrollhash{'default'}{$type}{$item} = $value;
21815:             if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
21816:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
21817:                     if ($selfenrollhash{'default'}{$type}{$item} ne
21818:                          $domconfig{'selfenrollment'}{'default'}{$type}{$item})  {
21819:                          push(@{$changes{'default'}{$type}},$item);
21820:                     }
21821:                 } else {
21822:                     push(@{$changes{'default'}{$type}},$item);
21823:                 }
21824:             } else {
21825:                 push(@{$changes{'default'}{$type}},$item);
21826:             }
21827:             if ($item eq 'limit') {
21828:                 if (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
21829:                     $env{'form.selfenrolldefault_cap_'.$type} =~ s/\D//g;
21830:                     if ($env{'form.selfenrolldefault_cap_'.$type} ne '') {
21831:                         $selfenrollhash{'default'}{$type}{'cap'} = $env{'form.selfenrolldefault_cap_'.$type};
21832:                     }
21833:                 } else {
21834:                     $selfenrollhash{'default'}{$type}{'cap'} = '';
21835:                 }
21836:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
21837:                     if ($selfenrollhash{'default'}{$type}{'cap'} ne
21838:                          $domconfig{'selfenrollment'}{'admin'}{$type}{'cap'})  {
21839:                          push(@{$changes{'default'}{$type}},'cap');
21840:                     }
21841:                 } elsif ($selfenrollhash{'default'}{$type}{'cap'} ne '') {
21842:                     push(@{$changes{'default'}{$type}},'cap');
21843:                 }
21844:             }
21845:         }
21846:     }
21847: 
21848:     foreach my $item (@{$itemsref}) {
21849:         if ($item eq 'fields') {
21850:             my @changed;
21851:             @{$selfenrollhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.selfenroll_validation_'.$item);
21852:             if (@{$selfenrollhash{'validation'}{$item}} > 0) {
21853:                 @{$selfenrollhash{'validation'}{$item}} = sort(@{$selfenrollhash{'validation'}{$item}});
21854:             }
21855:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
21856:                 if (ref($domconfig{'selfenrollment'}{'validation'}{$item}) eq 'ARRAY') {
21857:                     @changed = &Apache::loncommon::compare_arrays($selfenrollhash{'validation'}{$item},
21858:                                                                   $domconfig{'selfenrollment'}{'validation'}{$item});
21859:                 } else {
21860:                     @changed = @{$selfenrollhash{'validation'}{$item}};
21861:                 }
21862:             } else {
21863:                 @changed = @{$selfenrollhash{'validation'}{$item}};
21864:             }
21865:             if (@changed) {
21866:                 if ($selfenrollhash{'validation'}{$item}) { 
21867:                     $changes{'validation'}{$item} = join(', ',@{$selfenrollhash{'validation'}{$item}});
21868:                 } else {
21869:                     $changes{'validation'}{$item} = &mt('None');
21870:                 }
21871:             }
21872:         } else {
21873:             $selfenrollhash{'validation'}{$item} = $env{'form.selfenroll_validation_'.$item};
21874:             if ($item eq 'markup') {
21875:                if ($env{'form.selfenroll_validation_'.$item}) {
21876:                    $env{'form.selfenroll_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
21877:                }
21878:             }
21879:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
21880:                 if ($domconfig{'selfenrollment'}{'validation'}{$item} ne $selfenrollhash{'validation'}{$item}) {
21881:                     $changes{'validation'}{$item} = $selfenrollhash{'validation'}{$item};
21882:                 }
21883:             }
21884:         }
21885:     }
21886: 
21887:     my $putresult = &Apache::lonnet::put_dom('configuration',{'selfenrollment' => \%selfenrollhash},
21888:                                              $dom);
21889:     if ($putresult eq 'ok') {
21890:         if (keys(%changes) > 0) {
21891:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
21892:             $resulttext = &mt('Changes made:').'<ul>';
21893:             foreach my $key ('admin','default','validation') {
21894:                 if (ref($changes{$key}) eq 'HASH') {
21895:                     $resulttext .= '<li>'.$toplevel{$key}.'<ul>';
21896:                     if ($key eq 'validation') {
21897:                         foreach my $item (@{$itemsref}) {
21898:                             if (exists($changes{$key}{$item})) {
21899:                                 if ($item eq 'markup') {
21900:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
21901:                                                               '<br /><pre>'.$changes{$key}{$item}.'</pre>').'</li>';
21902:                                 } else {  
21903:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
21904:                                                               '<b>'.$changes{$key}{$item}.'</b>').'</li>';
21905:                                 }
21906:                             }
21907:                         }
21908:                     } else {
21909:                         foreach my $type (@types) {
21910:                             if ($type eq 'community') {
21911:                                 $roles{'1'} = &mt('Community personnel');
21912:                             } else {
21913:                                 $roles{'1'} = &mt('Course personnel');
21914:                             }
21915:                             if (ref($changes{$key}{$type}) eq 'ARRAY') {
21916:                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') {
21917:                                     if ($key eq 'admin') {
21918:                                         my @mgrdc = ();
21919:                                         if (ref($ordered{$key}) eq 'ARRAY') {
21920:                                             foreach my $item (@{$ordered{'admin'}}) {
21921:                                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') { 
21922:                                                     if ($selfenrollhash{$key}{$type}{$item} eq '0') {
21923:                                                         push(@mgrdc,$item);
21924:                                                     }
21925:                                                 }
21926:                                             }
21927:                                             if (@mgrdc) {
21928:                                                 $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
21929:                                             } else {
21930:                                                 delete($domdefaults{$type.'selfenrolladmdc'});
21931:                                             }
21932:                                         }
21933:                                     } else {
21934:                                         if (ref($ordered{$key}) eq 'ARRAY') {
21935:                                             foreach my $item (@{$ordered{$key}}) {
21936:                                                 if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
21937:                                                     $domdefaults{$type.'selfenroll'.$item} =
21938:                                                         $selfenrollhash{$key}{$type}{$item};
21939:                                                 }
21940:                                             }
21941:                                         }
21942:                                     }
21943:                                 }
21944:                                 $resulttext .= '<li>'.$titles{$type}.'<ul>';
21945:                                 foreach my $item (@{$ordered{$key}}) {
21946:                                     if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
21947:                                         $resulttext .= '<li>';
21948:                                         if ($key eq 'admin') {
21949:                                             $resulttext .= &mt('[_1] -- management by: [_2]',$titlesref->{$item},
21950:                                                                '<b>'.$roles{$selfenrollhash{'admin'}{$type}{$item}}.'</b>');
21951:                                         } else {
21952:                                             $resulttext .= &mt('[_1] set to: [_2]',$titlesref->{$item},
21953:                                                                '<b>'.$descs{$item}{$selfenrollhash{'default'}{$type}{$item}}.'</b>');
21954:                                         }
21955:                                         $resulttext .= '</li>';
21956:                                     }
21957:                                 }
21958:                                 $resulttext .= '</ul></li>';
21959:                             }
21960:                         }
21961:                         $resulttext .= '</ul></li>'; 
21962:                     }
21963:                 }
21964:             }
21965:             if ((exists($changes{'admin'})) || (exists($changes{'default'}))) {
21966:                 my $cachetime = 24*60*60;
21967:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
21968:                 if (ref($lastactref) eq 'HASH') {
21969:                     $lastactref->{'domdefaults'} = 1;
21970:                 }
21971:             }
21972:             $resulttext .= '</ul>';
21973:         } else {
21974:             $resulttext = &mt('No changes made to self-enrollment settings');
21975:         }
21976:     } else {
21977:         $resulttext = '<span class="LC_error">'.
21978:             &mt('An error occurred: [_1]',$putresult).'</span>';
21979:     }
21980:     return $resulttext;
21981: }
21982: 
21983: sub modify_wafproxy {
21984:     my ($dom,$action,$lastactref,%domconfig) = @_;
21985:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
21986:     my (%othercontrol,%canset,%values,%curralias,%currsaml,%currvalue,@warnings,
21987:         %wafproxy,%changes,%expirecache,%expiresaml);
21988:     foreach my $server (sort(keys(%servers))) {
21989:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
21990:         if ($serverhome eq $server) {
21991:             my $serverdom = &Apache::lonnet::host_domain($server);
21992:             if ($serverdom eq $dom) {
21993:                 $canset{$server} = 1;
21994:             }
21995:         }
21996:     }
21997:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
21998:         %{$values{$dom}} = ();
21999:         if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
22000:             %curralias = %{$domconfig{'wafproxy'}{'alias'}};
22001:         }
22002:         if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
22003:             %currsaml = %{$domconfig{'wafproxy'}{'saml'}};
22004:         }
22005:         foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
22006:             $currvalue{$item} = $domconfig{'wafproxy'}{$item};
22007:         }
22008:     }
22009:     my $output;
22010:     if (keys(%canset)) {
22011:         %{$wafproxy{'alias'}} = ();
22012:         %{$wafproxy{'saml'}} = ();
22013:         foreach my $key (sort(keys(%canset))) {
22014:             if ($env{'form.wafproxy_'.$dom}) {
22015:                 $wafproxy{'alias'}{$key} = $env{'form.wafproxy_alias_'.$key};
22016:                 $wafproxy{'alias'}{$key} =~ s/^\s+|\s+$//g;
22017:                 if ($wafproxy{'alias'}{$key} ne $curralias{$key}) {
22018:                     $changes{'alias'} = 1;
22019:                 }
22020:                 if ($env{'form.wafproxy_alias_saml_'.$key}) {
22021:                     $wafproxy{'saml'}{$key} = 1;
22022:                 }
22023:                 if ($wafproxy{'saml'}{$key} ne $currsaml{$key}) {
22024:                     $changes{'saml'} = 1;
22025:                 }
22026:             } else {
22027:                 $wafproxy{'alias'}{$key} = '';
22028:                 $wafproxy{'saml'}{$key} = '';
22029:                 if ($curralias{$key}) {
22030:                     $changes{'alias'} = 1;
22031:                 }
22032:                 if ($currsaml{$key}) {
22033:                     $changes{'saml'} = 1;
22034:                 }
22035:             }
22036:             if ($wafproxy{'alias'}{$key} eq '') {
22037:                 if ($curralias{$key}) {
22038:                     $expirecache{$key} = 1;
22039:                 }
22040:                 delete($wafproxy{'alias'}{$key});
22041:             }
22042:             if ($wafproxy{'saml'}{$key} eq '') {
22043:                 if ($currsaml{$key}) {
22044:                     $expiresaml{$key} = 1;
22045:                 }
22046:                 delete($wafproxy{'saml'}{$key});
22047:             }
22048:         }
22049:         unless (keys(%{$wafproxy{'alias'}})) {
22050:             delete($wafproxy{'alias'});
22051:         }
22052:         unless (keys(%{$wafproxy{'saml'}})) {
22053:             delete($wafproxy{'saml'});
22054:         }
22055:         # Localization for values in %warn occurs in &mt() calls separately.
22056:         my %warn = (
22057:                      trusted => 'trusted IP range(s)',
22058:                      vpnint => 'internal IP range(s) for VPN sessions(s)',
22059:                      vpnext => 'IP range(s) for backend WAF connections',
22060:                    );
22061:         foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
22062:             my $possible = $env{'form.wafproxy_'.$item};
22063:             $possible =~ s/^\s+|\s+$//g;
22064:             if ($possible ne '') {
22065:                 if ($item eq 'remoteip') {
22066:                     if ($possible =~ /^[mhn]$/) {
22067:                         $wafproxy{$item} = $possible;
22068:                     }
22069:                 } elsif ($item eq 'ipheader') {
22070:                     if ($wafproxy{'remoteip'} eq 'h') {
22071:                         $wafproxy{$item} = $possible;
22072:                     }
22073:                 } elsif ($item eq 'sslopt') {
22074:                     if ($possible =~ /^0|1$/) {
22075:                         $wafproxy{$item} = $possible;
22076:                     }
22077:                 } else {
22078:                     my (@ok,$count);
22079:                     if (($item eq 'vpnint') || ($item eq 'vpnext')) {
22080:                         unless ($env{'form.wafproxy_vpnaccess'}) {
22081:                             $possible = '';
22082:                         }
22083:                     } elsif ($item eq 'trusted') {
22084:                         unless ($wafproxy{'remoteip'} eq 'h') {
22085:                             $possible = '';
22086:                         }
22087:                     }
22088:                     unless ($possible eq '') {
22089:                         $possible =~ s/[\r\n]+/\s/g;
22090:                         $possible =~ s/\s*-\s*/-/g;
22091:                         $possible =~ s/\s+/,/g;
22092:                         $possible =~ s/,+/,/g;
22093:                     }
22094:                     $count = 0;
22095:                     if ($possible ne '') {
22096:                         foreach my $poss (split(/\,/,$possible)) {
22097:                             $count ++;
22098:                             $poss = &validate_ip_pattern($poss);
22099:                             if ($poss ne '') {
22100:                                 push(@ok,$poss);
22101:                             }
22102:                         }
22103:                         my $diff = $count - scalar(@ok);
22104:                         if ($diff) {
22105:                             push(@warnings,'<li>'.
22106:                                  &mt('[quant,_1,IP] invalid and excluded from saved value for [_2]',
22107:                                      $diff,$warn{$item}).
22108:                                  '</li>');
22109:                         }
22110:                         if (@ok) {
22111:                             my @cidr_list;
22112:                             foreach my $item (@ok) {
22113:                                 @cidr_list = &Net::CIDR::cidradd($item,@cidr_list);
22114:                             }
22115:                             $wafproxy{$item} = join(',',@cidr_list);
22116:                         }
22117:                     }
22118:                 }
22119:                 if ($wafproxy{$item} ne $currvalue{$item}) {
22120:                     $changes{$item} = 1;
22121:                 }
22122:             } elsif ($currvalue{$item}) {
22123:                 $changes{$item} = 1;
22124:             } 
22125:         }
22126:     } else {
22127:         if (keys(%curralias)) {
22128:             $changes{'alias'} = 1;
22129:         }
22130:         if (keys(%currsaml)) {
22131:             $changes{'saml'} = 1;
22132:         } 
22133:         if (keys(%currvalue)) {
22134:             foreach my $key (keys(%currvalue)) {
22135:                 $changes{$key} = 1;
22136:             }
22137:         }
22138:     }
22139:     if (keys(%changes)) {
22140:         my %defaultshash = (
22141:                               wafproxy => \%wafproxy,
22142:                            ); 
22143:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
22144:                                                  $dom);
22145:         if ($putresult eq 'ok') {
22146:             my $cachetime = 24*60*60;
22147:             my (%domdefaults,$updatedomdefs);
22148:             foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
22149:                 if ($changes{$item}) {
22150:                     unless ($updatedomdefs) {
22151:                         %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
22152:                         $updatedomdefs = 1;
22153:                     }
22154:                     if ($wafproxy{$item}) {
22155:                         $domdefaults{'waf_'.$item} = $wafproxy{$item};
22156:                     } elsif (exists($domdefaults{'waf_'.$item})) {
22157:                         delete($domdefaults{'waf_'.$item});
22158:                     } 
22159:                 }
22160:             }
22161:             if ($updatedomdefs) {
22162:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
22163:                 if (ref($lastactref) eq 'HASH') {
22164:                     $lastactref->{'domdefaults'} = 1;
22165:                 }
22166:             }
22167:             if ((exists($wafproxy{'alias'})) || (keys(%expirecache))) {
22168:                 my %updates = %expirecache;
22169:                 foreach my $key (keys(%expirecache)) {
22170:                     &Apache::lonnet::devalidate_cache_new('proxyalias',$key);
22171:                 }
22172:                 if (ref($wafproxy{'alias'}) eq 'HASH') {
22173:                     my $cachetime = 24*60*60;
22174:                     foreach my $key (keys(%{$wafproxy{'alias'}})) {
22175:                         $updates{$key} = 1;
22176:                         &Apache::lonnet::do_cache_new('proxyalias',$key,$wafproxy{'alias'}{$key},
22177:                                                       $cachetime);
22178:                     }
22179:                 }
22180:                 if (ref($lastactref) eq 'HASH') {
22181:                     $lastactref->{'proxyalias'} = \%updates;
22182:                 }
22183:             }
22184:             if ((exists($wafproxy{'saml'})) || (keys(%expiresaml))) {
22185:                 my %samlupdates = %expiresaml;
22186:                 foreach my $key (keys(%expiresaml)) {
22187:                     &Apache::lonnet::devalidate_cache_new('proxysaml',$key);
22188:                 }
22189:                 if (ref($wafproxy{'saml'}) eq 'HASH') {
22190:                     my $cachetime = 24*60*60;
22191:                     foreach my $key (keys(%{$wafproxy{'saml'}})) {
22192:                         $samlupdates{$key} = 1;
22193:                         &Apache::lonnet::do_cache_new('proxysaml',$key,$wafproxy{'saml'}{$key},
22194:                                                       $cachetime);
22195:                     }
22196:                 }
22197:                 if (ref($lastactref) eq 'HASH') {
22198:                     $lastactref->{'proxysaml'} = \%samlupdates;
22199:                 }
22200:             }
22201:             $output = &mt('Changes were made to Web Application Firewall/Reverse Proxy').'<ul>';
22202:             foreach my $item ('alias','saml','remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
22203:                 if ($changes{$item}) {
22204:                     if ($item eq 'alias') {
22205:                         my $numaliased = 0;
22206:                         if (ref($wafproxy{'alias'}) eq 'HASH') {
22207:                             my $shown;
22208:                             if (keys(%{$wafproxy{'alias'}})) {
22209:                                 foreach my $server (sort(keys(%{$wafproxy{'alias'}}))) {
22210:                                     $shown .= '<li>'.&mt('[_1] aliased by [_2]',
22211:                                                          &Apache::lonnet::hostname($server),
22212:                                                          $wafproxy{'alias'}{$server}).'</li>';
22213:                                     $numaliased ++;
22214:                                 }
22215:                                 if ($numaliased) {
22216:                                     $output .= '<li>'.&mt('Aliases for hostnames set to: [_1]',
22217:                                                           '<ul>'.$shown.'</ul>').'</li>';
22218:                                 }
22219:                             }
22220:                         }
22221:                         unless ($numaliased) {
22222:                             $output .= '<li>'.&mt('Aliases deleted for hostnames').'</li>';
22223:                         }
22224:                     } elsif ($item eq 'saml') {
22225:                         my $shown; 
22226:                         if (ref($wafproxy{'saml'}) eq 'HASH') {
22227:                             if (keys(%{$wafproxy{'saml'}})) {
22228:                                 $shown = join(', ',sort(keys(%{$wafproxy{'saml'}})));
22229:                             }
22230:                         }
22231:                         if ($shown) {
22232:                             $output .= '<li>'.&mt('Alias used by SSO Auth for: [_1]',
22233:                                                   $shown).'</li>';
22234:                         } else {
22235:                             $output .= '<li>'.&mt('No alias used for SSO Auth').'</li>';
22236:                         }
22237:                     } else {
22238:                         if ($item eq 'remoteip') {
22239:                             my %ip_methods = &remoteip_methods();
22240:                             if ($wafproxy{$item} =~ /^[mh]$/) {
22241:                                 $output .= '<li>'.&mt("Method for determining user's IP set to: [_1]",
22242:                                                       $ip_methods{$wafproxy{$item}}).'</li>';
22243:                             } else {
22244:                                 if (($env{'form.wafproxy_'.$dom}) && (ref($wafproxy{'alias'}) eq 'HASH')) {
22245:                                     $output .= '<li>'.&mt("No method in use to get user's real IP (will report IP used by WAF).").
22246:                                                '</li>';
22247:                                 } else {
22248:                                     $output .= '<li>'.&mt('WAF/Reverse Proxy not in use').'</li>';
22249:                                 }
22250:                             }
22251:                         } elsif ($item eq 'ipheader') {
22252:                             if ($wafproxy{$item}) {
22253:                                 $output .= '<li>'.&mt('Request header with remote IP set to: [_1]',
22254:                                                       $wafproxy{$item}).'</li>';
22255:                             } else {
22256:                                 $output .= '<li>'.&mt('Request header with remote IP deleted').'</li>';
22257:                             }
22258:                         } elsif ($item eq 'trusted') {
22259:                             if ($wafproxy{$item}) {
22260:                                 $output .= '<li>'.&mt('Trusted IP range(s) set to: [_1]',
22261:                                                       $wafproxy{$item}).'</li>';
22262:                             } else {
22263:                                 $output .= '<li>'.&mt('Trusted IP range(s) deleted').'</li>';
22264:                             }
22265:                         } elsif ($item eq 'vpnint') {
22266:                             if ($wafproxy{$item}) {
22267:                                 $output .= '<li>'.&mt('Internal IP Range(s) for VPN sessions set to: [_1]',
22268:                                                        $wafproxy{$item}).'</li>';
22269:                             } else {
22270:                                 $output .= '<li>'.&mt('Internal IP Range(s) for VPN sessions deleted').'</li>';
22271:                             }
22272:                         } elsif ($item eq 'vpnext') {
22273:                             if ($wafproxy{$item}) {
22274:                                 $output .= '<li>'.&mt('IP Range(s) for backend WAF connections set to: [_1]',
22275:                                                        $wafproxy{$item}).'</li>';
22276:                             } else {
22277:                                 $output .= '<li>'.&mt('IP Range(s) for backend WAF connections deleted').'</li>';
22278:                             }
22279:                         } elsif ($item eq 'sslopt') {
22280:                             if ($wafproxy{$item}) {
22281:                                 $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>';
22282:                             } else {
22283:                                 $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>';
22284:                             }
22285:                         }
22286:                     }
22287:                 }
22288:             }
22289:         } else {
22290:             $output = '<span class="LC_error">'.
22291:                       &mt('An error occurred: [_1]',$putresult).'</span>';
22292:         }
22293:     } elsif (keys(%canset)) {
22294:         $output = &mt('No changes made to Web Application Firewall/Reverse Proxy settings');
22295:     }
22296:     if (@warnings) {
22297:         $output .= '<br />'.&mt('Warnings:').'<ul>'.
22298:                        join("\n",@warnings).'</ul>';
22299:     }
22300:     return $output;
22301: }
22302: 
22303: sub validate_ip_pattern {
22304:     my ($pattern) = @_;
22305:     if ($pattern =~ /^([^-]+)\-([^-]+)$/) {
22306:         my ($start,$end) = ($1,$2);
22307:         if ((&Net::CIDR::cidrvalidate($start)) && (&Net::CIDR::cidrvalidate($end))) {
22308:             if (($start !~ m{/}) && ($end !~ m{/})) {
22309:                 return $start.'-'.$end;
22310:             }
22311:         }
22312:     } elsif ($pattern ne '') {
22313:         $pattern = &Net::CIDR::cidrvalidate($pattern);
22314:         if ($pattern ne '') {
22315:             return $pattern;
22316:         }
22317:     }
22318:     return;
22319: }
22320: 
22321: sub modify_usersessions {
22322:     my ($dom,$lastactref,%domconfig) = @_;
22323:     my @hostingtypes = ('version','excludedomain','includedomain');
22324:     my @offloadtypes = ('primary','default');
22325:     my %types = (
22326:                   remote => \@hostingtypes,
22327:                   hosted => \@hostingtypes,
22328:                   spares => \@offloadtypes,
22329:                 );
22330:     my @prefixes = ('remote','hosted','spares');
22331:     my @lcversions = &Apache::lonnet::all_loncaparevs();
22332:     my (%by_ip,%by_location,@intdoms,@instdoms);
22333:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
22334:     my @locations = sort(keys(%by_location));
22335:     my (%defaultshash,%changes);
22336:     foreach my $prefix (@prefixes) {
22337:         $defaultshash{'usersessions'}{$prefix} = {};
22338:     }
22339:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
22340:     my $resulttext;
22341:     my %iphost = &Apache::lonnet::get_iphost();
22342:     foreach my $prefix (@prefixes) {
22343:         next if ($prefix eq 'spares');
22344:         foreach my $type (@{$types{$prefix}}) {
22345:             my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
22346:             if ($type eq 'version') {
22347:                 my $value = $env{'form.'.$prefix.'_'.$type};
22348:                 my $okvalue;
22349:                 if ($value ne '') {
22350:                     if (grep(/^\Q$value\E$/,@lcversions)) {
22351:                         $okvalue = $value;
22352:                     }
22353:                 }
22354:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
22355:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
22356:                         if ($domconfig{'usersessions'}{$prefix}{$type} ne '') {
22357:                             if ($inuse == 0) {
22358:                                 $changes{$prefix}{$type} = 1;
22359:                             } else {
22360:                                 if ($okvalue ne $domconfig{'usersessions'}{$prefix}{$type}) {
22361:                                     $changes{$prefix}{$type} = 1;
22362:                                 }
22363:                                 if ($okvalue ne '') {
22364:                                     $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
22365:                                 } 
22366:                             }
22367:                         } else {
22368:                             if (($inuse == 1) && ($okvalue ne '')) {
22369:                                 $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
22370:                                 $changes{$prefix}{$type} = 1;
22371:                             }
22372:                         }
22373:                     } else {
22374:                         if (($inuse == 1) && ($okvalue ne '')) {
22375:                             $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
22376:                             $changes{$prefix}{$type} = 1;
22377:                         }
22378:                     }
22379:                 } else {
22380:                     if (($inuse == 1) && ($okvalue ne '')) {
22381:                         $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
22382:                         $changes{$prefix}{$type} = 1;
22383:                     }
22384:                 }
22385:             } else {
22386:                 my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
22387:                 my @okvals;
22388:                 foreach my $val (@vals) {
22389:                     if ($val =~ /:/) {
22390:                         my @items = split(/:/,$val);
22391:                         foreach my $item (@items) {
22392:                             if (ref($by_location{$item}) eq 'ARRAY') {
22393:                                 push(@okvals,$item);
22394:                             }
22395:                         }
22396:                     } else {
22397:                         if (ref($by_location{$val}) eq 'ARRAY') {
22398:                             push(@okvals,$val);
22399:                         }
22400:                     }
22401:                 }
22402:                 @okvals = sort(@okvals);
22403:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
22404:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
22405:                         if (ref($domconfig{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
22406:                             if ($inuse == 0) {
22407:                                 $changes{$prefix}{$type} = 1; 
22408:                             } else {
22409:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
22410:                                 my @changed = &Apache::loncommon::compare_arrays($domconfig{'usersessions'}{$prefix}{$type},$defaultshash{'usersessions'}{$prefix}{$type});
22411:                                 if (@changed > 0) {
22412:                                     $changes{$prefix}{$type} = 1;
22413:                                 }
22414:                             }
22415:                         } else {
22416:                             if ($inuse == 1) {
22417:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
22418:                                 $changes{$prefix}{$type} = 1;
22419:                             }
22420:                         } 
22421:                     } else {
22422:                         if ($inuse == 1) {
22423:                             $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
22424:                             $changes{$prefix}{$type} = 1;
22425:                         }
22426:                     }
22427:                 } else {
22428:                     if ($inuse == 1) {
22429:                         $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
22430:                         $changes{$prefix}{$type} = 1;
22431:                     }
22432:                 }
22433:             }
22434:         }
22435:     }
22436: 
22437:     my @alldoms = &Apache::lonnet::all_domains();
22438:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
22439:     my %spareid = &current_offloads_to($dom,$domconfig{'usersessions'},\%servers);
22440:     my $savespares;
22441: 
22442:     foreach my $lonhost (sort(keys(%servers))) {
22443:         my $serverhomeID =
22444:             &Apache::lonnet::get_server_homeID($servers{$lonhost});
22445:         my $serverhostname = &Apache::lonnet::hostname($lonhost);
22446:         $defaultshash{'usersessions'}{'spares'}{$lonhost} = {};
22447:         my %spareschg;
22448:         foreach my $type (@{$types{'spares'}}) {
22449:             my @okspares;
22450:             my @checked = &Apache::loncommon::get_env_multiple('form.spare_'.$type.'_'.$lonhost);
22451:             foreach my $server (@checked) {
22452:                 if (&Apache::lonnet::hostname($server) ne '') {
22453:                     unless (&Apache::lonnet::hostname($server) eq $serverhostname) {
22454:                         unless (grep(/^\Q$server\E$/,@okspares)) {
22455:                             push(@okspares,$server);
22456:                         }
22457:                     }
22458:                 }
22459:             }
22460:             my $new = $env{'form.newspare_'.$type.'_'.$lonhost};
22461:             my $newspare;
22462:             if (($new ne '') && (&Apache::lonnet::hostname($new))) {
22463:                 unless (&Apache::lonnet::hostname($new) eq $serverhostname) {
22464:                     $newspare = $new;
22465:                 }
22466:             }
22467:             my @spares;
22468:             if (($newspare ne '') && (!grep(/^\Q$newspare\E$/,@okspares))) {
22469:                 @spares = sort(@okspares,$newspare);
22470:             } else {
22471:                 @spares = sort(@okspares);
22472:             }
22473:             $defaultshash{'usersessions'}{'spares'}{$lonhost}{$type} = \@spares;
22474:             if (ref($spareid{$lonhost}) eq 'HASH') {
22475:                 if (ref($spareid{$lonhost}{$type}) eq 'ARRAY') {
22476:                     my @diffs = &Apache::loncommon::compare_arrays($spareid{$lonhost}{$type},\@spares);
22477:                     if (@diffs > 0) {
22478:                         $spareschg{$type} = 1;
22479:                     }
22480:                 }
22481:             }
22482:         }
22483:         if (keys(%spareschg) > 0) {
22484:             $changes{'spares'}{$lonhost} = \%spareschg;
22485:         }
22486:     }
22487:     $defaultshash{'usersessions'}{'offloadnow'} = {};
22488:     $defaultshash{'usersessions'}{'offloadoth'} = {};
22489:     my @offloadnow = &Apache::loncommon::get_env_multiple('form.offloadnow');
22490:     my @okoffload;
22491:     if (@offloadnow) {
22492:         foreach my $server (@offloadnow) {
22493:             if (&Apache::lonnet::hostname($server) ne '') {
22494:                 unless (grep(/^\Q$server\E$/,@okoffload)) {
22495:                     push(@okoffload,$server);
22496:                 }
22497:             }
22498:         }
22499:         if (@okoffload) {
22500:             foreach my $lonhost (@okoffload) {
22501:                 $defaultshash{'usersessions'}{'offloadnow'}{$lonhost} = 1;
22502:             }
22503:         }
22504:     }
22505:     my @offloadoth = &Apache::loncommon::get_env_multiple('form.offloadoth');
22506:     my @okoffloadoth;
22507:     if (@offloadoth) {
22508:         foreach my $server (@offloadoth) {
22509:             if (&Apache::lonnet::hostname($server) ne '') {
22510:                 unless (grep(/^\Q$server\E$/,@okoffloadoth)) {
22511:                     push(@okoffloadoth,$server);
22512:                 }
22513:             }
22514:         }
22515:         if (@okoffloadoth) {
22516:             foreach my $lonhost (@okoffloadoth) {
22517:                 $defaultshash{'usersessions'}{'offloadoth'}{$lonhost} = 1;
22518:             }
22519:         }
22520:     }
22521:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
22522:         if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
22523:             if (ref($changes{'spares'}) eq 'HASH') {
22524:                 if (keys(%{$changes{'spares'}}) > 0) {
22525:                     $savespares = 1;
22526:                 }
22527:             }
22528:         } else {
22529:             $savespares = 1;
22530:         }
22531:         foreach my $offload ('offloadnow','offloadoth') {
22532:             if (ref($domconfig{'usersessions'}{$offload}) eq 'HASH') {
22533:                 foreach my $lonhost (keys(%{$domconfig{'usersessions'}{$offload}})) {
22534:                     unless ($defaultshash{'usersessions'}{$offload}{$lonhost}) {
22535:                         $changes{$offload} = 1;
22536:                         last;
22537:                     }
22538:                 }
22539:                 unless ($changes{$offload}) {
22540:                     foreach my $lonhost (keys(%{$defaultshash{'usersessions'}{$offload}})) {
22541:                         unless ($domconfig{'usersessions'}{$offload}{$lonhost}) {
22542:                             $changes{$offload} = 1;
22543:                             last;
22544:                         }
22545:                     }
22546:                 }
22547:             } else {
22548:                 if (($offload eq 'offloadnow') && (@okoffload)) {
22549:                      $changes{'offloadnow'} = 1;
22550:                 }
22551:                 if (($offload eq 'offloadoth') && (@okoffloadoth)) {
22552:                     $changes{'offloadoth'} = 1;
22553:                 }
22554:             } 
22555:         }
22556:     } else {
22557:         if (@okoffload) {
22558:             $changes{'offloadnow'} = 1;
22559:         }
22560:         if (@okoffloadoth) {
22561:             $changes{'offloadoth'} = 1;
22562:         }
22563:     }
22564:     my $nochgmsg = &mt('No changes made to settings for user session hosting/offloading.');
22565:     if ((keys(%changes) > 0) || ($savespares)) {
22566:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
22567:                                                  $dom);
22568:         if ($putresult eq 'ok') {
22569:             if (ref($defaultshash{'usersessions'}) eq 'HASH') {
22570:                 if (ref($defaultshash{'usersessions'}{'remote'}) eq 'HASH') {
22571:                     $domdefaults{'remotesessions'} = $defaultshash{'usersessions'}{'remote'};
22572:                 }
22573:                 if (ref($defaultshash{'usersessions'}{'hosted'}) eq 'HASH') {
22574:                     $domdefaults{'hostedsessions'} = $defaultshash{'usersessions'}{'hosted'};
22575:                 }
22576:                 if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
22577:                     $domdefaults{'offloadnow'} = $defaultshash{'usersessions'}{'offloadnow'};
22578:                 }
22579:                 if (ref($defaultshash{'usersessions'}{'offloadoth'}) eq 'HASH') {
22580:                     $domdefaults{'offloadoth'} = $defaultshash{'usersessions'}{'offloadoth'};
22581:                 }
22582:             }
22583:             my $cachetime = 24*60*60;
22584:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
22585:             &Apache::lonnet::do_cache_new('usersessions',$dom,$defaultshash{'usersessions'},3600);
22586:             if (ref($lastactref) eq 'HASH') {
22587:                 $lastactref->{'domdefaults'} = 1;
22588:                 $lastactref->{'usersessions'} = 1;
22589:             }
22590:             if (keys(%changes) > 0) {
22591:                 my %lt = &usersession_titles();
22592:                 $resulttext = &mt('Changes made:').'<ul>';
22593:                 foreach my $prefix (@prefixes) {
22594:                     if (ref($changes{$prefix}) eq 'HASH') {
22595:                         $resulttext .= '<li>'.$lt{$prefix}.'<ul>';
22596:                         if ($prefix eq 'spares') {
22597:                             if (ref($changes{$prefix}) eq 'HASH') {
22598:                                 foreach my $lonhost (sort(keys(%{$changes{$prefix}}))) {
22599:                                     $resulttext .= '<li><b>'.$lonhost.'</b> ';
22600:                                     my $lonhostdom = &Apache::lonnet::host_domain($lonhost);
22601:                                     my $cachekey = &escape('spares').':'.&escape($lonhostdom);
22602:                                     &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
22603:                                     if (ref($changes{$prefix}{$lonhost}) eq 'HASH') {
22604:                                         foreach my $type (@{$types{$prefix}}) {
22605:                                             if ($changes{$prefix}{$lonhost}{$type}) {
22606:                                                 my $offloadto = &mt('None');
22607:                                                 if (ref($defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}) eq 'ARRAY') {
22608:                                                     if (@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}} > 0) {   
22609:                                                         $offloadto = join(', ',@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}});
22610:                                                     }
22611:                                                 }
22612:                                                 $resulttext .= &mt('[_1] set to: [_2].','<i>'.$lt{$type}.'</i>',$offloadto).('&nbsp;'x3);
22613:                                             }
22614:                                         }
22615:                                     }
22616:                                     $resulttext .= '</li>';
22617:                                 }
22618:                             }
22619:                         } else {
22620:                             foreach my $type (@{$types{$prefix}}) {
22621:                                 if (defined($changes{$prefix}{$type})) {
22622:                                     my ($newvalue,$notinuse);
22623:                                     if (ref($defaultshash{'usersessions'}) eq 'HASH') {
22624:                                         if (ref($defaultshash{'usersessions'}{$prefix})) {
22625:                                             if ($type eq 'version') {
22626:                                                 $newvalue = $defaultshash{'usersessions'}{$prefix}{$type};
22627:                                             } else {
22628:                                                 if (ref($defaultshash{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
22629:                                                     if (@{$defaultshash{'usersessions'}{$prefix}{$type}} > 0) {
22630:                                                         $newvalue = join(', ',@{$defaultshash{'usersessions'}{$prefix}{$type}});
22631:                                                     }
22632:                                                 } else {
22633:                                                     $notinuse = 1;
22634:                                                 }
22635:                                             }
22636:                                         }
22637:                                     }
22638:                                     if ($newvalue eq '') {
22639:                                         if ($type eq 'version') {
22640:                                             $resulttext .= '<li>'.&mt('[_1] set to: off',$lt{$type}).'</li>';
22641:                                         } elsif ($notinuse) {
22642:                                             $resulttext .= '<li>'.&mt('[_1] set to: not in use',$lt{$type}).'</li>';
22643:                                         } else {
22644:                                             $resulttext .= '<li>'.&mt('[_1] set to: none',$lt{$type}).'</li>';
22645:                                         }
22646:                                     } else {
22647:                                         if ($type eq 'version') {
22648:                                             $newvalue .= ' '.&mt('(or later)');
22649:                                         }
22650:                                         $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$lt{$type},$newvalue).'</li>';
22651:                                     }
22652:                                 }
22653:                             }
22654:                         }
22655:                         $resulttext .= '</ul>';
22656:                     }
22657:                 }
22658:                 if ($changes{'offloadnow'}) {
22659:                     if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
22660:                         if (keys(%{$defaultshash{'usersessions'}{'offloadnow'}}) > 0) {
22661:                             $resulttext .= '<li>'.&mt('Switch any active user on next access, for server(s):').'<ul>';
22662:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadnow'}}))) {
22663:                                 $resulttext .= '<li>'.$lonhost.'</li>';
22664:                             }
22665:                             $resulttext .= '</ul>';
22666:                         } else {
22667:                             $resulttext .= '<li>'.&mt('No servers now set to switch any active user on next access.');
22668:                         }
22669:                     } else {
22670:                         $resulttext .= '<li>'.&mt('No servers now set to switch any active user on next access.').'</li>';
22671:                     }
22672:                 }
22673:                 if ($changes{'offloadoth'}) {
22674:                     if (ref($defaultshash{'usersessions'}{'offloadoth'}) eq 'HASH') {
22675:                         if (keys(%{$defaultshash{'usersessions'}{'offloadoth'}}) > 0) {
22676:                             $resulttext .= '<li>'.&mt('Switch other institutions on next access, for server(s):').'<ul>';
22677:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadoth'}}))) {
22678:                                 $resulttext .= '<li>'.$lonhost.'</li>';
22679:                             }
22680:                             $resulttext .= '</ul>';
22681:                         } else {
22682:                             $resulttext .= '<li>'.&mt('No servers now set to switch other institutions on next access.');
22683:                         }
22684:                     } else {
22685:                         $resulttext .= '<li>'.&mt('No servers now set to switch other institutions on next access.').'</li>';
22686:                     }
22687:                 }
22688:                 $resulttext .= '</ul>';
22689:             } else {
22690:                 $resulttext = $nochgmsg;
22691:             }
22692:         } else {
22693:             $resulttext = '<span class="LC_error">'.
22694:                           &mt('An error occurred: [_1]',$putresult).'</span>';
22695:         }
22696:     } else {
22697:         $resulttext = $nochgmsg;
22698:     }
22699:     return $resulttext;
22700: }
22701: 
22702: sub modify_ssl {
22703:     my ($dom,$lastactref,%domconfig) = @_;
22704:     my (%by_ip,%by_location,@intdoms,@instdoms);
22705:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
22706:     my @locations = sort(keys(%by_location));
22707:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
22708:     my (%defaultshash,%changes);
22709:     my $action = 'ssl';
22710:     my @prefixes = ('connto','connfrom','replication');
22711:     foreach my $prefix (@prefixes) {
22712:         $defaultshash{$action}{$prefix} = {};
22713:     }
22714:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
22715:     my $resulttext;
22716:     my %iphost = &Apache::lonnet::get_iphost();
22717:     my @reptypes = ('certreq','nocertreq');
22718:     my @connecttypes = ('dom','intdom','other');
22719:     my %types = (
22720:                   connto      => \@connecttypes,
22721:                   connfrom    => \@connecttypes,
22722:                   replication => \@reptypes,
22723:                 );
22724:     foreach my $prefix (sort(keys(%types))) {
22725:         foreach my $type (@{$types{$prefix}}) {
22726:             if (($prefix eq 'connto') || ($prefix eq 'connfrom')) {
22727:                 my $value = 'yes';
22728:                 if ($env{'form.'.$prefix.'_'.$type} =~ /^(no|req)$/) {
22729:                     $value = $env{'form.'.$prefix.'_'.$type};
22730:                 }
22731:                 if (ref($domconfig{$action}) eq 'HASH') {
22732:                     if (ref($domconfig{$action}{$prefix}) eq 'HASH') {
22733:                         if ($domconfig{$action}{$prefix}{$type} ne '') {
22734:                             if ($value ne $domconfig{$action}{$prefix}{$type}) {
22735:                                 $changes{$prefix}{$type} = 1;
22736:                             }
22737:                             $defaultshash{$action}{$prefix}{$type} = $value;
22738:                         } else {
22739:                             $defaultshash{$action}{$prefix}{$type} = $value;
22740:                             $changes{$prefix}{$type} = 1;
22741:                         }
22742:                     } else {
22743:                         $defaultshash{$action}{$prefix}{$type} = $value;
22744:                         $changes{$prefix}{$type} = 1;
22745:                     }
22746:                 } else {
22747:                     $defaultshash{$action}{$prefix}{$type} = $value;
22748:                     $changes{$prefix}{$type} = 1;
22749:                 }
22750:                 if (($type eq 'dom') && (keys(%servers) == 1)) {
22751:                     delete($changes{$prefix}{$type});
22752:                 } elsif (($type eq 'intdom') && (@instdoms == 1)) {
22753:                     delete($changes{$prefix}{$type});
22754:                 } elsif (($type eq 'other') && (keys(%by_location) == 0)) { 
22755:                     delete($changes{$prefix}{$type});
22756:                 }
22757:             } elsif ($prefix eq 'replication') {
22758:                 if (@locations > 0) {
22759:                     my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
22760:                     my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
22761:                     my @okvals;
22762:                     foreach my $val (@vals) {
22763:                         if ($val =~ /:/) {
22764:                             my @items = split(/:/,$val);
22765:                             foreach my $item (@items) {
22766:                                 if (ref($by_location{$item}) eq 'ARRAY') {
22767:                                     push(@okvals,$item);
22768:                                 }
22769:                             }
22770:                         } else {
22771:                             if (ref($by_location{$val}) eq 'ARRAY') {
22772:                                 push(@okvals,$val);
22773:                             }
22774:                         }
22775:                     }
22776:                     @okvals = sort(@okvals);
22777:                     if (ref($domconfig{$action}) eq 'HASH') {
22778:                         if (ref($domconfig{$action}{$prefix}) eq 'HASH') {
22779:                             if (ref($domconfig{$action}{$prefix}{$type}) eq 'ARRAY') {
22780:                                 if ($inuse == 0) {
22781:                                     $changes{$prefix}{$type} = 1;
22782:                                 } else {
22783:                                     $defaultshash{$action}{$prefix}{$type} = \@okvals;
22784:                                     my @changed = &Apache::loncommon::compare_arrays($domconfig{$action}{$prefix}{$type},$defaultshash{$action}{$prefix}{$type});
22785:                                     if (@changed > 0) {
22786:                                         $changes{$prefix}{$type} = 1;
22787:                                     }
22788:                                 }
22789:                             } else {
22790:                                 if ($inuse == 1) {
22791:                                     $defaultshash{$action}{$prefix}{$type} = \@okvals;
22792:                                     $changes{$prefix}{$type} = 1;
22793:                                 }
22794:                             }
22795:                         } else {
22796:                             if ($inuse == 1) {
22797:                                 $defaultshash{$action}{$prefix}{$type} = \@okvals;
22798:                                 $changes{$prefix}{$type} = 1;
22799:                             }
22800:                         }
22801:                     } else {
22802:                         if ($inuse == 1) {
22803:                             $defaultshash{$action}{$prefix}{$type} = \@okvals;
22804:                             $changes{$prefix}{$type} = 1;
22805:                         }
22806:                     }
22807:                 }
22808:             }
22809:         }
22810:     }
22811:     if (keys(%changes)) {
22812:         foreach my $prefix (keys(%changes)) {
22813:             if (ref($changes{$prefix}) eq 'HASH') {
22814:                 if (scalar(keys(%{$changes{$prefix}})) == 0) {
22815:                     delete($changes{$prefix});
22816:                 }
22817:             } else {
22818:                 delete($changes{$prefix});
22819:             }
22820:         }
22821:     }
22822:     my $nochgmsg = &mt('No changes made to LON-CAPA SSL settings');
22823:     if (keys(%changes) > 0) {
22824:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
22825:                                                  $dom);
22826:         if ($putresult eq 'ok') {
22827:             if (ref($defaultshash{$action}) eq 'HASH') {
22828:                 if (ref($defaultshash{$action}{'replication'}) eq 'HASH') {
22829:                     $domdefaults{'replication'} = $defaultshash{$action}{'replication'};
22830:                 }
22831:                 if (ref($defaultshash{$action}{'connto'}) eq 'HASH') {
22832:                     $domdefaults{'connto'} = $defaultshash{$action}{'connto'};
22833:                 }
22834:                 if (ref($defaultshash{$action}{'connfrom'}) eq 'HASH') {
22835:                     $domdefaults{'connfrom'} = $defaultshash{$action}{'connfrom'};
22836:                 }
22837:             }
22838:             my $cachetime = 24*60*60;
22839:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
22840:             if (ref($lastactref) eq 'HASH') {
22841:                 $lastactref->{'domdefaults'} = 1;
22842:             }
22843:             if (keys(%changes) > 0) {
22844:                 my %titles = &ssl_titles();
22845:                 $resulttext = &mt('Changes made:').'<ul>';
22846:                 foreach my $prefix (@prefixes) {
22847:                     if (ref($changes{$prefix}) eq 'HASH') {
22848:                         $resulttext .= '<li>'.$titles{$prefix}.'<ul>';
22849:                         foreach my $type (@{$types{$prefix}}) {
22850:                             if (defined($changes{$prefix}{$type})) {
22851:                                 my ($newvalue,$notinuse);
22852:                                 if (ref($defaultshash{$action}) eq 'HASH') {
22853:                                     if (ref($defaultshash{$action}{$prefix})) {
22854:                                         if (($prefix eq 'connto') || ($prefix eq 'connfrom')) {
22855:                                             $newvalue = $titles{$defaultshash{$action}{$prefix}{$type}};
22856:                                         } else {
22857:                                             if (ref($defaultshash{$action}{$prefix}{$type}) eq 'ARRAY') {
22858:                                                 if (@{$defaultshash{$action}{$prefix}{$type}} > 0) {
22859:                                                     $newvalue = join(', ',@{$defaultshash{$action}{$prefix}{$type}});
22860:                                                 }
22861:                                             } else {
22862:                                                 $notinuse = 1;
22863:                                             }
22864:                                         }
22865:                                     }
22866:                                     if ($notinuse) {
22867:                                         $resulttext .= '<li>'.&mt('[_1] set to: not in use',$titles{$type}).'</li>';
22868:                                     } elsif ($newvalue eq '') {
22869:                                         $resulttext .= '<li>'.&mt('[_1] set to: none',$titles{$type}).'</li>';
22870:                                     } else {
22871:                                         $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$titles{$type},$newvalue).'</li>';
22872:                                     }
22873:                                 }
22874:                             }
22875:                         }
22876:                         $resulttext .= '</ul>';
22877:                     }
22878:                 }
22879:             } else {
22880:                 $resulttext = $nochgmsg;
22881:             }
22882:         } else {
22883:             $resulttext = '<span class="LC_error">'.
22884:                           &mt('An error occurred: [_1]',$putresult).'</span>';
22885:         }
22886:     } else {
22887:         $resulttext = $nochgmsg;
22888:     }
22889:     return $resulttext;
22890: }
22891: 
22892: sub modify_trust {
22893:     my ($dom,$lastactref,%domconfig) = @_;
22894:     my (%by_ip,%by_location,@intdoms,@instdoms);
22895:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
22896:     my @locations = sort(keys(%by_location));
22897:     my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
22898:     my @types = ('exc','inc');
22899:     my (%defaultshash,%changes);
22900:     foreach my $prefix (@prefixes) {
22901:         $defaultshash{'trust'}{$prefix} = {};
22902:     }
22903:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
22904:     my $resulttext;
22905:     foreach my $prefix (@prefixes) {
22906:         foreach my $type (@types) {
22907:             my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
22908:             my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
22909:             my @okvals;
22910:             foreach my $val (@vals) {
22911:                 if ($val =~ /:/) {
22912:                     my @items = split(/:/,$val);
22913:                     foreach my $item (@items) {
22914:                         if (ref($by_location{$item}) eq 'ARRAY') {
22915:                             push(@okvals,$item);
22916:                         }
22917:                     }
22918:                 } else {
22919:                     if (ref($by_location{$val}) eq 'ARRAY') {
22920:                         push(@okvals,$val);
22921:                     }
22922:                 }
22923:             }
22924:             @okvals = sort(@okvals);
22925:             if (ref($domconfig{'trust'}) eq 'HASH') {
22926:                 if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
22927:                     if (ref($domconfig{'trust'}{$prefix}{$type}) eq 'ARRAY') {
22928:                         if ($inuse == 0) {
22929:                             $changes{$prefix}{$type} = 1;
22930:                         } else {
22931:                             $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
22932:                             my @changed = &Apache::loncommon::compare_arrays($domconfig{'trust'}{$prefix}{$type},$defaultshash{'trust'}{$prefix}{$type});
22933:                             if (@changed > 0) {
22934:                                 $changes{$prefix}{$type} = 1;
22935:                             }
22936:                         }
22937:                     } else {
22938:                         if ($inuse == 1) {
22939:                             $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
22940:                             $changes{$prefix}{$type} = 1;
22941:                         }
22942:                     }
22943:                 } else {
22944:                     if ($inuse == 1) {
22945:                         $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
22946:                         $changes{$prefix}{$type} = 1;
22947:                     }
22948:                 }
22949:             } else {
22950:                 if ($inuse == 1) {
22951:                     $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
22952:                     $changes{$prefix}{$type} = 1;
22953:                 }
22954:             }
22955:         }
22956:     }
22957:     my $nochgmsg = &mt('No changes made to trust settings.');
22958:     if (keys(%changes) > 0) {
22959:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
22960:                                                  $dom);
22961:         if ($putresult eq 'ok') {
22962:             if (ref($defaultshash{'trust'}) eq 'HASH') {
22963:                 foreach my $prefix (@prefixes) {
22964:                     if (ref($defaultshash{'trust'}{$prefix}) eq 'HASH') {
22965:                         $domdefaults{'trust'.$prefix} = $defaultshash{'trust'}{$prefix};
22966:                     }
22967:                 }
22968:             }
22969:             my $cachetime = 24*60*60;
22970:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
22971:             &Apache::lonnet::do_cache_new('trust',$dom,$defaultshash{'trust'},3600);
22972:             if (ref($lastactref) eq 'HASH') {
22973:                 $lastactref->{'domdefaults'} = 1;
22974:                 $lastactref->{'trust'} = 1;
22975:             }
22976:             if (keys(%changes) > 0) {
22977:                 my %lt = &trust_titles();
22978:                 $resulttext = &mt('Changes made:').'<ul>';
22979:                 foreach my $prefix (@prefixes) {
22980:                     if (ref($changes{$prefix}) eq 'HASH') {
22981:                         $resulttext .= '<li>'.$lt{$prefix}.'<ul>';
22982:                         foreach my $type (@types) {
22983:                             if (defined($changes{$prefix}{$type})) {
22984:                                 my ($newvalue,$notinuse);
22985:                                 if (ref($defaultshash{'trust'}) eq 'HASH') {
22986:                                     if (ref($defaultshash{'trust'}{$prefix})) {
22987:                                         if (ref($defaultshash{'trust'}{$prefix}{$type}) eq 'ARRAY') {
22988:                                             if (@{$defaultshash{'trust'}{$prefix}{$type}} > 0) {
22989:                                                 $newvalue = join(', ',@{$defaultshash{'trust'}{$prefix}{$type}});
22990:                                             }
22991:                                         } else {
22992:                                             $notinuse = 1;
22993:                                         }
22994:                                     }
22995:                                 }
22996:                                 if ($notinuse) {
22997:                                     $resulttext .= '<li>'.&mt('[_1] set to: not in use',$lt{$type}).'</li>';
22998:                                 } elsif ($newvalue eq '') {
22999:                                     $resulttext .= '<li>'.&mt('[_1] set to: none',$lt{$type}).'</li>';
23000:                                 } else {
23001:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$lt{$type},$newvalue).'</li>';
23002:                                 }
23003:                             }
23004:                         }
23005:                         $resulttext .= '</ul>';
23006:                     }
23007:                 }
23008:                 $resulttext .= '</ul>';
23009:             } else {
23010:                 $resulttext = $nochgmsg;
23011:             }
23012:         } else {
23013:             $resulttext = '<span class="LC_error">'.
23014:                           &mt('An error occurred: [_1]',$putresult).'</span>';
23015:         }
23016:     } else {
23017:         $resulttext = $nochgmsg;
23018:     }
23019:     return $resulttext;
23020: }
23021: 
23022: sub modify_loadbalancing {
23023:     my ($dom,%domconfig) = @_;
23024:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
23025:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
23026:     my ($othertitle,$usertypes,$types) =
23027:         &Apache::loncommon::sorted_inst_types($dom);
23028:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
23029:     my %libraryservers = &Apache::lonnet::get_servers($dom,'library');
23030:     my @sparestypes = ('primary','default');
23031:     my %typetitles = &sparestype_titles();
23032:     my $resulttext;
23033:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
23034:     if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
23035:         %existing = %{$domconfig{'loadbalancing'}};
23036:     }
23037:     &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
23038:                               \%currtargets,\%currrules,\%currcookies);
23039:     my ($saveloadbalancing,%defaultshash,%changes);
23040:     my ($alltypes,$othertypes,$titles) =
23041:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
23042:     my %ruletitles = &offloadtype_text();
23043:     my @deletions = &Apache::loncommon::get_env_multiple('form.loadbalancing_delete');
23044:     for (my $i=0; $i<$env{'form.loadbalancing_total'}; $i++) {
23045:         my $balancer = $env{'form.loadbalancing_lonhost_'.$i};
23046:         if ($balancer eq '') {
23047:             next;
23048:         }
23049:         if (!exists($servers{$balancer})) {
23050:             if (exists($currbalancer{$balancer})) {
23051:                 push(@{$changes{'delete'}},$balancer);
23052:             }
23053:             next;
23054:         }
23055:         if ((@deletions > 0) && (grep(/^\Q$i\E$/,@deletions))) {
23056:             push(@{$changes{'delete'}},$balancer);
23057:             next;
23058:         }
23059:         if (!exists($currbalancer{$balancer})) {
23060:             push(@{$changes{'add'}},$balancer);
23061:         }
23062:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'} = [];
23063:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'default'} = [];
23064:         $defaultshash{'loadbalancing'}{$balancer}{'rules'} = {};
23065:         unless (ref($domconfig{'loadbalancing'}) eq 'HASH') {
23066:             $saveloadbalancing = 1;
23067:         }
23068:         foreach my $sparetype (@sparestypes) {
23069:             my @targets = &Apache::loncommon::get_env_multiple('form.loadbalancing_target_'.$i.'_'.$sparetype);
23070:             my @offloadto;
23071:             foreach my $target (@targets) {
23072:                 if (($servers{$target}) && ($target ne $balancer)) {
23073:                     if ($sparetype eq 'default') {
23074:                         if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}) eq 'ARRAY') {
23075:                             next if (grep(/^\Q$target\E$/,@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}}));
23076:                         }
23077:                     }
23078:                     unless(grep(/^\Q$target\E$/,@offloadto)) {
23079:                         push(@offloadto,$target);
23080:                     }
23081:                 }
23082:             }
23083:             if ($env{'form.loadbalancing_target_'.$i.'_hosthere'} eq $sparetype) {
23084:                 unless(grep(/^\Q$balancer\E$/,@offloadto)) {
23085:                     push(@offloadto,$balancer);
23086:                 }
23087:             }
23088:             $defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype} = \@offloadto;
23089:         }
23090:         if ($env{'form.loadbalancing_cookie_'.$i}) {
23091:             $defaultshash{'loadbalancing'}{$balancer}{'cookie'} = 1;
23092:             if (exists($currbalancer{$balancer})) { 
23093:                 unless ($currcookies{$balancer}) {
23094:                     $changes{'curr'}{$balancer}{'cookie'} = 1;
23095:                 }
23096:             }
23097:         } elsif (exists($currbalancer{$balancer})) {
23098:             if ($currcookies{$balancer}) {
23099:                 $changes{'curr'}{$balancer}{'cookie'} = 1;
23100:             }
23101:         }
23102:         if (ref($currtargets{$balancer}) eq 'HASH') {
23103:             foreach my $sparetype (@sparestypes) {
23104:                 if (ref($currtargets{$balancer}{$sparetype}) eq 'ARRAY') {
23105:                     my @targetdiffs = &Apache::loncommon::compare_arrays($currtargets{$balancer}{$sparetype},$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype});
23106:                     if (@targetdiffs > 0) {
23107:                         $changes{'curr'}{$balancer}{'targets'} = 1;
23108:                     }
23109:                 } elsif (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
23110:                     if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
23111:                         $changes{'curr'}{$balancer}{'targets'} = 1;
23112:                     }
23113:                 }
23114:             }
23115:         } else {
23116:             if (ref($defaultshash{'loadbalancing'}{$balancer}) eq 'HASH') {
23117:                 foreach my $sparetype (@sparestypes) {
23118:                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
23119:                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
23120:                             $changes{'curr'}{$balancer}{'targets'} = 1;
23121:                         }
23122:                     }
23123:                 }
23124:             }
23125:         }
23126:         my $ishomedom;
23127:         if (&Apache::lonnet::host_domain($balancer) eq $dom) {
23128:             $ishomedom = 1;
23129:         }
23130:         if (ref($alltypes) eq 'ARRAY') {
23131:             foreach my $type (@{$alltypes}) {
23132:                 my $rule;
23133:                 unless ((($type eq '_LC_external') || ($type eq '_LC_internetdom')) &&
23134:                          (!$ishomedom)) {
23135:                     $rule = $env{'form.loadbalancing_rules_'.$i.'_'.$type};
23136:                 }
23137:                 if ($rule eq 'specific') {
23138:                     my $specifiedhost = $env{'form.loadbalancing_singleserver_'.$i.'_'.$type};
23139:                     if (exists($servers{$specifiedhost})) {
23140:                         $rule = $specifiedhost;
23141:                     }
23142:                 }
23143:                 $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type} = $rule;
23144:                 if (ref($currrules{$balancer}) eq 'HASH') {
23145:                     if ($rule ne $currrules{$balancer}{$type}) {
23146:                         $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
23147:                     }
23148:                 } elsif ($rule ne '') {
23149:                     $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
23150:                 }
23151:             }
23152:         }
23153:     }
23154:     my $nochgmsg = &mt('No changes made to Load Balancer settings.');
23155:     if ((keys(%changes) > 0) || ($saveloadbalancing)) {
23156:         unless (ref($defaultshash{'loadbalancing'}) eq 'HASH') {
23157:             $defaultshash{'loadbalancing'} = {};
23158:         }
23159:         my $putresult = &Apache::lonnet::put_dom('configuration',
23160:                                                  \%defaultshash,$dom);
23161:         if ($putresult eq 'ok') {
23162:             if (keys(%changes) > 0) {
23163:                 my %toupdate;
23164:                 if (ref($changes{'delete'}) eq 'ARRAY') {
23165:                     foreach my $balancer (sort(@{$changes{'delete'}})) {
23166:                         $resulttext .= '<li>'.&mt('Load Balancing discontinued for: [_1]',$balancer).'</li>';
23167:                         $toupdate{$balancer} = 1;
23168:                     }
23169:                 }
23170:                 if (ref($changes{'add'}) eq 'ARRAY') {
23171:                     foreach my $balancer (sort(@{$changes{'add'}})) {
23172:                         $resulttext .= '<li>'.&mt('Load Balancing enabled for: [_1]',$balancer);
23173:                         $toupdate{$balancer} = 1;
23174:                     }
23175:                 }
23176:                 if (ref($changes{'curr'}) eq 'HASH') {
23177:                     foreach my $balancer (sort(keys(%{$changes{'curr'}}))) {
23178:                         $toupdate{$balancer} = 1;
23179:                         if (ref($changes{'curr'}{$balancer}) eq 'HASH') {
23180:                             if ($changes{'curr'}{$balancer}{'targets'}) {
23181:                                 my %offloadstr;
23182:                                 foreach my $sparetype (@sparestypes) {
23183:                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
23184:                                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
23185:                                             $offloadstr{$sparetype} = join(', ',@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
23186:                                         }
23187:                                     }
23188:                                 }
23189:                                 if (keys(%offloadstr) == 0) {
23190:                                     $resulttext .= '<li>'.&mt("Servers to which Load Balance server offloads set to 'None', by default").'</li>';
23191:                                 } else {
23192:                                     my $showoffload;
23193:                                     foreach my $sparetype (@sparestypes) {
23194:                                         $showoffload .= '<i>'.$typetitles{$sparetype}.'</i>:&nbsp;';
23195:                                         if (defined($offloadstr{$sparetype})) {
23196:                                             $showoffload .= $offloadstr{$sparetype};
23197:                                         } else {
23198:                                             $showoffload .= &mt('None');
23199:                                         }
23200:                                         $showoffload .= ('&nbsp;'x3);
23201:                                     }
23202:                                     $resulttext .= '<li>'.&mt('By default, Load Balancer: [_1] set to offload to - [_2]',$balancer,$showoffload).'</li>';
23203:                                 }
23204:                             }
23205:                         }
23206:                         if (ref($changes{'curr'}{$balancer}{'rules'}) eq 'HASH') {
23207:                             if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH')) {
23208:                                 foreach my $type (@{$alltypes}) {
23209:                                     if ($changes{'curr'}{$balancer}{'rules'}{$type}) {
23210:                                         my $rule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
23211:                                         my $balancetext;
23212:                                         if ($rule eq '') {
23213:                                             $balancetext =  $ruletitles{'default'};
23214:                                         } elsif (($rule eq 'homeserver') || ($rule eq 'externalbalancer') ||
23215:                                                  ($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
23216:                                             if (($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
23217:                                                 foreach my $sparetype (@sparestypes) {
23218:                                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
23219:                                                         map { $toupdate{$_} = 1; } (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
23220:                                                     }
23221:                                                 }
23222:                                                 foreach my $item (@{$alltypes}) {
23223:                                                     next if ($item =~  /^_LC_ipchange/);
23224:                                                     my $hasrule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$item};
23225:                                                     if ($hasrule eq 'homeserver') {
23226:                                                         map { $toupdate{$_} = 1; } (keys(%libraryservers));
23227:                                                     } else {
23228:                                                         unless (($hasrule eq 'default') || ($hasrule eq 'none') || ($hasrule eq 'externalbalancer')) {
23229:                                                             if ($servers{$hasrule}) {
23230:                                                                 $toupdate{$hasrule} = 1;
23231:                                                             }
23232:                                                         }
23233:                                                     }
23234:                                                 }
23235:                                                 if (($rule eq 'balancer') || ($rule eq 'offloadedto')) {
23236:                                                     $balancetext =  $ruletitles{$rule};
23237:                                                 } else {
23238:                                                     my $receiver = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
23239:                                                     $balancetext = $ruletitles{'particular'}.' '.$receiver;
23240:                                                     if ($receiver) {
23241:                                                         $toupdate{$receiver};
23242:                                                     }
23243:                                                 }
23244:                                             } else {
23245:                                                 $balancetext =  $ruletitles{$rule};
23246:                                             }
23247:                                         } else {
23248:                                             $balancetext = &mt('offload to [_1]',$defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type});
23249:                                         }
23250:                                         $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- balancing for [_2] set to - "[_3]"',$balancer,$titles->{$type},$balancetext).'</li>';
23251:                                     }
23252:                                 }
23253:                             }
23254:                         }
23255:                         if ($changes{'curr'}{$balancer}{'cookie'}) {
23256:                             if ($currcookies{$balancer}) {
23257:                                 $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- cookie use disabled',
23258:                                                           $balancer).'</li>';
23259:                             } else {
23260:                                 $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- cookie use enabled',
23261:                                                           $balancer).'</li>';
23262:                             }
23263:                         }
23264:                     }
23265:                 }
23266:                 if (keys(%toupdate)) {
23267:                     my %thismachine;
23268:                     my $updatedhere;
23269:                     my $cachetime = 60*60*24;
23270:                     map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
23271:                     foreach my $lonhost (keys(%toupdate)) {
23272:                         if ($thismachine{$lonhost}) {
23273:                             unless ($updatedhere) {
23274:                                 &Apache::lonnet::do_cache_new('loadbalancing',$dom,
23275:                                                               $defaultshash{'loadbalancing'},
23276:                                                               $cachetime);
23277:                                 $updatedhere = 1;
23278:                             }
23279:                         } else {
23280:                             my $cachekey = &escape('loadbalancing').':'.&escape($dom);
23281:                             &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
23282:                         }
23283:                     }
23284:                 }
23285:                 if ($resulttext ne '') {
23286:                     $resulttext = &mt('Changes made:').'<ul>'.$resulttext.'</ul>';
23287:                 } else {
23288:                     $resulttext = $nochgmsg;
23289:                 }
23290:             } else {
23291:                 $resulttext = $nochgmsg;
23292:             }
23293:         } else {
23294:             $resulttext = '<span class="LC_error">'.
23295:                           &mt('An error occurred: [_1]',$putresult).'</span>';
23296:         }
23297:     } else {
23298:         $resulttext = $nochgmsg;
23299:     }
23300:     return $resulttext;
23301: }
23302: 
23303: sub recurse_check {
23304:     my ($chkcats,$categories,$depth,$name) = @_;
23305:     if (ref($chkcats->[$depth]{$name}) eq 'ARRAY') {
23306:         my $chg = 0;
23307:         for (my $j=0; $j<@{$chkcats->[$depth]{$name}}; $j++) {
23308:             my $category = $chkcats->[$depth]{$name}[$j];
23309:             my $item;
23310:             if ($category eq '') {
23311:                 $chg ++;
23312:             } else {
23313:                 my $deeper = $depth + 1;
23314:                 $item = &escape($category).':'.&escape($name).':'.$depth;
23315:                 if ($chg) {
23316:                     $categories->{$item} -= $chg;
23317:                 }
23318:                 &recurse_check($chkcats,$categories,$deeper,$category);
23319:                 $deeper --;
23320:             }
23321:         }
23322:     }
23323:     return;
23324: }
23325: 
23326: sub recurse_cat_deletes {
23327:     my ($item,$coursecategories,$deletions) = @_;
23328:     my ($deleted,$container,$depth) = map { &unescape($_); } split(/:/,$item);
23329:     my $subdepth = $depth + 1;
23330:     if (ref($coursecategories) eq 'HASH') {
23331:         foreach my $subitem (keys(%{$coursecategories})) {
23332:             my ($child,$parent,$itemdepth) = map { &unescape($_); } split(/:/,$subitem);
23333:             if (($parent eq $deleted) && ($itemdepth == $subdepth)) {
23334:                 delete($coursecategories->{$subitem});
23335:                 $deletions->{$subitem} = 1;
23336:                 &recurse_cat_deletes($subitem,$coursecategories,$deletions);
23337:             }
23338:         }
23339:     }
23340:     return;
23341: }
23342: 
23343: sub active_dc_picker {
23344:     my ($dom,$numinrow,$inputtype,$name,%currhash) = @_;
23345:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
23346:     my @domcoord = keys(%domcoords);
23347:     if (keys(%currhash)) {
23348:         foreach my $dc (keys(%currhash)) {
23349:             unless (exists($domcoords{$dc})) {
23350:                 push(@domcoord,$dc);
23351:             }
23352:         }
23353:     }
23354:     @domcoord = sort(@domcoord);
23355:     my $numdcs = scalar(@domcoord);
23356:     my $rows = 0;
23357:     my $table;
23358:     if ($numdcs > 1) {
23359:         $table = '<table>';
23360:         for (my $i=0; $i<@domcoord; $i++) {
23361:             my $rem = $i%($numinrow);
23362:             if ($rem == 0) {
23363:                 if ($i > 0) {
23364:                     $table .= '</tr>';
23365:                 }
23366:                 $table .= '<tr>';
23367:                 $rows ++;
23368:             }
23369:             my $check = '';
23370:             if ($inputtype eq 'radio') {
23371:                 if (keys(%currhash) == 0) {
23372:                     if (!$i) {
23373:                         $check = ' checked="checked"';
23374:                     }
23375:                 } elsif (exists($currhash{$domcoord[$i]})) {
23376:                     $check = ' checked="checked"';
23377:                 }
23378:             } else {
23379:                 if (exists($currhash{$domcoord[$i]})) {
23380:                     $check = ' checked="checked"';
23381:                 }
23382:             }
23383:             if ($i == @domcoord - 1) {
23384:                 my $colsleft = $numinrow - $rem;
23385:                 if ($colsleft > 1) {
23386:                     $table .= '<td class="LC_left_item" colspan="'.$colsleft.'">';
23387:                 } else {
23388:                     $table .= '<td class="LC_left_item">';
23389:                 }
23390:             } else {
23391:                 $table .= '<td class="LC_left_item">';
23392:             }
23393:             my ($dcname,$dcdom) = split(':',$domcoord[$i]);
23394:             my $user = &Apache::loncommon::plainname($dcname,$dcdom);
23395:             $table .= '<span class="LC_nobreak"><label>'.
23396:                       '<input type="'.$inputtype.'" name="'.$name.'"'.
23397:                       ' value="'.$domcoord[$i].'"'.$check.' />'.$user;
23398:             if ($user ne $dcname.':'.$dcdom) {
23399:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
23400:             }
23401:             $table .= '</label></span></td>';
23402:         }
23403:         $table .= '</tr></table>';
23404:     } elsif ($numdcs == 1) {
23405:         my ($dcname,$dcdom) = split(':',$domcoord[0]);
23406:         my $user = &Apache::loncommon::plainname($dcname,$dcdom);
23407:         if ($inputtype eq 'radio') {
23408:             $table = '<input type="hidden" name="'.$name.'" value="'.$domcoord[0].'" />'.$user;
23409:             if ($user ne $dcname.':'.$dcdom) {
23410:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
23411:             }
23412:         } else {
23413:             my $check;
23414:             if (exists($currhash{$domcoord[0]})) {
23415:                 $check = ' checked="checked"';
23416:             }
23417:             $table = '<span class="LC_nobreak"><label>'.
23418:                      '<input type="checkbox" name="'.$name.'" '.
23419:                      'value="'.$domcoord[0].'"'.$check.' />'.$user;
23420:             if ($user ne $dcname.':'.$dcdom) {
23421:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
23422:             }
23423:             $table .= '</label></span>';
23424:             $rows ++;
23425:         }
23426:     }
23427:     return ($numdcs,$table,$rows);
23428: }
23429: 
23430: sub usersession_titles {
23431:     return &Apache::lonlocal::texthash(
23432:                hosted => 'Hosting of sessions for users from other domains on servers in this domain',
23433:                remote => 'Hosting of sessions for users in this domain on servers in other domains',
23434:                spares => 'Servers offloaded to, when busy',
23435:                version => 'LON-CAPA version requirement',
23436:                excludedomain => 'Allow all, but exclude specific domains',
23437:                includedomain => 'Deny all, but include specific domains',
23438:                primary => 'Primary (checked first)',
23439:                default => 'Default',
23440:            );
23441: }
23442: 
23443: sub id_for_thisdom {
23444:     my (%servers) = @_;
23445:     my %altids;
23446:     foreach my $server (keys(%servers)) {
23447:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
23448:         if ($serverhome ne $server) {
23449:             $altids{$serverhome} = $server;
23450:         }
23451:     }
23452:     return %altids;
23453: }
23454: 
23455: sub count_servers {
23456:     my ($currbalancer,%servers) = @_;
23457:     my (@spares,$numspares);
23458:     foreach my $lonhost (sort(keys(%servers))) {
23459:         next if ($currbalancer eq $lonhost);
23460:         push(@spares,$lonhost);
23461:     }
23462:     if ($currbalancer) {
23463:         $numspares = scalar(@spares);
23464:     } else {
23465:         $numspares = scalar(@spares) - 1;
23466:     }
23467:     return ($numspares,@spares);
23468: }
23469: 
23470: sub lonbalance_targets_js {
23471:     my ($dom,$types,$servers,$settings) = @_;
23472:     my $select = &mt('Select');
23473:     my ($alltargets,$allishome,$allinsttypes,@alltypes);
23474:     if (ref($servers) eq 'HASH') {
23475:         $alltargets = join("','",sort(keys(%{$servers})));
23476:         my @homedoms;
23477:         foreach my $server (sort(keys(%{$servers}))) {
23478:             if (&Apache::lonnet::host_domain($server) eq $dom) {
23479:                 push(@homedoms,'1');
23480:             } else {
23481:                 push(@homedoms,'0');
23482:             }
23483:         }
23484:         $allishome = join("','",@homedoms);
23485:     }
23486:     if (ref($types) eq 'ARRAY') {
23487:         if (@{$types} > 0) {
23488:             @alltypes = @{$types};
23489:         }
23490:     }
23491:     push(@alltypes,'default','_LC_adv','_LC_author','_LC_internetdom','_LC_external');
23492:     $allinsttypes = join("','",@alltypes);
23493:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
23494:     if (ref($settings) eq 'HASH') {
23495:         %existing = %{$settings};
23496:     }
23497:     &get_loadbalancers_config($servers,\%existing,\%currbalancer,
23498:                               \%currtargets,\%currrules,\%currcookies);
23499:     my $balancers = join("','",sort(keys(%currbalancer)));
23500:     return <<"END";
23501: 
23502: <script type="text/javascript">
23503: // <![CDATA[
23504: 
23505: currBalancers = new Array('$balancers');
23506: 
23507: function toggleTargets(balnum) {
23508:     var lonhostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
23509:     var prevhostitem = document.getElementById('loadbalancing_prevlonhost_'+balnum);
23510:     var balancer = lonhostitem.options[lonhostitem.selectedIndex].value;
23511:     var prevbalancer = prevhostitem.value;
23512:     var baltotal = document.getElementById('loadbalancing_total').value;
23513:     prevhostitem.value = balancer;
23514:     if (prevbalancer != '') {
23515:         var prevIdx = currBalancers.indexOf(prevbalancer);
23516:         if (prevIdx != -1) {
23517:             currBalancers.splice(prevIdx,1);
23518:         }
23519:     }
23520:     if (balancer == '') {
23521:         hideSpares(balnum);
23522:     } else {
23523:         var currIdx = currBalancers.indexOf(balancer);
23524:         if (currIdx == -1) {
23525:             currBalancers.push(balancer);
23526:         }
23527:         var homedoms = new Array('$allishome');
23528:         var ishomedom = homedoms[lonhostitem.selectedIndex];
23529:         showSpares(balancer,ishomedom,balnum);
23530:     }
23531:     balancerChange(balnum,baltotal,'change',prevbalancer,balancer);
23532:     return;
23533: }
23534: 
23535: function showSpares(balancer,ishomedom,balnum) {
23536:     var alltargets = new Array('$alltargets');
23537:     var insttypes = new Array('$allinsttypes');
23538:     var offloadtypes = new Array('primary','default');
23539: 
23540:     document.getElementById('loadbalancing_targets_'+balnum).style.display='block';
23541:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='none';
23542:  
23543:     for (var i=0; i<offloadtypes.length; i++) {
23544:         var count = 0;
23545:         for (var j=0; j<alltargets.length; j++) {
23546:             if (alltargets[j] != balancer) {
23547:                 var item = document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+count);
23548:                 item.value = alltargets[j];
23549:                 item.style.textAlign='left';
23550:                 item.style.textFace='normal';
23551:                 document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+count).innerHTML = alltargets[j];
23552:                 if (currBalancers.indexOf(alltargets[j]) == -1) {
23553:                     item.disabled = '';
23554:                 } else {
23555:                     item.disabled = 'disabled';
23556:                     item.checked = false;
23557:                 }
23558:                 count ++;
23559:             }
23560:         }
23561:     }
23562:     for (var k=0; k<insttypes.length; k++) {
23563:         if ((insttypes[k] == '_LC_external') || (insttypes[k] == '_LC_internetdom')) {
23564:             if (ishomedom == 1) {
23565:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
23566:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
23567:             } else {
23568:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
23569:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
23570:             }
23571:         } else {
23572:             document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
23573:             document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
23574:         }
23575:         if ((insttypes[k] != '_LC_external') && 
23576:             ((insttypes[k] != '_LC_internetdom') ||
23577:              ((insttypes[k] == '_LC_internetdom') && (ishomedom == 1)))) {
23578:             var item = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]);
23579:             item.options.length = 0;
23580:             item.options[0] = new Option("","",true,true);
23581:             var idx = 0;
23582:             for (var m=0; m<alltargets.length; m++) {
23583:                 if ((currBalancers.indexOf(alltargets[m]) == -1) && (alltargets[m] != balancer)) {
23584:                     idx ++;
23585:                     item.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
23586:                 }
23587:             }
23588:         }
23589:     }
23590:     return;
23591: }
23592: 
23593: function hideSpares(balnum) {
23594:     var alltargets = new Array('$alltargets');
23595:     var insttypes = new Array('$allinsttypes');
23596:     var offloadtypes = new Array('primary','default');
23597: 
23598:     document.getElementById('loadbalancing_targets_'+balnum).style.display='none';
23599:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='block';
23600: 
23601:     var total = alltargets.length - 1;
23602:     for (var i=0; i<offloadtypes; i++) {
23603:         for (var j=0; j<total; j++) {
23604:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).checked = false;
23605:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).value = '';
23606:            document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+j).innerHTML = '';
23607:         }
23608:     }
23609:     for (var k=0; k<insttypes.length; k++) {
23610:         document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
23611:         document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
23612:         if (insttypes[k] != '_LC_external') {
23613:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).length = 0;
23614:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).options[0] = new Option("","",true,true);
23615:         }
23616:     }
23617:     return;
23618: }
23619: 
23620: function checkOffloads(item,balnum,type) {
23621:     var alltargets = new Array('$alltargets');
23622:     var offloadtypes = new Array('primary','default');
23623:     if (item.checked) {
23624:         var total = alltargets.length - 1;
23625:         var other;
23626:         if (type == offloadtypes[0]) {
23627:             other = offloadtypes[1];
23628:         } else {
23629:             other = offloadtypes[0];
23630:         }
23631:         for (var i=0; i<total; i++) {
23632:             var server = document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).value;
23633:             if (server == item.value) {
23634:                 if (document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked) {
23635:                     document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked = false;
23636:                 }
23637:             }
23638:         }
23639:     }
23640:     return;
23641: }
23642: 
23643: function singleServerToggle(balnum,type) {
23644:     var offloadtoSelIdx = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex;
23645:     if (offloadtoSelIdx == 0) {
23646:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_0').checked = true;
23647:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
23648: 
23649:     } else {
23650:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_2').checked = true;
23651:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
23652:     }
23653:     return;
23654: }
23655: 
23656: function balanceruleChange(formname,balnum,type) {
23657:     if (type == '_LC_external') {
23658:         return;
23659:     }
23660:     var typesRules = getIndicesByName(formname,'loadbalancing_rules_'+balnum+'_'+type);
23661:     for (var i=0; i<typesRules.length; i++) {
23662:         if (formname.elements[typesRules[i]].checked) {
23663:             if (formname.elements[typesRules[i]].value != 'specific') {
23664:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex = 0;
23665:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
23666:             } else {
23667:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
23668:             }
23669:         }
23670:     }
23671:     return;
23672: }
23673: 
23674: function balancerDeleteChange(balnum) {
23675:     var hostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
23676:     var baltotal = document.getElementById('loadbalancing_total').value;
23677:     var addtarget;
23678:     var removetarget;
23679:     var action = 'delete';
23680:     if (document.getElementById('loadbalancing_delete_'+balnum)) {
23681:         var lonhost = hostitem.value;
23682:         var currIdx = currBalancers.indexOf(lonhost);
23683:         if (document.getElementById('loadbalancing_delete_'+balnum).checked) {
23684:             if (currIdx != -1) {
23685:                 currBalancers.splice(currIdx,1);
23686:             }
23687:             addtarget = lonhost;
23688:         } else {
23689:             if (currIdx == -1) {
23690:                 currBalancers.push(lonhost);
23691:             }
23692:             removetarget = lonhost;
23693:             action = 'undelete';
23694:         }
23695:         balancerChange(balnum,baltotal,action,addtarget,removetarget);
23696:     }
23697:     return;
23698: }
23699: 
23700: function balancerChange(balnum,baltotal,action,addtarget,removetarget) {
23701:     if (baltotal > 1) {
23702:         var offloadtypes = new Array('primary','default');
23703:         var alltargets = new Array('$alltargets');
23704:         var insttypes = new Array('$allinsttypes');
23705:         for (var i=0; i<baltotal; i++) {
23706:             if (i != balnum) {
23707:                 for (var j=0; j<offloadtypes.length; j++) {
23708:                     var total = alltargets.length - 1;
23709:                     for (var k=0; k<total; k++) {
23710:                         var serveritem = document.getElementById('loadbalancing_target_'+i+'_'+offloadtypes[j]+'_'+k);
23711:                         var server = serveritem.value;
23712:                         if ((action == 'delete') || (action == 'change' && addtarget != ''))  {
23713:                             if (server == addtarget) {
23714:                                 serveritem.disabled = '';
23715:                             }
23716:                         }
23717:                         if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
23718:                             if (server == removetarget) {
23719:                                 serveritem.disabled = 'disabled';
23720:                                 serveritem.checked = false;
23721:                             }
23722:                         }
23723:                     }
23724:                 }
23725:                 for (var j=0; j<insttypes.length; j++) {
23726:                     if (insttypes[j] != '_LC_external') {
23727:                         if (document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j])) {
23728:                             var singleserver = document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j]);
23729:                             var currSel = singleserver.selectedIndex;
23730:                             var currVal = singleserver.options[currSel].value;
23731:                             if ((action == 'delete') || (action == 'change' && addtarget != '')) {
23732:                                 var numoptions = singleserver.options.length;
23733:                                 var needsnew = 1;
23734:                                 for (var k=0; k<numoptions; k++) {
23735:                                     if (singleserver.options[k] == addtarget) {
23736:                                         needsnew = 0;
23737:                                         break;
23738:                                     }
23739:                                 }
23740:                                 if (needsnew == 1) {
23741:                                     singleserver.options[numoptions] = new Option(addtarget,addtarget,false,false);
23742:                                 }
23743:                             }
23744:                             if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
23745:                                 singleserver.options.length = 0;
23746:                                 if ((currVal) && (currVal != removetarget)) {
23747:                                     singleserver.options[0] = new Option("","",false,false);
23748:                                 } else {
23749:                                     singleserver.options[0] = new Option("","",true,true);
23750:                                 }
23751:                                 var idx = 0;
23752:                                 for (var m=0; m<alltargets.length; m++) {
23753:                                     if (currBalancers.indexOf(alltargets[m]) == -1) {
23754:                                         idx ++;
23755:                                         if (currVal == alltargets[m]) {
23756:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],true,true);
23757:                                         } else {
23758:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
23759:                                         }
23760:                                     }
23761:                                 }
23762:                             }
23763:                         }
23764:                     }
23765:                 }
23766:             }
23767:         }
23768:     }
23769:     return;
23770: }
23771: 
23772: // ]]>
23773: </script>
23774: 
23775: END
23776: }
23777: 
23778: 
23779: sub new_spares_js {
23780:     my @sparestypes = ('primary','default');
23781:     my $types = join("','",@sparestypes);
23782:     my $select = &mt('Select');
23783:     return <<"END";
23784: 
23785: <script type="text/javascript">
23786: // <![CDATA[
23787: 
23788: function updateNewSpares(formname,lonhost) {
23789:     var types = new Array('$types');
23790:     var include = new Array();
23791:     var exclude = new Array();
23792:     for (var i=0; i<types.length; i++) {
23793:         var spareboxes = getIndicesByName(formname,'spare_'+types[i]+'_'+lonhost);
23794:         for (var j=0; j<spareboxes.length; j++) {
23795:             if (formname.elements[spareboxes[j]].checked) {
23796:                 exclude.push(formname.elements[spareboxes[j]].value);
23797:             } else {
23798:                 include.push(formname.elements[spareboxes[j]].value);
23799:             }
23800:         }
23801:     }
23802:     for (var i=0; i<types.length; i++) {
23803:         var newSpare = document.getElementById('newspare_'+types[i]+'_'+lonhost);
23804:         var selIdx = newSpare.selectedIndex;
23805:         var currnew = newSpare.options[selIdx].value;
23806:         var okSpares = new Array();
23807:         for (var j=0; j<newSpare.options.length; j++) {
23808:             var possible = newSpare.options[j].value;
23809:             if (possible != '') {
23810:                 if (exclude.indexOf(possible) == -1) {
23811:                     okSpares.push(possible);
23812:                 } else {
23813:                     if (currnew == possible) {
23814:                         selIdx = 0;
23815:                     }
23816:                 }
23817:             }
23818:         }
23819:         for (var k=0; k<include.length; k++) {
23820:             if (okSpares.indexOf(include[k]) == -1) {
23821:                 okSpares.push(include[k]);
23822:             }
23823:         }
23824:         okSpares.sort();
23825:         newSpare.options.length = 0;
23826:         if (selIdx == 0) {
23827:             newSpare.options[0] = new Option("$select","",true,true);
23828:         } else {
23829:             newSpare.options[0] = new Option("$select","",false,false);
23830:         }
23831:         for (var m=0; m<okSpares.length; m++) {
23832:             var idx = m+1;
23833:             var selThis = 0;
23834:             if (selIdx != 0) {
23835:                 if (okSpares[m] == currnew) {
23836:                     selThis = 1;
23837:                 }
23838:             }
23839:             if (selThis == 1) {
23840:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],true,true);
23841:             } else {
23842:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],false,false);
23843:             }
23844:         }
23845:     }
23846:     return;
23847: }
23848: 
23849: function checkNewSpares(lonhost,type) {
23850:     var newSpare = document.getElementById('newspare_'+type+'_'+lonhost);
23851:     var chosen =  newSpare.options[newSpare.selectedIndex].value;
23852:     if (chosen != '') {
23853:         var othertype;
23854:         var othernewSpare;
23855:         if (type == 'primary') {
23856:             othernewSpare = document.getElementById('newspare_default_'+lonhost);
23857:         }
23858:         if (type == 'default') {
23859:             othernewSpare = document.getElementById('newspare_primary_'+lonhost);
23860:         }
23861:         if (othernewSpare.options[othernewSpare.selectedIndex].value == chosen) {
23862:             othernewSpare.selectedIndex = 0;
23863:         }
23864:     }
23865:     return;
23866: }
23867: 
23868: // ]]>
23869: </script>
23870: 
23871: END
23872: 
23873: }
23874: 
23875: sub common_domprefs_js {
23876:     return <<"END";
23877: 
23878: <script type="text/javascript">
23879: // <![CDATA[
23880: 
23881: function getIndicesByName(formname,item) {
23882:     var group = new Array();
23883:     for (var i=0;i<formname.elements.length;i++) {
23884:         if (formname.elements[i].name == item) {
23885:             group.push(formname.elements[i].id);
23886:         }
23887:     }
23888:     return group;
23889: }
23890: 
23891: // ]]>
23892: </script>
23893: 
23894: END
23895: 
23896: }
23897: 
23898: sub recaptcha_js {
23899:     my %lt = &captcha_phrases();
23900:     return <<"END";
23901: 
23902: <script type="text/javascript">
23903: // <![CDATA[
23904: 
23905: function updateCaptcha(caller,context) {
23906:     var privitem;
23907:     var pubitem;
23908:     var privtext;
23909:     var pubtext;
23910:     var versionitem;
23911:     var versiontext;
23912:     if (document.getElementById(context+'_recaptchapub')) {
23913:         pubitem = document.getElementById(context+'_recaptchapub');
23914:     } else {
23915:         return;
23916:     }
23917:     if (document.getElementById(context+'_recaptchapriv')) {
23918:         privitem = document.getElementById(context+'_recaptchapriv');
23919:     } else {
23920:         return;
23921:     }
23922:     if (document.getElementById(context+'_recaptchapubtxt')) {
23923:         pubtext = document.getElementById(context+'_recaptchapubtxt');
23924:     } else {
23925:         return;
23926:     }
23927:     if (document.getElementById(context+'_recaptchaprivtxt')) {
23928:         privtext = document.getElementById(context+'_recaptchaprivtxt');
23929:     } else {
23930:         return;
23931:     }
23932:     if (document.getElementById(context+'_recaptchaversion')) {
23933:         versionitem = document.getElementById(context+'_recaptchaversion');
23934:     } else {
23935:         return;
23936:     }
23937:     if (document.getElementById(context+'_recaptchavertxt')) {
23938:         versiontext = document.getElementById(context+'_recaptchavertxt');
23939:     } else {
23940:         return;
23941:     }
23942:     if (caller.checked) {
23943:         if (caller.value == 'recaptcha') {
23944:             pubitem.type = 'text';
23945:             privitem.type = 'text';
23946:             pubitem.size = '40';
23947:             privitem.size = '40';
23948:             pubtext.innerHTML = "$lt{'pub'}";
23949:             privtext.innerHTML = "$lt{'priv'}";
23950:             versionitem.type = 'text';
23951:             versionitem.size = '3';
23952:             versiontext.innerHTML = "$lt{'ver'}";
23953:         } else {
23954:             pubitem.type = 'hidden';
23955:             privitem.type = 'hidden';
23956:             versionitem.type = 'hidden';
23957:             pubtext.innerHTML = '';
23958:             privtext.innerHTML = '';
23959:             versiontext.innerHTML = '';
23960:         }
23961:     }
23962:     return;
23963: }
23964: 
23965: // ]]>
23966: </script>
23967: 
23968: END
23969: 
23970: }
23971: 
23972: sub toggle_display_js {
23973:     return <<"END";
23974: 
23975: <script type="text/javascript">
23976: // <![CDATA[
23977: 
23978: function toggleDisplay(domForm,caller) {
23979:     if (document.getElementById(caller)) {
23980:         var divitem = document.getElementById(caller);
23981:         var optionsElement = domForm.coursecredits;
23982:         var checkval = 1;
23983:         var dispval = 'block';
23984:         var selfcreateRegExp = /^cancreate_emailverified/;
23985:         if (caller == 'emailoptions') {
23986:             optionsElement = domForm.cancreate_email;
23987:         }
23988:         if (caller == 'studentsubmission') {
23989:             optionsElement = domForm.postsubmit;
23990:         }
23991:         if (caller == 'cloneinstcode') {
23992:             optionsElement = domForm.canclone;
23993:             checkval = 'instcode';
23994:         }
23995:         if (selfcreateRegExp.test(caller)) {
23996:             optionsElement = domForm.elements[caller];
23997:             checkval = 'other';
23998:             dispval = 'inline'
23999:         }
24000:         if (optionsElement.length) {
24001:             var currval;
24002:             for (var i=0; i<optionsElement.length; i++) {
24003:                 if (optionsElement[i].checked) {
24004:                    currval = optionsElement[i].value;
24005:                 }
24006:             }
24007:             if (currval == checkval) {
24008:                 divitem.style.display = dispval;
24009:             } else {
24010:                 divitem.style.display = 'none';
24011:             }
24012:         }
24013:     }
24014:     return;
24015: }
24016: 
24017: // ]]>
24018: </script>
24019: 
24020: END
24021: 
24022: }
24023: 
24024: sub captcha_phrases {
24025:     return &Apache::lonlocal::texthash (
24026:                  priv => 'Private key',
24027:                  pub  => 'Public key',
24028:                  original  => 'original (CAPTCHA)',
24029:                  recaptcha => 'successor (ReCAPTCHA)',
24030:                  notused   => 'unused',
24031:                  ver => 'ReCAPTCHA version (1 or 2)',
24032:     );
24033: }
24034: 
24035: sub devalidate_remote_domconfs {
24036:     my ($dom,$cachekeys) = @_;
24037:     return unless (ref($cachekeys) eq 'HASH');
24038:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
24039:     my %thismachine;
24040:     map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
24041:     my @posscached = ('domainconfig','domdefaults','ltitools','usersessions',
24042:                       'directorysrch','passwdconf','cats','proxyalias','proxysaml',
24043:                       'ipaccess','trust');
24044:     my %cache_by_lonhost;
24045:     if (exists($cachekeys->{'samllanding'})) {
24046:         if (ref($cachekeys->{'samllanding'}) eq 'HASH') {
24047:             my %landing = %{$cachekeys->{'samllanding'}};
24048:             my %domservers = &Apache::lonnet::get_servers($dom);
24049:             if (keys(%domservers)) {
24050:                 foreach my $server (keys(%domservers)) {
24051:                     my @cached;
24052:                     next if ($thismachine{$server});
24053:                     if ($landing{$server}) {
24054:                         push(@cached,&escape('samllanding').':'.&escape($server));
24055:                     }
24056:                     if (@cached) {
24057:                         $cache_by_lonhost{$server} = \@cached;
24058:                     }
24059:                 }
24060:             }
24061:         }
24062:     }
24063:     if (keys(%servers)) {
24064:         foreach my $server (keys(%servers)) {
24065:             next if ($thismachine{$server});
24066:             my @cached;
24067:             foreach my $name (@posscached) {
24068:                 if ($cachekeys->{$name}) {
24069:                     if (($name eq 'proxyalias') || ($name eq 'proxysaml')) {
24070:                         if (ref($cachekeys->{$name}) eq 'HASH') {
24071:                             foreach my $key (keys(%{$cachekeys->{$name}})) {
24072:                                 push(@cached,&escape($name).':'.&escape($key));
24073:                             }
24074:                         }
24075:                     } else {
24076:                         push(@cached,&escape($name).':'.&escape($dom));
24077:                     }
24078:                 }
24079:             }
24080:             if ((exists($cache_by_lonhost{$server})) &&
24081:                 (ref($cache_by_lonhost{$server}) eq 'ARRAY')) {
24082:                 push(@cached,@{$cache_by_lonhost{$server}});
24083:             }
24084:             if (@cached) {
24085:                 &Apache::lonnet::remote_devalidate_cache($server,\@cached);
24086:             }
24087:         }
24088:     }
24089:     return;
24090: }
24091: 
24092: 1;

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